67% menganggap dokumen ini bermanfaat (3 suara)
355 tayangan

Arduino Projects For Beginners

Proyek ini menjelaskan cara mengendalikan dua motor DC menggunakan modul L298N dual H-bridge motor controller pada Arduino. Program yang disajikan memungkinkan pengendalian motor secara manual menggunakan keyboard.
Hak Cipta
© © All Rights Reserved
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
67% menganggap dokumen ini bermanfaat (3 suara)
355 tayangan

Arduino Projects For Beginners

Proyek ini menjelaskan cara mengendalikan dua motor DC menggunakan modul L298N dual H-bridge motor controller pada Arduino. Program yang disajikan memungkinkan pengendalian motor secara manual menggunakan keyboard.
Hak Cipta
© © All Rights Reserved
Format Tersedia
Unduh sebagai PDF, TXT atau baca online di Scribd
Anda di halaman 1/ 1039

PROYEK MICRO-CONTROLLER BERBASIS ARDUINO TINGKAT PEMULA

Tulisan ini ditujukan kepada penggemar micro controller berbasis arduino tingkat pemula. Semua
materi adalah rangkuman dari berbagai sumber, kemudian dilakukan pengujian dan modifikasi.
Pengetahuan ini diperuntukkan untuk tujuan kebaikan, penerapan untuk tujuan-tujuan kejahatan
diluar tanggung jawab penyusun.
DAFTAR ISI

1. MOTOR DC DENGAN L298N DUAL H-BRIDGE MOTOR CONTROLLER


2. MOTOR DC L298N DUAL H-BRIDGE MOTOR CONTROL BY KEYBOARD
3. KONTROL SERVO MOTOR DENGAN POTENSIOMETER
4. DHT11 ARDUINO
5. DHT22 ARDUINO
6. PRESSURE BAROMETER BMP 180
7. PRESSURE BAROMETER BMP 280
8. STEPPER MOTOR 28BYJ-48 WITH L293D CONTROLLED BY KEYBOARD
9. PUSH BUTTON IR REMOTE
10. LIFT 3 FLOOR
11. SWITCH OTOMATIS POMPA AIR DENGAN SENSOR KAPASITIF
12. ALAT PENGUJI WEATHERING LPG
13. SWITCH OTOMATIS POMPA AIR DENGAN SENSOR CONDUCTIVITY
14. SETUP LCD 16X2
15. GENERATOR NADA
16. MEMBACA TEGANGAN 5V
17. SETUP RTC
18. ALARM NADA
19. SETUP ULTRASONIC DISTANCE SENSOR
20. PEMBACA KODE REMOTE INFRA RED
21. MENYALAKAN LAMPU LED DENGAN IR REMOTE
22. PENGUKURAN SUHU DENGAN LM35
23. SETUP MICRO SD ARDUINO
24. LDR ARDUINO
25. MENGENDALIKAN LAMPU LED DENGAN LDR
26. MENGUKUR TEGANGAN
27. SETUP LCD I2C
28. LED ON ARDUINO
29. MULTI LED
30. KAPASITIF SENSOR
31. LED PETERN DENGAN SHIFT REGISTER IC 74HC595
32. LED MATRIX MAPPING
33. LED MATRIX
34. JAM-SUHU-KELEMBABAN-LED MATRIX
35. LED MATRIX MAX7219
36. LED MATRIX MAX7219 TANPA SHIFTING
37. LED MATRIX MAX7219 DENGAN SHIFTING
38. LED MATRIX MAX7219 (MENGHITUNG DETIK)
39. PIN PWM
40. SOFT PWM
41. KONTROL SERVO MOTOR DENGAN POTENSIOMETER
42. DC FAN SPEED CONTROL
43. MENGUKUR KUAT ARUS
44. PUSH BUTTON
45. COUNTER
46. CONTER DENGAN LED MATRIX DISPLAY
47. PENGHITUNG RAKAAT SHOLAT
48. DC MOTOR SHIELD
49. MOTOR SHIELD TEST-1
50. MOTOR SHIELD TEST-2
51. RUN MOTOR SHIELD BY KEYBOARD
52. MOTOR SHIELD DENGAN VOID
53. MENGENDALIKAN MOTOR SERVO DENGAN IR REMOTE
54. PENGUKURAN SUHU DENGAN SENSOR PT-100
55. MENGATUR KECERAHAN LED DENGAN PUSH BUTTON
56. MENGATUR LAJU FAN DENGAN PUSH BUTTON
57. SETTING LAJU FAN DENGAN EEPROM
58. SETUP LCD MENGGUNAKAN IC 74HC595
59. ACCELEROMETER MPU 6050
60. ALARM GEMPA BUMI
61. MENGENDALIKAN ARAH DAN LAJU PUTARAN MOTOR DENGAN MPU
62. CONTINOUS SERVO MOTOR
63. RF CONTROL 433 MHz
64. RF RC-SWITCH
65. KONTROL RF DENGAN KEYBOARD
66. ACCELEROMETER MMA7455
67. MP3 SHIELD
68. THERMOCOUPLE
69. MENGUKUR SUDUT MEMUTAR DENGAN MPU6050
70. MENGUKUR SUDUT MEMUTAR DENGAN MPU6050 (IR RESET)
71. MENGENDALIKAN CONTINOUS MOTOR SERVO DENGAN IR REMOTE
72. MENGENDALIKAN CONTINOUS MOTOR SERVO DENGAN MPU DAN IR REMOTE
73. WATERING PLANT
74. RAIN DETECTOR
75. PIR SENSOR
76. SAKLAR SENTUH
77. SENSOR INFRAMERAH
78. PENGUKURAN TEGANGAN DC, KUAT ARUS, DAYA
79. ETHERNET SHIELD
80. MENYALAKAN LED VIA BROWSER
81. SWITCH LED DAN SERVO MOTOR VIA HTML
82. MEMBACA INPUT ANALOG VIA BROWSER
83. ETHERNET SHIELD MULTI SWITCH
84. ETHERNET SHIELD MULTI SWITCH DENGAN TELNET
85. MAGNETOMETER HMC5883L
86. ACCELEROMETER GY-61
87. SEND DATA VIA BLUETOOTH
88. SERVO MOTOR
89. SONAR ARDUINO
90. WATERBATH
91. WATERBATH REMOTE CONTROLLED
92. SWITCH VIA BLUETOOTH
93. GAS SENSOR MQ135
94. KEYPAD 4x4
95. KEYPAD SWITCH
96. RF REMOTE SWITCH
97. CALCULATOR
98. HALL PROXIMITY SENSOR
99. SERVO SERIAL CONTROLED
100. SERVO CONTROL VIA BLUETOOTH
101. SERIAL MONITOR TO LCD
102. SERIAL MONITOR TO LCD WITH SCHROLL
103. PESAN 63 HURUF
104. MATRIX-RTC-DHT22-EEPROM
105. KEYPAD LOCK PASSWORD
106. WIRELESS RF TEMPERATUR AND RH
107. SEND ANALOG DATA VIA RF
108. CONTROL LED BRIGHNESS VIA IR REMOTE
109. DC FAN SPEED CONTROL BY IR REMOTE
110. CONTROL KECERAHAN LED BY LDR
111. CONTROL LED BRIGHNESS BY SERIAL
112. EEPROM BIG NUMBER AND PWM SETTING
113. MOTOR SPEED MEASUREMENT
114. SPEED CONTROL BY SERIAL
115. SPEED CONTROL DC MOTOR WITH SPEED SENSOR
116. PASSWORD KEYPAD WITH I2C LCD
117. SEND CHARACTER VIA RF
118. SEVEN SEGMENT
119. SEVEN SEGMENT DATA DISPLAY
120. SERIAL MONITOR TO SEVEN SEG DISPLAY
121. ANALOG DATA TO MATRIX DISPLAY
122. ULTRASONIC SENSOR WITH LED MATRIX
123. SEND ANALOG DATA TO MATRIX DISPL VIA RF
124. BODY HEIGHT MEASUREMENT BY ULTRASONIC VIA RF
125. DHT 22 WITH LED MATRIX-RTC
126. CONTROL SERVO BY MOUSE
127. SETUP BLUETOOTH MODULE AS MASTER OR SLAVE
128. SEND ANALOG DATA ARDUINO TO ARDUINO VIA BLUETOOTH
129. CONTROL SERVO VIA BLUETOOTH
130. SEND ANALOG DATA ARDUINO TO ARDUINO VIA BLUETOOTH BY LED MATRIX
131. BODY HEIGHT MEASUREMENT BY ULTRASONIC VIA BLUETOOTH
132. PIR ALARM VIA RF
133. RFID READ CODE
134. RFID LIGHT SWITCH
135. RFID ROOM POWER SWITCH
136. RFID ROOM DOOR KEY
137. LED LEVEL INDICATOR
138. LED BAR LEVEL INDICATOR
139. OSCILOSCOPE
140. WRITING STRING ON EEPROM VIA SERIAL MONITOR
141. WRITING STRING VIA SERIAL MONITOR
142. POWER SWITCH WITH MOC3011 AND BT136
143. CONTACTLESS THERMOMETER MLX90614
144. CAR POWER LOCK
145. RFID 125kHz CODE READING
146. RFID 125kHz CODE READING WITH RX PIN
147. RFID POWER SWITCH
148. RF24 LIGHT SWITCH
149. RF24 PIR ALARM
150. RF24 SERVO
151. RF24 TEST RUN
152. RF24 ANALOG DATA
153. LED BAR INDICATOR TLC5940
154. TLC5940 LED ANIMATION
155. TLC5940 LED SHIFT
156. TCL5940 LED BLINK
157. TCL5940 ONE LED FADE
158. TCL5940 ALL LED FADE
159. RF24 TWO ANALOG DATA TRANSFER
160. TLC5940 TWO CASCADE
161. 32 LED LEVEL INDICATOR TLC5940
162. RGB LED COMMON CATHODE
163. LIGHT INTENSITY BH1750
164. RF24 EARTHQUAKE ALARM
165. RF24 DHT22
166. AMBIENT WEATHER MONITORING
167. WEATHER MONITORING DHT11
168. LED PETERN SELECT BY IR REMOTE
169. SWITCH AC LAMP BY IR REMOTE
170. TLC5940 RGB LED COMMON ANODE
171. RGB WHEEL
172. SEVEN SEGMENT MODULE 4 DIGIT COMMON ANODE
173. ANALOG ON SEVEN SEGMENT
174. LIGHTNING COUNTER
175. LIGHTNING COUNTER WITH LED DISPLAY
176. CALL WITH A6 GSM MODULE
177. PIR ALARM WITH A6 GSM MODULE
178. PIR ALARM WITH A6 SERIAL SOFTWARE
179. LED SWITCH WITH GSM CALL
180. POWER LOCK BY GSM
181. FLAME DETECTOR WITH RF24
182. ALARM GEMPA BUMI ADXL355
183. IR DISTANCE SENSOR
184. STEPPER MOTOR WITH ULN2003
185. CONTINUES STEPPER MOTOR WITH ULN2003
186. CONTINUES TWO STEPPER MOTOR WITH ULN2003
187. TWO STEPPER MOTOR COTROLLED BY IR DISTANCE
188. PROPORTIONAL CONTROL STEPPER BY IR DISTANCE
189. CONTROL STEPPER BY ROTARY ENCODER
191. CONTROL STEPPER IR REMOTE
192. STEPPER ROTATION SQUENCE
193. LIGHTNING COUNTER WITH 595 LED DISPLAY
194. PUSH BUTTON COUNTER WITH 595 LED DISPLAY
195. CONTROL STEPPER BY POTENSIOMETER
196. LIGHT SOURCE FOLLOWER
197. SOLAR PANEL ALIGNMENT
198. TOUCHLESS LAMP SWITCH
199. VIBRATION SENSOR SW 420
200. KNOCK SWITCH WITH SENSOR SW 420
201. SPEED RADIAN WITH HALL SENSOR
202. ANALOG READ WITH 595 LED DISPLAY
203. LAMP TIMER WITH RTC
204. VIBRATION DETECTOR ADXL355
205. DIGITAL CLOCK
206. STAIR LIGHT
207. DIGITAL CLOCK LED MATRIX
208. GPS RECEIVER
1. MOTOR DC DENGAN L298N DUAL H-BRIDGE MOTOR CONTROLLER

Pada proyek ini kita sajikan penginstalan module L298N pada arduino. Kita menggunakan dua
motor DC, modul ini dapat dipasang dengan dua motor maksimum. Program yang kita sajikan
adalah modifikasi dari progran yang dibuat oleh Reichenstein.

//Code by Reichenstein7 (thejamerson.com)

// 1 -Motor 1 Left
// 2 -Motor 1 Stop
// 3 -Motor 1 Right
//
// 4 -Motor 2 Left
// 5 -Motor 2 Stop
// 6 -Motor 2 Right

// Declare L298N Dual H-Bridge Motor Controller directly since there is not a library to load.

// Motor 1
int dir1PinA = 2;
int dir2PinA = 3;
int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed

// Motor 2
int dir1PinB = 4;
int dir2PinB = 5;
int speedPinB = 10; // Needs to be a PWM pin to be able to control motor speed

void setup() { // Setup runs once per reset


// initialize serial communication @ 9600 baud:
Serial.begin(9600);

//Define L298N Dual H-Bridge Motor Controller Pins

pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
pinMode(dir1PinB,OUTPUT);
pinMode(dir2PinB,OUTPUT);
pinMode(speedPinB,OUTPUT);

void loop() {
henti();
delay(1000);
maju();
delay(5000);
henti();
delay(1000);
mundur();
delay(5000);
henti();
delay(1000);
kanan();
delay(5000);
henti();
delay(1000);
kiri();
delay(5000);
}

void maju(){
analogWrite(speedPinA, 80);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
analogWrite(speedPinB, 80);
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
}
void mundur(){
analogWrite(speedPinA, 80);
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, 80);
digitalWrite(dir1PinB, HIGH);
digitalWrite(dir2PinB, LOW);
}
void kanan(){
analogWrite(speedPinA, 80);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
analogWrite(speedPinB, 80);
digitalWrite(dir1PinB, HIGH);
digitalWrite(dir2PinB, LOW);
}
void kiri(){
analogWrite(speedPinA, 80);
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, 80);
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
}
void henti(){
analogWrite(speedPinA, 0);
analogWrite(speedPinB, 0);
}
------------------------------------------------------------------------------------------------------
2. MOTOR DC DENGAN L298N DUAL H-BRIDGE MOTOR CONTROLLER BY
KEYBOARD

//Code by Reichenstein7 (thejamerson.com)

//Keyboard Controls:
//
// 1 -Motor 1 Left
// 2 -Motor 1 Stop
// 3 -Motor 1 Right
//
// 4 -Motor 2 Left
// 5 -Motor 2 Stop
// 6 -Motor 2 Right

// Declare L298N Dual H-Bridge Motor Controller directly since there is not a library to load.

// Motor 1
int dir1PinA = 2;
int dir2PinA = 3;
int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed

// Motor 2
int dir1PinB = 4;
int dir2PinB = 5;
int speedPinB = 10; // Needs to be a PWM pin to be able to control motor speed

void setup() { // Setup runs once per reset


// initialize serial communication @ 9600 baud:
Serial.begin(9600);

//Define L298N Dual H-Bridge Motor Controller Pins

pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
pinMode(dir1PinB,OUTPUT);
pinMode(dir2PinB,OUTPUT);
pinMode(speedPinB,OUTPUT);

void loop() {

// Initialize the Serial interface:

if (Serial.available() > 0) {
int inByte = Serial.read();
int speed; // Local variable

switch (inByte) {
//______________Motor 1______________

case '1': // Motor 1 Forward


analogWrite(speedPinA, 255);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
Serial.println("Motor 1 Forward"); // Prints out “Motor 1 Forward” on the serial monitor
Serial.println(" "); // Creates a blank line printed on the serial monitor
break;

case '2': // Motor 1 Stop (Freespin)


analogWrite(speedPinA, 0);
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
Serial.println("Motor 1 Stop");
Serial.println(" ");
break;

case '3': // Motor 1 Reverse


analogWrite(speedPinA, 255);
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
Serial.println("Motor 1 Reverse");
Serial.println(" ");
break;

//______________Motor 2______________

case '4': // Motor 2 Forward


analogWrite(speedPinB, 255);
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
Serial.println("Motor 2 Forward");
Serial.println(" ");
break;

case '5': // Motor 1 Stop (Freespin)


analogWrite(speedPinB, 0);
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
Serial.println("Motor 2 Stop");
Serial.println(" ");
break;

case '6': // Motor 2 Reverse


analogWrite(speedPinB, 255);
digitalWrite(dir1PinB, HIGH);
digitalWrite(dir2PinB, LOW);
Serial.println("Motor 2 Reverse");
Serial.println(" ");
break;
default:
// turn all the connections off if an unmapped key is pressed:
for (int thisPin = 2; thisPin < 11; thisPin++) {
digitalWrite(thisPin, LOW);
}
}
}
}

-------------------------------------------------------------------------------------------------------
3. KONTROL SERVO MOTOR DENGAN POTENSIOMETER

#include <Servo.h>

Servo head;
int sensorPin = A0;
int sensorValue = 0;
int sudut = 0;
void setup()
{
head.attach(7); // pin terkoneksi ke input servo motor
head.write(80);
pinMode(sensorPin,INPUT);
Serial.begin(9600);

}
void loop(){
float sensorValue = analogRead(sensorPin);
int sudut = (sensorValue/1023)*180;
Serial.println(sudut);
head.write(sudut);
}
4. PENGUKURAN SUHU DAN KELEMBABAN DENGAN DHT 11

#include <dht.h>

dht DHT;

#define DHT11_PIN 5

void setup()
{
Serial.begin(9600);

void loop()
{

int chk = DHT.read11(DHT11_PIN);


Serial.print(DHT.humidity, 1);
Serial.print(" % ");
Serial.print(DHT.temperature, 1);
Serial.println(" C");

delay(100);
}

================================================================
5. DHT22 ARDUINO

#include "DHT.h" // DHT & AM2302 library

// Version number
const float fVerNum = 0.03;

// Data pin connected to AM2302


#define DHTPIN 2

#define DHTTYPE DHT22 // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE); // LED pins

//////////////////////////////////////////////////////
//
// SETUP
//
void setup() {
// Setup serial monitor
Serial.begin(9600);

// Wait 3 seconds
delay(3000);

Serial.println(F("\nAM2302 Sensor"));
Serial.print(F("Version : "));
Serial.println(fVerNum);
Serial.println(F("Arduino - Derek Erb\n"));
delay(5000);

dht.begin();
}

void loop() {

// Reading temperature or humidity takes about 250 milliseconds!


// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
float t = dht.readTemperature();
// check if returns are valid, if they are NaN (not a number) then something went wrong!
if (isnan(t) || isnan(h)) {
Serial.println(F("Failed to read from DHT"));
}
else {
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F(" %\t"));
Serial.print(F("Temperature: "));
Serial.print(t);
Serial.println(F(" C"));
}

// Wait 3 seconds
delay(3000);
}
--------------------------------------------------------------------------------------------------------
6. PRESSURE BAROMETER BMP 180

/* SFE_BMP180 library example sketch

This sketch shows how to use the SFE_BMP180 library to read the
Bosch BMP180 barometric pressure sensor.
https://www.sparkfun.com/products/11824

Like most pressure sensors, the BMP180 measures absolute pressure.


This is the actual ambient pressure seen by the device, which will
vary with both altitude and weather.

Before taking a pressure reading you must take a temparture reading.


This is done with startTemperature() and getTemperature().
The result is in degrees C.

Once you have a temperature reading, you can take a pressure reading.
This is done with startPressure() and getPressure().
The result is in millibar (mb) aka hectopascals (hPa).

If you'll be monitoring weather patterns, you will probably want to


remove the effects of altitude. This will produce readings that can
be compared to the published pressure readings from other locations.
To do this, use the sealevel() function. You will need to provide
the known altitude at which the pressure was measured.

If you want to measure altitude, you will need to know the pressure
at a baseline altitude. This can be average sealevel pressure, or
a previous pressure reading at your altitude, in which case
subsequent altitude readings will be + or - the initial baseline.
This is done with the altitude() function.

Hardware connections:
- (GND) to GND
+ (VDD) to 3.3V

(WARNING: do not connect + to 5V or the sensor will be damaged!)

You will also need to connect the I2C pins (SCL and SDA) to your
Arduino. The pins are different on different Arduinos:

Any Arduino pins labeled: SDA SCL


Uno, Redboard, Pro: A4 A5
Mega2560, Due: 20 21
Leonardo: 2 3

Leave the IO (VDDIO) pin unconnected. This pin is for connecting


the BMP180 to systems with lower logic levels such as 1.8V

Have fun! -Your friends at SparkFun.

The SFE_BMP180 library uses floating-point equations developed by the


Weather Station Data Logger project: http://wmrx00.sourceforge.net/

Our example code uses the "beerware" license. You can do anything
you like with this code. No really, anything. If you find it useful,
buy me a beer someday.

V10 Mike Grusin, SparkFun Electronics 10/24/2013


V1.1.2 Updates for Arduino 1.6.4 5/2015
*/

// Your sketch must #include this library, and the Wire library.
// (Wire is a standard library included with Arduino.):

#include <SFE_BMP180.h>
#include <Wire.h>

// You will need to create an SFE_BMP180 object, here called "pressure":

SFE_BMP180 pressure;

#define ALTITUDE 1655.0 // Altitude of SparkFun's HQ in Boulder, CO. in meters

void setup()
{
Serial.begin(9600);
Serial.println("REBOOT");

// Initialize the sensor (it is important to get calibration values stored on the device).

if (pressure.begin())
Serial.println("BMP180 init success");
else
{
// Oops, something went wrong, this is usually a connection problem,
// see the comments at the top of this sketch for the proper connections.

Serial.println("BMP180 init fail\n\n");


while(1); // Pause forever.
}
}

void loop()
{
char status;
double T,P,p0,a;

// Loop here getting pressure readings every 10 seconds.

// If you want sea-level-compensated pressure, as used in weather reports,


// you will need to know the altitude at which your measurements are taken.
// We're using a constant called ALTITUDE in this sketch:

Serial.println();
Serial.print("provided altitude: ");
Serial.print(ALTITUDE,0);
Serial.print(" meters, ");
Serial.print(ALTITUDE*3.28084,0);
Serial.println(" feet");

// If you want to measure altitude, and not pressure, you will instead need
// to provide a known baseline pressure. This is shown at the end of the sketch.

// You must first get a temperature measurement to perform a pressure reading.

// Start a temperature measurement:


// If request is successful, the number of ms to wait is returned.
// If request is unsuccessful, 0 is returned.

status = pressure.startTemperature();
if (status != 0)
{
// Wait for the measurement to complete:
delay(status);

// Retrieve the completed temperature measurement:


// Note that the measurement is stored in the variable T.
// Function returns 1 if successful, 0 if failure.

status = pressure.getTemperature(T);
if (status != 0)
{
// Print out the measurement:
Serial.print("temperature: ");
Serial.print(T,2);
Serial.print(" deg C, ");
Serial.print((9.0/5.0)*T+32.0,2);
Serial.println(" deg F");

// Start a pressure measurement:


// The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).
// If request is successful, the number of ms to wait is returned.
// If request is unsuccessful, 0 is returned.

status = pressure.startPressure(3);
if (status != 0)
{
// Wait for the measurement to complete:
delay(status);

// Retrieve the completed pressure measurement:


// Note that the measurement is stored in the variable P.
// Note also that the function requires the previous temperature measurement (T).
// (If temperature is stable, you can do one temperature measurement for a number of pressure
measurements.)
// Function returns 1 if successful, 0 if failure.

status = pressure.getPressure(P,T);
if (status != 0)
{
// Print out the measurement:
Serial.print("absolute pressure: ");
Serial.print(P,2);
Serial.print(" mb, ");
Serial.print(P*0.0295333727,2);
Serial.println(" inHg");

// The pressure sensor returns abolute pressure, which varies with altitude.
// To remove the effects of altitude, use the sealevel function and your current altitude.
// This number is commonly used in weather reports.
// Parameters: P = absolute pressure in mb, ALTITUDE = current altitude in m.
// Result: p0 = sea-level compensated pressure in mb

p0 = pressure.sealevel(P,ALTITUDE); // we're at 1655 meters (Boulder, CO)


Serial.print("relative (sea-level) pressure: ");
Serial.print(p0,2);
Serial.print(" mb, ");
Serial.print(p0*0.0295333727,2);
Serial.println(" inHg");

// On the other hand, if you want to determine your altitude from the pressure reading,
// use the altitude function along with a baseline pressure (sea-level or other).
// Parameters: P = absolute pressure in mb, p0 = baseline pressure in mb.
// Result: a = altitude in m.

a = pressure.altitude(P,p0);
Serial.print("computed altitude: ");
Serial.print(a,0);
Serial.print(" meters, ");
Serial.print(a*3.28084,0);
Serial.println(" feet");
}
else Serial.println("error retrieving pressure measurement\n");
}
else Serial.println("error starting pressure measurement\n");
}
else Serial.println("error retrieving temperature measurement\n");
}
else Serial.println("error starting temperature measurement\n");

delay(5000); // Pause for 5 seconds.


}
7. PRESSURE BAROMETER BMP 280

#include <Wire.h>
#include "BMP280.h"
#define P0 1013.25
BMP280 bmp;

void setup(){
if(!bmp.begin()){
Serial.println("BMP init failed!");
while(1);
}
else {
Serial.println("BMP init success!");
}

bmp.setOversampling(4);

Serial.begin(9600);

Wire.begin();

}
void loop(){
{
double T,P;
char result = bmp.startMeasurment();

if(result!=0){
delay(result);
result = bmp.getTemperatureAndPressure(T,P);

if(result!=0)
{
double A = bmp.altitude(P,P0);
Serial.print("T = \t");
Serial.print(T,2);
Serial.print(" degC\t");
Serial.print("P = \t");
Serial.print(P,2);
Serial.print(" mBar\t");
Serial.print("A = \t");
Serial.print(A,2);
Serial.println(" m");

}
else {
Serial.println("Error.");
}
}
else {
Serial.println("Error.");
}

delay(100);
}
}

===========================================================
8. STEPPER MOTOR 28BYJ-48 WITH L293D CONTROLLED BY KEYBOARD

/*
Adafruit Arduino - Lesson 16. Stepper
*/

#include <Stepper.h>

int in1Pin = 12;


int in2Pin = 11;
int in3Pin = 10;
int in4Pin = 9;

Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

void setup()
{
pinMode(in1Pin, OUTPUT);
pinMode(in2Pin, OUTPUT);
pinMode(in3Pin, OUTPUT);
pinMode(in4Pin, OUTPUT);

// this line is for Leonardo's, it delays the serial interface


// until the terminal window is opened
while (!Serial);

Serial.begin(9600);
motor.setSpeed(25);
}

void loop()
{
if (Serial.available())
{
int steps = Serial.parseInt();
motor.step(steps);
}
}

==============================================================
9. PUSH BUTTON IR REMOTE

#include <IRremote.h>

int RECV_PIN = 8; // the pin where connect the output pin of IR receiver
int led4 = 9;//connect this pin to relay module
int led5 = 10;
int led6 = 11;
int itsONled[] = {0,0,0};
#define code1 16724175 // code received from button IR remote
#define code2 16718055
#define code3 16743045
IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
pinMode(led6, OUTPUT);

void loop() {
if (irrecv.decode(&results)) {
unsigned int value = results.value;
switch(value) {
case code1:
if(itsONled[1] == 1) { // if first led is on then
digitalWrite(led4, HIGH);
delay(500);
digitalWrite(led4, LOW);
//digitalWrite(led2, LOW);
//digitalWrite(led3, HIGH); // turn it off when button is pressed
itsONled[1] = 0; // and set its state as off
} else { // else if first led is off
digitalWrite(led4, HIGH);
delay(500);
digitalWrite(led4, LOW);
//digitalWrite(led2, HIGH);
//digitalWrite(led3, LOW); // turn it on when the button is pressed
itsONled[1] = 1; // and set its state as on
}
break;
case code2:
if(itsONled[1] == 1) { // if first led is on then
digitalWrite(led5, HIGH);
delay(500);
digitalWrite(led5, LOW);
//digitalWrite(led2, LOW);
//digitalWrite(led3, HIGH); // turn it off when button is pressed
itsONled[1] = 0; // and set its state as off
} else { // else if first led is off
digitalWrite(led5, HIGH);
delay(500);
digitalWrite(led5, LOW);
//digitalWrite(led2, HIGH);
//digitalWrite(led3, LOW); // turn it on when the button is pressed
itsONled[1] = 1; // and set its state as on
}
break;
case code3:
if(itsONled[1] == 1) { // if first led is on then
digitalWrite(led6, HIGH);
delay(500);
digitalWrite(led6, LOW);
//digitalWrite(led2, LOW);
//digitalWrite(led3, HIGH); // turn it off when button is pressed
itsONled[1] = 0; // and set its state as off
} else { // else if first led is off
digitalWrite(led6, HIGH);
delay(500);
digitalWrite(led6, LOW);
//digitalWrite(led2, HIGH);
//digitalWrite(led3, LOW); // turn it on when the button is pressed
itsONled[1] = 1; // and set its state as on
}
break;

}
Serial.println(value);
irrecv.resume(); // Receive the next value
}
}

------------------------------------------------------------------------------------------------------------
10. LIFT 3 FLOOR

/*
Elevator project with arduino pro mini 328 5v 8mhz

- This is a simple elevator project using a single-phase ac motor.


- There are 3 floors and a button is placed in every floor and are connected in paraller with 3
button inside the elevator.
- 3 proximity switches are attached on every floor to indicate where the elevator is and to stop it.
- A buzzer is connected to warn for movement or
-alarm stop inside the elevator is attached directly to the reset button.

code by:Fanis Katmadas


site:oramasolutions.com
[email protected]
*/

int dir1PinA = 10;


int dir2PinA = 11;
int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed

const int sensorL1 = 2;//signal sensor lantai 1


const int sensorL2 = 3;//signal sensor lantai 2
const int sensorL3 = 4;//signal sensor lantai 3
const int tombolL1 = 5;//signal tombol lantai 1
const int tombolL2 = 6;//signal tombol lantai 2
const int tombolL3 = 7;//signal tombol lantai 3

const int poweron=13;

// variables will change:


int tombolL1state = 0;
int tombolL2state = 0;
int tombolL3state = 0;
int sensorL1state = 0;
int sensorL2state = 0;
int sensorL3state = 0;

void setup()

pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
pinMode(sensorL1, INPUT);
pinMode(sensorL2, INPUT);
pinMode(sensorL3, INPUT);
pinMode(tombolL1, INPUT);
pinMode(tombolL2, INPUT);
pinMode(tombolL3, INPUT);

Serial.begin(9600);

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()

{
digitalWrite(poweron, HIGH);

tombolL1state = digitalRead(tombolL1);
tombolL2state = digitalRead(tombolL2);
tombolL3state = digitalRead(tombolL3);

sensorL1state = digitalRead(sensorL1);
sensorL2state = digitalRead(sensorL2);
sensorL3state = digitalRead(sensorL3);

if (tombolL1state == HIGH)

{
delay(200);
while(tombolL1state == HIGH)
{
tombolL1state = digitalRead(tombolL1);//check the value of the button again
delay(10);//keep running smoothly
}//wait for the relese of the button to continue
delay(1000);
floor1function();//go to the floor 1 fuction of the elevator
}

else if(tombolL2state == HIGH)// if the floor 2 call button is pressed

{
delay(200); //software debounce of the button
while(tombolL2state == HIGH)
{
tombolL2state = digitalRead(tombolL2);//check the value of the button again
delay(10);//keep running smoothly
}//wait for the relese of the button to continue
delay(1000);
floor2function();//go to the floor 2 fuction of the elevator
}

else if(tombolL3state == HIGH)// if the floor 1 call button is pressed

{
delay(200); //software debounce of the button
while(tombolL3state == HIGH)
{
tombolL3state = digitalRead(tombolL3);//check the value of the button again
delay(10);//keep running smoothly
}//wait for the relese of the button to continue
delay(1000);
floor3function();//go to the floor 3 fuction of the elevator
}

//digitalWrite(relayup, LOW); //keep the relay for up motion inactive


//digitalWrite(relaydown, LOW); //keep the relay for down motion inactive
//digitalWrite(buzzer, LOW);//keep the buzzer quite

delay(10);//a few delay just to keep running smoothly

void floor1function()

if(sensorL1state != HIGH) // check the proximity sensor of the first floor to see if the
elevator is there

{//if the elevator isn't there call it

while(sensorL1state==LOW) //check that the proximity of the first floor is low


//the motor begins and stops when the appropriate floor proximity give the
signal
{
turun();
//digitalWrite(buzzer, HIGH);//some noise in the mic
sensorL1state = digitalRead(sensorL1);
delay(10);//a few delay to keep running the routine smoothly
}
while(sensorL1state==HIGH) //check that the proximity of the first floor is low
//the motor begins and stops when the appropriate floor proximity give the
signal
{
henti();

//digitalWrite(buzzer, HIGH);//some noise in the mic


sensorL1state = digitalRead(sensorL1);
delay(10);//a few delay to keep running the routine smoothly
resetFunc(); //call reset
}
}

void floor2function()

if(sensorL3state == HIGH) // check the proximity sensor of the third floor to see
if the elevator is there

{//if the elevator is there call it

while( sensorL2state==LOW)//the motor begins and stops when the


appropriate floor proximity give the signal

{
turun();
//digitalWrite(buzzer, HIGH);//some noise in the mic
sensorL2state = digitalRead(sensorL2);
delay(10);//a few delay to keep running the routine smoothly

}
while( sensorL2state==HIGH)//the motor begins and stops when the
appropriate floor proximity give the signal

{
henti();
//digitalWrite(buzzer, HIGH);//some noise in the mic
sensorL2state = digitalRead(sensorL2);
delay(10);//a few delay to keep running the routine smoothly
resetFunc(); //call reset
}
}

else if(sensorL1state == HIGH) // check the proximity sensor of the first floor to
see if the elevator is there

{//if the elevator is there call it

while( sensorL2state==LOW)//the motor begins and stops when the


appropriate floor proximity give the signal

{
naik();
//digitalWrite(buzzer, HIGH);//some noise in the mic
sensorL2state = digitalRead(sensorL2);
delay(10);//a few delay to keep running the routine smoothly
}
while( sensorL2state==HIGH)//the motor begins and stops when
the appropriate floor proximity give the signal

{
henti();
//digitalWrite(buzzer, HIGH);//some noise in the mic
sensorL2state = digitalRead(sensorL2);
delay(10);//a few delay to keep running the routine smoothly
resetFunc(); //call reset
}

void floor3function()

if(sensorL2state == HIGH || sensorL1state == HIGH) // check the proximity


sensor of the first and second floor to see if the elevator is there

{//if the elevator is there call it

while( sensorL3state==LOW) //the motor begins and stops when the


appropriate floor proximity give the signal
{
naik();
//digitalWrite(buzzer, HIGH);//some noise in the mic
sensorL3state = digitalRead(sensorL3);
delay(10);//a few delay to keep running the routine smoothly
}
while( sensorL3state==HIGH) //the motor begins and stops when
the appropriate floor proximity give the signal

{
henti();
//digitalWrite(buzzer, HIGH);//some noise in the mic
sensorL3state = digitalRead(sensorL3);
delay(10);//a few delay to keep running the routine smoothly
resetFunc(); //call reset
}

void naik(){
analogWrite(speedPinA, 80);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);

}
void turun(){
analogWrite(speedPinA, 80);
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);

}
void henti(){
analogWrite(speedPinA, 0);
}

--------------------------------------------------------
11. SWITCH OTOMATIS POMPA AIR DENGAN SENSOR KAPASITIF

Metode ini pada prinsipnya menggunakan pelepasan muatan pada kawat sensor, sensor sangat peka,
karena kepekaannya maka metode ini kadang memberikan kesalahan. Peletakan kabel sensor sangat
banyak berpengaruh.

#include <CapacitiveSensor.h>
#define led 11 //this pin for drive relay
CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2); // 10M resistor between pins 4 & 2, pin 2
is sensor pin, add a wire and or foil if desired
CapacitiveSensor cs_5_6 = CapacitiveSensor(5,6); // 10M resistor between pins 5 & 6, pin 6
is sensor pin, add a wire and or foil

void setup() {
cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate on channel 1 - just as an
example
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
long start = millis();
long total1 = cs_4_2.capacitiveSensor(30);
long total2 = cs_5_6.capacitiveSensor(30);

if (total1 <= 15000) {


digitalWrite(led, LOW);//this output go to relay IN

}
if (total2 >= 15000) {
digitalWrite(led, HIGH);

Serial.print(total1);
Serial.print(" ");
Serial.println(total2);
delay(100);
}
-------------------------------------------
12. ALAT PENGUJI WEATHERING LPG

/*
In this project we use LM324 chip for amplify signal from RTD PT100, amplified signal than go to
ADS1015 for increase digital resolution.
*/
#include <Wire.h>
#include <Adafruit_ADS1015.h>

Adafruit_ADS1115 ads(0x48);

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 7, 6, 5, 4, 3);

int temp0;
int temp1;

int delta;

void setup() {

Serial.begin(9600);
ads.begin();
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(1,0);
lcd.print("WEATHERING TEST");
lcd.setCursor(4,1);
lcd.print("VERSION 3");
delay(5000);

}
void loop() {
int16_t adc0; // we read from the ADC, we have a sixteen bit integer as a result
int16_t adc1;
adc0 = ads.readADC_SingleEnded(0);
adc1 = ads.readADC_SingleEnded(1);
temp1 = adc1;
temp0 = adc0;
float fhrt = (temp0*0.0466)-671.48;
int delta = temp1-temp0;
if (delta>=70 || fhrt>40){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("T=");
lcd.setCursor(2,0);
lcd.print(fhrt,2);
lcd.setCursor(7,0);
lcd.print("F");
lcd.setCursor(12,0);
lcd.print("END");
lcd.setCursor(0,1);
lcd.print(delta);
lcd.setCursor(11,1);
lcd.print(temp1);
delay(36000000);
}
else {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("T=");
lcd.setCursor(2,0);
lcd.print(fhrt,2);
lcd.setCursor(7,0);
lcd.print("F");
lcd.setCursor(0,1);
lcd.print(delta);
lcd.setCursor(11,0);
lcd.print(temp0);
lcd.setCursor(11,1);
lcd.print(temp1);
Serial.print(temp0);
Serial.print(" ");
Serial.println(temp1);
delay(400);
}
}
----------------------------------------------------------------------
13. SWITCH OTOMATIS POMPA AIR DENGAN SENSOR CONDUCTIVITY

#define led 11 //this pin for drive relay

void setup() {

Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
int sensorValue0 = analogRead(A0);
int sensorValue1 = analogRead(A1);

if (sensorValue0 <= 500) {


digitalWrite(led, LOW);//this output go to relay IN

}
if (sensorValue1 >= 500) {
digitalWrite(led, HIGH);
}
Serial.print(sensorValue0);
Serial.print(" ");
Serial.println(sensorValue1);
delay(100);
}
---------------------------------------------------------------------------------------------
14. SETUP LCD 16X2

Pada proyek ini kita setup LCD 16x2 langsung ke arduino

/*
LiquidCrystal Library - Hello World

Demonstrates the use a 16x2 LCD display. The LiquidCrystal


library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
can usually tell them by the 16-pin interface.

This sketch prints "Hello World!" to the LCD


and shows the time.

The circuit:
* LCD RS pin to digital pin 8
* LCD Enable pin to digital pin 7
* LCD D4 pin to digital pin 6
* LCD D5 pin to digital pin 5
* LCD D6 pin to digital pin 4
* LCD D7 pin to digital pin 3
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008
by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe
modified 22 Nov 2010
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/

// include the library code:


#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins


LiquidCrystal lcd(8, 7, 6, 5, 4, 3);//order number : RS,EN,D4,D5,D6,D7

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis() / 1000);
}

---------------------------------------------------------------------------------------------------------
15. GENERATOR NADA

// referensi tangga nada


#include "pitches.h"
// speaker ada di pin 9
const int pinSpeaker = 9;
#define JUMLAH_NADA 85
const int daftar_nada[JUMLAH_NADA] = {
NOTE_E4, NOTE_F4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_E4,0, // 0 is stop
NOTE_E4, NOTE_F4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_E4,0,
NOTE_D4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_B3, NOTE_D4, NOTE_G4,
NOTE_D4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_C4, NOTE_C4,0,
NOTE_E4, NOTE_F4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_E4,0,
NOTE_E4, NOTE_F4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_E4,0,
NOTE_D4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_B3, NOTE_D4, NOTE_G4,
NOTE_D4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_C4, NOTE_C4,0,
NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_A4, NOTE_G4,0,
NOTE_C4, NOTE_D4, NOTE_E4, NOTE_A4, NOTE_A4, NOTE_G4,0,
NOTE_D4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_B4, NOTE_G4,0,
NOTE_D4, NOTE_C4, NOTE_E4, NOTE_D4, NOTE_C3, NOTE_C4, NOTE_C4,0,
};
const int lama_beat = 150;
const int beats[JUMLAH_NADA] = {
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2,
2, 2, 2, 2, 1, 4, 2, 8,
};
float data1;
void setup() {
pinMode(pinSpeaker, OUTPUT);
Serial.begin(9600);
}
void loop() {
for(int i=0; i<JUMLAH_NADA; i++){
if(nada[i] == 0){
delay(beats[i] * lama_beat);
}else{
nada(daftar_nada[i], beats[i] * lama_beat);
}
// jeda antar nada
noTone(pinSpeaker);
delay(lama_beat / 2);
}
}

void nada(int frek, int durasi){


tone(pinSpeaker, frek, durasi);
delay(durasi);
}

pada sket di atas harus dilengkapi folder dengan nama pitches.h, buatlah folder baru pada IDE beri
nama folder pitches.h, selanjutnya paste sket di bawah ini kemudian save.

/*************************************************
* Public Constants
*************************************************/

#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
------------------------------------------------------------------------------------------------------------
16. MEMBACA TEGANGAN 5V

/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

This example code is in the public domain.


*/

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}

--------------------------------------------------------------------------------------------------------------
17. SETUP RTC

#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;

void setup () {
Serial.begin(9600);
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
}
void loop () {
DateTime now = RTC.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
delay(1000);
}

------------------------------------------------------------------------------------------------
18. ALARM NADA

// coder elangsakti
// tangga nada C
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
// DO
// RE
// MI
// FA
// SOL
// LA
// SI
// DO
// speaker ada di pin 9
const int pinSpeaker = 9;
void setup() {
pinMode(pinSpeaker, OUTPUT);
}
void loop() {
tone(pinSpeaker,NOTE_C4, 500);
delay(500);
tone(pinSpeaker,NOTE_D4, 500);
delay(500);
tone(pinSpeaker,NOTE_E4, 500);
delay(500);
tone(pinSpeaker,NOTE_F4, 500);
delay(500);
tone(pinSpeaker,NOTE_G4, 500);
delay(500);
tone(pinSpeaker,NOTE_A4, 500);
delay(500);
tone(pinSpeaker,NOTE_B4, 500);
delay(500);
tone(pinSpeaker,NOTE_C5, 500);
delay(500);

noTone(pinSpeaker); // noTone berarti diam


delay(1000);
}

-----------------------------------------------------------------------------------------------------------

/*
SparkFun Inventor's Kit
Example sketch 11

BUZZER

Use the buzzer to play a song!

The buzzer in your Inventor's Kit is an electromechanical


component you can use to make noise. Inside the buzzer is a
coil of wire and a small magnet. When current flows through
the coil, it becomes magnetized and pulls towards the magnet,
creating a tiny "click". When you do this thousands of times
per second, you create tones.

The Arduino has a built-in command called tone() which clicks


the buzzer at a certain frequency. This sketch knows the
frequencies of the common notes, allowing you to create songs.
We're never going to let you down!

Hardware connections:

The buzzer has two pins. One is positive and one is negative.
The postitive pin is marked by a "+" symbol on both the top
and bottom of the buzzer.

Connect the positive pin to Arduino digital pin 9.


(Note that this must be a PWM pin.)
Connect the negative pin to GND.

Tip: if the buzzer doesn't fit into the breadboard easily,


try rotating it slightly to fit into diagonal holes.

This sketch was written by SparkFun Electronics,


with lots of help from the Arduino community.
(This sketch was originally developed by D. Cuartielles for K3)
This code is completely free for any use.
Visit http://learn.sparkfun.com/products/2 for SIK information.
Visit http://www.arduino.cc to learn about the Arduino.

Version 2.0 6/2012 MDG


*/

/*
This sketch uses the buzzer to play songs.
The Arduino's tone() command will play notes of a given frequency.
We'll provide a function that takes in note characters (a-g),
and returns the corresponding frequency from this table:

note frequency
c 262 Hz
d 294 Hz
e 330 Hz
f 349 Hz
g 392 Hz
a 440 Hz
b 494 Hz
C 523 Hz

For more information, see http://arduino.cc/en/Tutorial/Tone


*/

const int buzzerPin = 9;

// We'll set up an array with the notes we want to play


// change these values to make different songs!

// Length must equal the total number of notes and spaces

const int songLength = 18;

// Notes is an array of text characters corresponding to the notes


// in your song. A space represents a rest (no tone)

char notes[] = "cdfda ag cdfdg gf "; // a space represents a rest


// Beats is an array of values for each note and rest.
// A "1" represents a quarter-note, 2 a half-note, etc.
// Don't forget that the rests (spaces) need a length as well.

int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};

// The tempo is how fast to play the song.


// To make the song play faster, decrease this value.

int tempo = 113;

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

void loop()
{
int i, duration;

for (i = 0; i < songLength; i++) // step through the song arrays


{
duration = beats[i] * tempo; // length of note/rest in ms

if (notes[i] == ' ') // is this a rest?


{
delay(duration); // then pause for a moment
}
else // otherwise, play the note
{
tone(buzzerPin, frequency(notes[i]), duration);
delay(duration); // wait for tone to finish
}
delay(tempo/10); // brief pause between notes
}

// We only want to play the song once, so we'll pause forever:


while(true){}
// If you'd like your song to play over and over,
// remove the above statement
}

int frequency(char note)


{
// This function takes a note character (a-g), and returns the
// corresponding frequency in Hz for the tone() function.

int i;
const int numNotes = 8; // number of notes we're storing

// The following arrays hold the note characters and their


// corresponding frequencies. The last "C" note is uppercase
// to separate it from the first lowercase "c". If you want to
// add more notes, you'll need to use unique characters.

// For the "char" (character) type, we put single characters


// in single quotes.

char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};

// Now we'll search through the letters in the array, and if


// we find it, we'll return the frequency for that note.

for (i = 0; i < numNotes; i++) // Step through the notes


{
if (names[i] == note) // Is this the one?
{
return(frequencies[i]); // Yes! Return the frequency
}
}
return(0); // We looked through everything and didn't find it,
// but we still need to return a value, so return 0.
}

-----------------------------------------------------------------------------------------------------------------

/* Arduino tutorial - Buzzer / Piezo Speaker

More info and circuit: http://www.ardumotive.com/how-to-use-a-buzzer-en.html

Dev: Michalis Vasilakis // Date: 9/6/2015 // www.ardumotive.com */


const int buzzer = 9; //buzzer to arduino pin 9
void setup(){
pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
}
void loop(){
tone(buzzer, 1000); // Send 1KHz sound signal...
delay(1000); // ...for 1 sec
noTone(buzzer); // Stop sound...
delay(1000); // ...for 1sec
}

---------------------------------------------------------------------------------------------------------------------

/* Play Melody
* -----------
*
* Program to play melodies stored in an array, it requires to know
* about timing issues and about how to play tones.
*
* The calculation of the tones is made following the mathematical
* operation:
*
* timeHigh = 1/(2 * toneFrequency) = period / 2
*
* where the different tones are described as in the table:
*
* note frequency period PW (timeHigh)
*c 261 Hz 3830 1915
*d 294 Hz 3400 1700
*e 329 Hz 3038 1519
*f 349 Hz 2864 1432
*g 392 Hz 2550 1275
*a 440 Hz 2272 1136
*b 493 Hz 2028 1014
*C 523 Hz 1912 956
*
* (cleft) 2005 D. Cuartielles for K3
*/

int ledPin = 13;


int speakerOut = 9;
byte names[] = {'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'};
int tones[] = {1915, 1700, 1519, 1432, 1275, 1136, 1014, 956};
byte melody[] = "2d2a1f2c2d2a2d2c2f2d2a2c2d2a1f2c2d2a2a2g2p8p8p8p";
// count length: 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
// 10 20 30
int count = 0;
int count2 = 0;
int count3 = 0;
int MAX_COUNT = 24;
int statePin = LOW;

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

void loop() {
analogWrite(speakerOut, 0);
for (count = 0; count < MAX_COUNT; count++) {
statePin = !statePin;
digitalWrite(ledPin, statePin);
for (count3 = 0; count3 <= (melody[count*2] - 48) * 30; count3++) {
for (count2=0;count2<8;count2++) {
if (names[count2] == melody[count*2 + 1]) {
analogWrite(speakerOut,500);
delayMicroseconds(tones[count2]);
analogWrite(speakerOut, 0);
delayMicroseconds(tones[count2]);
}
if (melody[count*2 + 1] == 'p') {
// make a pause of a certain size
analogWrite(speakerOut, 0);
delayMicroseconds(500);
}
}
}
}
}

----------------------------------------------------------------------------------------------------------------
/*
Piezo

This example shows how to run a Piezo Buzzer on pin 9


using the analogWrite() function.

It beeps 3 times fast at startup, waits a second then beeps continuously


at a slower pace

*/

void setup() {
// declare pin 9 to be an output:
pinMode(9, OUTPUT);
beep(50);
beep(50);
beep(50);
delay(1000);
}

void loop() {
beep(200);
}

void beep(unsigned char delayms){


analogWrite(9, 20); // Almost any value can be used except 0 and 255
// experiment to get the best tone
delay(delayms); // wait for a delayms ms
analogWrite(9, 0); // 0 turns it off
delay(delayms); // wait for a delayms ms
}

------------------------------------------------------------------------------------------------------

int pinSpeaker = 9;

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

void loop () {
playTone(750, 500);
delay(750);
}

// duration in mSecs, frequency in hertz


void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}

------------------------------------------------------------------------------------------------------
Ambulans alarm

int speaker = 9;
#define wait 1
#define time 100
int freq = 0;
void setup()
{

Serial.begin(9600);

pinMode(speaker, OUTPUT);
}

void loop()
{

digitalWrite(speaker, HIGH);
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000; freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker,
freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500;
freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}

-------------------------------------------------------------------------------------------------------
19. SETUP ULTRASONIC DISTANCE SENSOR

Ada beberapa sket yang dapat kita gunakan

Sket 1

#define trigPin1 2
#define echoPin1 4

long duration, distance, UltraSensor;

void setup()
{
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
}

void loop() {
SonarSensor(trigPin1, echoPin1);
UltraSensor = distance;
Serial.println(UltraSensor);
}

void SonarSensor(int trigPin,int echoPin)


{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
delay(100);
}

Sket 2

const int trigPin = 2;


const int echoPin = 4;

void setup() {
// initialize serial communication:
Serial.begin(9600);
}

void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;

// The sensor is triggered by a HIGH pulse of 10 or more microseconds.


// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the signal from the sensor: a HIGH pulse whose


// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);

Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();

delay(100);
}

long microsecondsToInches(long microseconds)


{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)


{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}

Sket 3

#include <NewPing.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define TRIGGER_PIN 2
#define ECHO_PIN 4
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters).
//Maximum sensor distance is rated at 400-500cm.
/*-----( Declare objects )-----*/
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and
maximum distance.
/*-----( Declare Variables )-----*/
int DistanceIn;
int DistanceCm;

void setup()
{
Serial.begin(9600);
Serial.println("UltraSonic Distance Measurement");
}

void loop()
{
delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay
between pings.
DistanceIn = sonar.ping_in();
Serial.print("Ping: ");
Serial.print(DistanceIn); // Convert ping time to distance and print result
// (0 = outside set distance range, no ping echo)
Serial.print(" in ");

delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay
between pings.
DistanceCm = sonar.ping_cm();
Serial.print("Ping: ");
Serial.print(DistanceCm);
Serial.println(" cm");

Sket 4

Sensor ultrasonic range juga dapat di pasang lebih dari satu, seperti sket di bawah.

int trigPin1 = 6;
int echoPin1 = 7;

int trigPin2 = 8;
int echoPin2 = 9;

void setup() {
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);

pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);

void firstsensor(){ // This function is for first sensor.


int duration1, distance1;
digitalWrite (trigPin1, HIGH);
delayMicroseconds (10);
digitalWrite (trigPin1, LOW);
duration1 = pulseIn (echoPin1, HIGH);
distance1 = (duration1/2) / 29.1;
Serial.print("1st Sensor: ");
Serial.print(distance1);
Serial.print("cm ");

}
void secondsensor(){ // This function is for second sensor.
int duration2, distance2;
digitalWrite (trigPin2, HIGH);
delayMicroseconds (10);
digitalWrite (trigPin2, LOW);
duration2 = pulseIn (echoPin2, HIGH);
distance2 = (duration2/2) / 29.1;

Serial.print("2nd Sensor: ");


Serial.print(distance2);
Serial.print("cm ");

void loop() {
Serial.println("\n");
firstsensor();
secondsensor();
delay(100);
}
Sket 5
Multi sensor dengan ping library

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


#include <NewPing.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define TRIGGER_PINR 3
#define ECHO_PINR 2
#define TRIGGER_PINL 4
#define ECHO_PINL 5
#define TRIGGER_PINF 7
#define ECHO_PINF 8
#define MAX_DISTANCE 500 // Maximum distance we want to ping for (in centimeters).
//Maximum sensor distance is rated at 400-500cm.
/*-----( Declare objects )-----*/
NewPing sonarR(TRIGGER_PINR, ECHO_PINR, MAX_DISTANCE); // NewPing setup of pins
and maximum distance.
NewPing sonarL(TRIGGER_PINL, ECHO_PINL, MAX_DISTANCE); // NewPing setup of pins
and maximum distance.
NewPing sonarF(TRIGGER_PINF, ECHO_PINF, MAX_DISTANCE); // NewPing setup of pins
and maximum distance.
/*-----( Declare Variables )-----*/
//int DistanceIn;
int DistanceCmR;
int DistanceCmL;
int DistanceCmF;

void setup()
{
Serial.begin (9600);

}
void loop() {

delay(100);// Wait 100ms between pings (about 10 pings/sec). 29ms should be the shortest delay
between pings.
DistanceCmR = sonarR.ping_cm();
DistanceCmL = sonarL.ping_cm();
DistanceCmF = sonarF.ping_cm();
Serial.print("Ping: ");
Serial.print(DistanceCmR);
Serial.print(" ");
Serial.print(DistanceCmL);
Serial.print(" ");
Serial.println(DistanceCmF);

----------------------------------------------------------------------------------------------------------------
20. PEMBACA KODE REMOTE INFRA RED

#include <IRremote.h>
int RECV_PIN = 3;
IRrecv irrecv(RECV_PIN);
decode_results results;

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

void loop()
{
if (irrecv.decode(&results))
{
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
}

atau dapat kita lihat dengan hasil desimal


#include <IRremote.h>
int RECV_PIN = 3;
IRrecv irrecv(RECV_PIN);
decode_results results;

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

void loop()
{
if (irrecv.decode(&results))
{
Serial.println(results.value, DEC);
irrecv.resume(); // Receive the next value
}
}

atau dapat juga dibaca dengan sket berikut

#include <IRLib.h>
//Create a receiver object to listen on pin 3
IRrecv My_Receiver(3);
//Create a decoder object
IRdecode My_Decoder;
void setup()
{
Serial.begin(9600);
My_Receiver.enableIRIn(); // Start the receiver
}
void loop() {
//Continuously look for results. When you have them pass them to the decoder
if (My_Receiver.GetResults(&My_Decoder)) {
My_Decoder.decode(); //Decode the data
My_Decoder.DumpResults(); //Show the results on serial monitor
My_Receiver.resume(); //Restart the receiver
}
}
---------------------------------------------------------------------------------------------------------
21. MENYALAKAN LAMPU DENGAN REMOTE IR UNSPECIFIC CODE

#include <IRremote.h>
int RECV_PIN = 5;
int OUTPUT_PIN = 9;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
pinMode(OUTPUT_PIN, OUTPUT);
pinMode(9, OUTPUT);
irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();
void loop() {
if (irrecv.decode(&results)) {
// If it's been at least 1/4 second since the last
// IR received, toggle the relay
if (millis() - last > 250) {
on = !on;
digitalWrite(OUTPUT_PIN, on ? HIGH : LOW);
}
last = millis();
irrecv.resume(); // Receive the next value
}
}

atau kita dapat menyalakan dan mematikan satu lampu dengan tombol yang berbeda dengan sket
berikut,

#include <IRremote.h>
int RECV_PIN = 3;
int OUTPUT_PIN = 4;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
pinMode(OUTPUT_PIN, OUTPUT);
pinMode(13, OUTPUT);
irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();
void loop() {
if (irrecv.decode(&results)) {
if (results.value == 0xEF1001FE) {
digitalWrite(OUTPUT_PIN, HIGH);
}
else if (results.value == 0xEF1055AA) {
digitalWrite(OUTPUT_PIN, LOW);
}
irrecv.resume(); // Receive the next value
}
}

atau kita menyalakan dan mematikan dengan tombol yang sama dengan sket berikut,

#include <IRremote.h>
int RECV_PIN = 3;
int OUTPUT_PIN = 4;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
pinMode(OUTPUT_PIN, OUTPUT);
pinMode(13, OUTPUT);
irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();
void loop() {

if (irrecv.decode(&results)) {

if (results.value == 0xEF1001FE) { // TIVO button

// If it's been at least 1/4 second since the last

// IR received, toggle the relay


if (millis() - last > 250) {
on = !on;
digitalWrite(OUTPUT_PIN, on ? HIGH : LOW);
}
last = millis();
}
irrecv.resume(); // Receive the next value
}
}
--------------------------------------------------------------------------------------------------
22. MENYALAKAN LAMPU LED DENGAN IR REMOTE

Pada proyek ini memanfaatkan kode remote inframerah untuk mematikan dan menyalakan lampu
LED.

/*
source: www.electroschematics.com
You'll need to change the led pins and the codes
accordingly to your configuration and IR remote
552656927
552600317
552624287
*/

#include <IRremote.h>

int RECV_PIN = 3; // the pin where you connect the output pin of TSOP4838
int led1 = 2;
int led2 = 4;
int led3 = 7;
int itsONled[] = {0,0,0,0};
/* the initial state of LEDs is OFF (zero)
the first zero must remain zero but you can
change the others to 1's if you want a certain
led to light when the board is powered */
#define code1 552656927 // code received from button A
#define code2 552600317 // code received from button B
#define code3 552624287 // code received from button C

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
Serial.begin(9600); // you can comment this line
irrecv.enableIRIn(); // Start the receiver
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}

void loop() {
if (irrecv.decode(&results)) {
unsigned int value = results.value;
switch(value) {
case code1:
if(itsONled[1] == 1) { // if first led is on then
digitalWrite(led1, LOW); // turn it off when button is pressed
itsONled[1] = 0; // and set its state as off
} else { // else if first led is off
digitalWrite(led1, HIGH); // turn it on when the button is pressed
itsONled[1] = 1; // and set its state as on
}
break;
case code2:
if(itsONled[2] == 1) {
digitalWrite(led2, LOW);
itsONled[2] = 0;
} else {
digitalWrite(led2, HIGH);
itsONled[2] = 1;
}
break;
case code3:
if(itsONled[3] == 1) {
digitalWrite(led3, LOW);
itsONled[3] = 0;
} else {
digitalWrite(led3, HIGH);
itsONled[3] = 1;
}
break;
}
Serial.println(value); // you can comment this line
irrecv.resume(); // Receive the next value
}
}
Kita akam melihat bahwa 3 lampu LED dikendalikan dengan satu tombol pada remote, masing-
masing tombol ketika ditekan pertama maka LED akan menyala dan ketika tombol ditekan untuk
kedua kalinya maka LED akan padam.

Sket berikut adalah modifikasi dari sket di atas, satu kode akan mengontrol sebuah kejadian, kalau
pada sket sebelumnya satu kode digunakan untuk memicu dua kejadian yaitu nyala dan padam,
susunan komponen masih sama.

/*
source: www.electroschematics.com
You'll need to change the led pins and the codes
accordingly to your configuration and IR remote
552656927
552600317
552624287
*/

#include <IRremote.h>

int RECV_PIN = 3; // the pin where you connect the output pin of TSOP4838
int led1 = 2;
int led2 = 4;
int led3 = 7;
int itsONled[] = {0,0,0,0};
/* the initial state of LEDs is OFF (zero)
the first zero must remain zero but you can
change the others to 1's if you want a certain
led to light when the board is powered */
#define code1 552656927 // code received from button A
#define code2 552600317 // code received from button B
#define code3 552624287 // code received from button C

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
Serial.begin(9600); // you can comment this line
irrecv.enableIRIn(); // Start the receiver
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}

void loop() {
if (irrecv.decode(&results)) {
unsigned int value = results.value;
switch(value) {
case code1:
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW); // turn it off when button is pressed

break;
case code2:
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
break;
case code3:
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
break;
}
Serial.println(value); // you can comment this line
irrecv.resume(); // Receive the next value
}
}
--------------------------------------------------------------------------------------------------------------
22. PENGUKURAN SUHU DENGAN LM35

IC LM 35 memiliki output 10 mV setiap kenaikan 1 derajat Celcius

int val;
int tempPin = 1;

void setup()
{
temperature = (5.0 * reading * 100.0) / 1024;
}
void loop()
{
val = analogRead(tempPin);
float mv = ( val/1024.0)*5000;
float cel = mv/10;
float farh = (cel*9)/5 + 32;

Serial.print("TEMPRATURE = ");
Serial.print(cel);
Serial.print("*C");
Serial.println();
delay(1000);

---------------------------------------------------------------------------------------------------------

Other sketch with internal reference

float temperature;
int reading;
int lm35Pin = 1;

void setup()
{
analogReference(INTERNAL);
Serial.begin(9600);
}

void loop()
{
reading = analogRead(lm35Pin);
temperature = reading / 9.31;
Serial.println(temperature);
delay(100);
}
---------------------------------------------------------------------------------------------------------------------
23. SETUP MICRO SD ARDUINO

Sket 1

Pada sket 1 ini kita membaca nilai analog dari 3 pin analog, hasil pembacaan ditampilkan pada
serial monitor dan disimpan ke SD card.

/*
SD card datalogger

This example shows how to log data from three analog sensors
to an SD card using the SD library.

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created 24 Nov 2010


modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.print("Initializing SD card...");

// see if the card is present and can be initialized:


if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}

void loop() {
// make a string for assembling the data to log:
String dataString = "";

// read three sensors and append to the string:


for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);
dataString += String(sensor);
if (analogPin < 2) {
dataString += " ";
}
}

// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
delay(1000);
}

Sket 2

Pada sket 2 ini pada bagian loop kita lakukan modifikasi

/*
SD card datalogger

This example shows how to log data from three analog sensors
to an SD card using the SD library.

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created 24 Nov 2010


modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.print("Initializing SD card...");

// see if the card is present and can be initialized:


if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}

void loop() {
// make a string for assembling the data to log:
String dataString0 = "";
String dataString1 = "";
String dataString2 = "";

int sensorValue0 = analogRead(A0);


int sensorValue1 = analogRead(A1);
int sensorValue2 = analogRead(A2);

dataString0 += String(sensorValue0);
dataString1 += String(sensorValue1);
dataString2 += String(sensorValue2);

// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);

// if the file is available, write to it:


if (dataFile) {
dataFile.print(dataString0);
dataFile.print(" ");
dataFile.print(dataString1);
dataFile.print(" ");
dataFile.println(dataString2);
dataFile.close();
// print to the serial port too:
Serial.print(dataString0);
Serial.print(" ");
Serial.print(dataString1);
Serial.print(" ");
Serial.println(dataString2);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
delay(1000);
}

Sket 3

Pada sket 3 ini kita menempatkan data pada file yang berbeda

/*
SD card datalogger

This example shows how to log data from three analog sensors
to an SD card using the SD library.

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created 24 Nov 2010


modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.print("Initializing SD card...");

// see if the card is present and can be initialized:


if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}

void loop() {
// make a string for assembling the data to log:
String dataString0 = "";
String dataString1 = "";
String dataString2 = "";

int sensorValue0 = analogRead(A0);


int sensorValue1 = analogRead(A1);
int sensorValue2 = analogRead(A2);

dataString0 += String(sensorValue0);
dataString1 += String(sensorValue1);
dataString2 += String(sensorValue2);

// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile0 = SD.open("datalog0.txt", FILE_WRITE);
File dataFile1 = SD.open("datalog1.txt", FILE_WRITE);
File dataFile2 = SD.open("datalog2.txt", FILE_WRITE);

// if the file is available, write to it:


if (dataFile0 && dataFile1 && dataFile2 ) {
dataFile0.println(dataString0);
//dataFile.print(" ");
dataFile1.println(dataString1);
//dataFile.print(" ");
dataFile2.println(dataString2);
dataFile0.close();
dataFile1.close();
dataFile2.close();
// print to the serial port too:
Serial.print(dataString0);
Serial.print(" ");
Serial.print(dataString1);
Serial.print(" ");
Serial.println(dataString2);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
delay(100);
}
Sket 4

Pada sket 4 ini kita aplikasikan pada penyimpanan data waktu yang dihasilkan dari RTC.
/*
SD card datalogger

This example shows how to log data from three analog sensors
to an SD card using the SD library.

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created 24 Nov 2010


modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;

const int chipSelect = 4;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

Serial.print("Initializing SD card...");

// see if the card is present and can be initialized:


if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
}

void loop() {
DateTime now = RTC.now();

File dataFile = SD.open("datalog.txt", FILE_WRITE);

// if the file is available, write to it:


if (dataFile) {
dataFile.print(now.year(), DEC);
dataFile.print('/');
dataFile.print(now.month(), DEC);
dataFile.print('/');
dataFile.print(now.day(), DEC);
dataFile.print(' ');
dataFile.print(now.hour(), DEC);
dataFile.print(':');
dataFile.print(now.minute(), DEC);
dataFile.print(':');
dataFile.print(now.second(), DEC);
dataFile.println();
dataFile.close();
// print to the serial port too:
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
delay(1000);
}
24. LDR ARDUINO

int LDR = 0;

// initialize the serial port


// and declare inputs and outputs
void setup() {
pinMode(LDR, INPUT);
Serial.begin(9600);
}

// read from the analog input connected to the LDR


// and print the value to the serial port.
// the delay is only to avoid sending so much data
// as to make it unreadable.
void loop() {
int v = analogRead(LDR);
Serial.println(v);
delay(1000);
}
25. MENGENDALIKAN LAMPU LED DENGAN LDR

// pin assignments
int LED = 13;
int LDR = 0;

// variables
int base;
int threshold = 100;

// declare inputs and outputs


// and take a baseline reading
void setup() {
pinMode(LED, OUTPUT);
pinMode(LDR, INPUT);
base = analogRead(LDR);
}

// read from the analog input connected to the LDR


// and print the value to the serial port.
// the delay is only to avoid sending so much data
// as to make it unreadable.
void loop() {
int v = analogRead(LDR);
if (v > threshold) {
digitalWrite(LED, LOW);
} else {
digitalWrite(LED, HIGH);
}
}

---------------------------------------------------------------------------------------------------------------
26.MENGUKUR TEGANGAN

/*--------------------------------------------------------------
Program: volt_measure

Description: Reads value on analog input A2 and calculates


the voltage assuming that a voltage divider
network on the pin divides by 11.

Hardware: Arduino Uno with voltage divider on A2.

Software: Developed using Arduino 1.0.5 software


Should be compatible with Arduino 1.0 +

Date: 22 May 2013

Author: W.A. Smith, http://startingelectronics.org


--------------------------------------------------------------*/

// number of analog samples to take per reading


#define NUM_SAMPLES 10

int sum = 0; // sum of samples taken


unsigned char sample_count = 0; // current sample number
float voltage = 0.0; // calculated voltage

void setup()
{
Serial.begin(9600);
}
void loop()
{
// take a number of analog samples and add them up
while (sample_count < NUM_SAMPLES) {
sum += analogRead(A2);
sample_count++;
delay(10);
}
// calculate the voltage
// use 5.0 for a 5.0V ADC reference voltage
// 5.015V is the calibrated reference voltage
voltage = ((float)sum / (float)NUM_SAMPLES * 5.015) / 1024.0;
// send voltage for display on Serial Monitor
// voltage multiplied by 11 when using voltage divider that
// divides by 11. 11.132 is the calibrated voltage divide
// value
Serial.print(voltage * 11.132);
Serial.println (" V");
sample_count = 0;
sum = 0;
}

-----------------------------------------------------------------------------------------------------------------
27. SETUP LCD I2C

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
/*
For details about the LCD display with I2C support see
http://www.fasttech.com/reviews/1380909/22072
and
http://dx.com/p/funduino-iic-i2c-1602-lcd-adapter-board-w-2-5-lcd-screen-black-green-red-173588
The reviewer comments by docpayce and particularly JackWP associated with the two product
pages above have been very useful.

Connect the LCD: VCC -> 5V, GND -> GND, SDA -> A4 (PortC4, ADC4), SCL -> A5 (PortC5,
SDA)

The LiquidCrystal_I2C library needs to be downloaded and installed from here:


https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home
*/

#define I2C_ADDR 0x27


#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

int SENSOR_PIN = 0; // center pin of the potentiometer

void setup()
{
lcd.begin(16,2); // initialize the lcd
lcd.home (); // go home
lcd.print("Hello, ARDUINO ");
delay(100);
}

void loop()
{
int sensorValue = analogRead(SENSOR_PIN);
// set cursor to second row, first column
lcd.setCursor(0, 1);
lcd.print("PIN VALUE=");
lcd.setCursor(12, 1);
lcd.print(sensorValue);
lcd.print("");
delay (1000);
}

----------------------------------------------------------------------------------------------------------------------
28. LED ON ARDUINO

Setting up LED arduino adalah hal yang paling sederhana. Pada permulaan pengguna atau yang
baru belajar Arduino, pemasangan LED ini menjadi dasar sebelum memulai ke proyek-protek lain.

Sket 1:
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.


*/

// Pin 8 has an LED connected on most Arduino boards.


// give it a name:
int led = 8;

// the setup routine runs once when you press reset:


void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

Sket 2:

// coder elangsakti
// Pin 8 untuk LED
const int pinLED = 8;
void setup() {
// pin LED sebagai output
pinMode(pinLED, OUTPUT);
}
// awal time delay 1000 | 1 detik
int timeDelay = 1000;
void loop() {
/* Jika timeDelay bernilai lebih kecil sama dengan 0
maka LED akan diam selama 3 detik
lalu nilai timeDelay direset ke 1000
*/
if(timeDelay <= 100){
delay(3000);
timeDelay = 1000;
}else{
// nilai timeDelay dikurangi 100 jika time delay > 100
timeDelay = timeDelay - 100;
}
//Nyalakan dan matikan LED selama timeDelay
digitalWrite(pinLED, HIGH);
delay(timeDelay);
digitalWrite(pinLED, LOW);
delay(timeDelay);
}

--------------------------------------------------------------------------------------------------------------------
29. MULTI LED

Pada multi LED ini kita sajikan pemasangan LED dengan menggunakan 16 pin yaitu D2 hingga
D13, dan tambahan 4 pin analog yang kita fungsikan sebagai pin digital.

Sket 1

// Free Ebook Arduino


// www.elangsakti.com
// coder elangsakti
// Inisialisasi Jumlah LED
const int numLED = 16;
// LED 1,2,3,&4 jadi 1 varibel
// dengaan alamat index 0,1,2,3
const int pinLED[numLED] = {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
void setup() {
// Inisialisasi semua pin LED sebagai OUTPUT
for(int i=0; i<16; i++){
pinMode(pinLED[i], OUTPUT);
}
}
void loop() {
// Matikan semua LED
for(int i=0; i<16; i++){
digitalWrite(pinLED[i], LOW);
}
delay(100);
// Hidupkan semua LED bertahap dg jeda 1 detik
for(int i=0; i<16; i++){
digitalWrite(pinLED[i], HIGH);
delay(100);
}
}

Sket 2

// Inisialisasi Pin LED


const int pinLED1 =2;
const int pinLED2 =3;
const int pinLED3 =4;
const int pinLED4 =5;
const int pinLED5 =6;
const int pinLED6 =7;
const int pinLED7 =8;
const int pinLED8 =9;
const int pinLED9 =10;
const int pinLED10=11;
const int pinLED11=12;
const int pinLED12=13;
const int pinLED13=14; // pin A0
const int pinLED14=15; // pin A1
const int pinLED15=16; // pin A2
const int pinLED16=17; // pin A3

void setup() {
// pin LED sebagai output
pinMode(pinLED1, OUTPUT);
pinMode(pinLED2, OUTPUT);
pinMode(pinLED3, OUTPUT);
pinMode(pinLED4, OUTPUT);
pinMode(pinLED5, OUTPUT);
pinMode(pinLED6, OUTPUT);
pinMode(pinLED7, OUTPUT);
pinMode(pinLED8, OUTPUT);
pinMode(pinLED9, OUTPUT);
pinMode(pinLED10, OUTPUT);
pinMode(pinLED11, OUTPUT);
pinMode(pinLED12, OUTPUT);
pinMode(pinLED13, OUTPUT);
pinMode(pinLED14, OUTPUT);
pinMode(pinLED15, OUTPUT);
pinMode(pinLED16, OUTPUT);
}
void loop() {
for(int i=0; i<17; i++){
if(i==1){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==2){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==3){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==4){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==5){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==6){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==7){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==8){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==9){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==10){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==11){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==12){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);
digitalWrite(pinLED12, HIGH);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==13){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);
digitalWrite(pinLED12, HIGH);
digitalWrite(pinLED13, HIGH);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==14){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);
digitalWrite(pinLED12, HIGH);
digitalWrite(pinLED13, HIGH);
digitalWrite(pinLED14, HIGH);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}else if(i==15){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);
digitalWrite(pinLED12, HIGH);
digitalWrite(pinLED13, HIGH);
digitalWrite(pinLED14, HIGH);
digitalWrite(pinLED15, HIGH);
digitalWrite(pinLED16, LOW);
}else if(i==16){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);
digitalWrite(pinLED12, HIGH);
digitalWrite(pinLED13, HIGH);
digitalWrite(pinLED14, HIGH);
digitalWrite(pinLED15, HIGH);
digitalWrite(pinLED16, HIGH);
}
else{
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
}
delay(100);
}
}

Sket 3

// Inisialisasi Pin LED


const int pinLED1 =2;
const int pinLED2 =3;
const int pinLED3 =4;
const int pinLED4 =5;
const int pinLED5 =6;
const int pinLED6 =7;
const int pinLED7 =8;
const int pinLED8 =9;
const int pinLED9 =10;
const int pinLED10=11;
const int pinLED11=12;
const int pinLED12=13;
const int pinLED13=14;
const int pinLED14=15;
const int pinLED15=16;
const int pinLED16=17;
void setup() {
// pin LED sebagai output
pinMode(pinLED1, OUTPUT);
pinMode(pinLED2, OUTPUT);
pinMode(pinLED3, OUTPUT);
pinMode(pinLED4, OUTPUT);
pinMode(pinLED5, OUTPUT);
pinMode(pinLED6, OUTPUT);
pinMode(pinLED7, OUTPUT);
pinMode(pinLED8, OUTPUT);
pinMode(pinLED9, OUTPUT);
pinMode(pinLED10, OUTPUT);
pinMode(pinLED11, OUTPUT);
pinMode(pinLED12, OUTPUT);
pinMode(pinLED13, OUTPUT);
pinMode(pinLED14, OUTPUT);
pinMode(pinLED15, OUTPUT);
pinMode(pinLED16, OUTPUT);
}
void loop() {
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
digitalWrite(pinLED12, LOW);
digitalWrite(pinLED13, LOW);
digitalWrite(pinLED14, LOW);
digitalWrite(pinLED15, LOW);
digitalWrite(pinLED16, LOW);
delay(100);
digitalWrite(pinLED1, HIGH);
delay(100);
digitalWrite(pinLED2, HIGH);
delay(100);
digitalWrite(pinLED3, HIGH);
delay(100);
digitalWrite(pinLED4, HIGH);
delay(100);
digitalWrite(pinLED5, HIGH);
delay(100);
digitalWrite(pinLED6, HIGH);
delay(100);
digitalWrite(pinLED7, HIGH);
delay(100);
digitalWrite(pinLED8, HIGH);
delay(100);
digitalWrite(pinLED9, HIGH);
delay(100);
digitalWrite(pinLED10, HIGH);
delay(100);
digitalWrite(pinLED11, HIGH);
delay(100);
digitalWrite(pinLED12, HIGH);
delay(100);
digitalWrite(pinLED13, HIGH);
delay(100);
digitalWrite(pinLED14, HIGH);
delay(100);
digitalWrite(pinLED15, HIGH);
delay(100);
digitalWrite(pinLED16, HIGH);
delay(100);
}

Sket 4

// Inisialisasi Jumlah LED


const int numLED = 16;
const int pinLED[numLED] = {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
void setup() {
for(int i=0; i<16; i++){
pinMode(pinLED[i], OUTPUT);
}
}
void loop() {
for(int i=0; i<15; i++){
digitalWrite(pinLED[i], HIGH);
delay(100);
digitalWrite(pinLED[i], LOW);
}
for(int i=15; i>0; i--){
digitalWrite(pinLED[i], HIGH);
delay(100);
digitalWrite(pinLED[i], LOW);
}
}

===============================================================
30. KAPASITIF SENSOR

#include <CapacitiveSensor.h>

/*
* CapitiveSense Library Demo Sketch
* Paul Badger 2008
* Uses a high value resistor e.g. 10M between send pin and receive pin
* Resistor effects sensitivity, experiment with values, 50K - 50M. Larger resistor values yield
larger sensor values.
* Receive pin is the sensor pin - try different amounts of foil/metal on this pin
*/
#include <Wire.h>
CapacitiveSensor cs_5_7 = CapacitiveSensor(5,7); // 10M resistor between pins 5 & 7, pin 7
is sensor pin, add a wire and or foil if desired
void setup()
{
cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate on channel 1 - just as
an example
Serial.begin(9600);
}
void loop()
{
long start = millis();
long total1 = cs_5_7.capacitiveSensor(30);
Serial.print(total1); // print sensor output 1
Serial.println("\t");
delay(100); // arbitrary delay to limit data to serial port
}

========================================================
31. LED PETERN dengan Shift Register IC 74HC595

Kita dapat menjalankan banyal LED dengan bantuan C 74HC595 dengan hanya memanfaatkan 3
pin dari Arduino. Pada dasarnya satu IC ini dapat menjalankan 8 LED. Dengan menggabungkan
beberapa IC maka kita dapat menjalankan LED kelipatan delapan. Pada gambar di bawah
ditampilkan dengan satu dan dua IC 595, kita bisa ekspansi dengan menambahkan IC 595 dengan
menghubungkan secara paralel semua pin ST_CP dan SH_CP, sedangkan pin DS terhubung dengan
pin nomer 9 pada IC 595 pendahulunya.
1x IC74HC595 (atas), 2x IC74HC595 (bawah)
PETERN-1 (1x IC74HC595)

/*
Adafruit Arduino - Lesson 4. 8 LEDs and a Shift Register
*/

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

byte leds = 0;

void setup()
{
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}

void loop()
{
leds = 0;
updateShiftRegister();
delay(100);
for (int i = 0; i < 8; i++)
{
bitSet(leds, i);
updateShiftRegister();
delay(100);
}
}

void updateShiftRegister()
{
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, HIGH);
}

PETERN-2 (1x IC74HC595 dapat juga 2x IC74HC595 )

//**************************************************************//
// Name : shiftOutCode, Dual One By One //
// Author : Carlyn Maw, Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//**************************************************************//

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holder for infromation you're going to pass to shifting function


byte data = 0;

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);

void loop() {

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(2,100);

// light each pin one by one using a function A


for (int j = 0; j < 8; j++) {
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
//red LEDs
lightShiftPinA(7-j);
//green LEDs
lightShiftPinA(j);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(100);

// light each pin one by one using a function A


for (int j = 0; j < 8; j++) {
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
//red LEDs
lightShiftPinB(j);
//green LEDs
lightShiftPinB(7-j);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(100);

}
}

//This function uses bitwise math to move the pins up


void lightShiftPinA(int p) {
//defines a local variable
int pin;

//this is line uses a bitwise operator


//shifting a bit left using << is the same
//as multiplying the decimal number by two.
pin = 1<< p;

//move 'em out


shiftOut(dataPin, clockPin, pin);

//This function uses that fact that each bit in a byte


//is 2 times greater than the one before it to
//shift the bits higher
void lightShiftPinB(int p) {
//defines a local variable
int pin;

//start with the pin = 1 so that if 0 is passed to this


//function pin 0 will light.
pin = 1;

for (int x = 0; x < p; x++) {


pin = pin * 2;
}
//move 'em out
shiftOut(dataPin, clockPin, pin);
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}

//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks both registers based on the number of times you want to


//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-3 (2x IC74HC595 )

//**************************************************************//
// Name : shiftOutCode, Predefined Dual Array Style //
// Author : Carlyn Maw, Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//****************************************************************

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holders for infromation you're going to pass to shifting function


byte dataRED;
byte dataGREEN;
byte dataArrayRED[10];
byte dataArrayGREEN[10];

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
Serial.begin(9600);

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.
dataArrayRED[0] = 0xFF; //11111111
dataArrayRED[1] = 0xFE; //11111110
dataArrayRED[2] = 0xFC; //11111100
dataArrayRED[3] = 0xF8; //11111000
dataArrayRED[4] = 0xF0; //11110000
dataArrayRED[5] = 0xE0; //11100000
dataArrayRED[6] = 0xC0; //11000000
dataArrayRED[7] = 0x80; //10000000
dataArrayRED[8] = 0x00; //00000000
dataArrayRED[9] = 0xE0; //11100000

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.
dataArrayGREEN[0] = 0xFF; //11111111
dataArrayGREEN[1] = 0x7F; //01111111
dataArrayGREEN[2] = 0x3F; //00111111
dataArrayGREEN[3] = 0x1F; //00011111
dataArrayGREEN[4] = 0x0F; //00001111
dataArrayGREEN[5] = 0x07; //00000111
dataArrayGREEN[6] = 0x03; //00000011
dataArrayGREEN[7] = 0x01; //00000001
dataArrayGREEN[8] = 0x00; //00000000
dataArrayGREEN[9] = 0x07; //00000111

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(1,100);
}

void loop() {

for (int j = 0; j < 10; j++) {


//load the light sequence you want from array
dataRED = dataArrayRED[j];
dataGREEN = dataArrayGREEN[j];
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
//move 'em out
shiftOut(dataPin, clockPin, dataGREEN);
shiftOut(dataPin, clockPin, dataRED);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(300);
}
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);
//for each bit in the byte myDataOut�
//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}

//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks the whole register based on the number of times you want to
//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-4 (1x IC74HC595 )

//**************************************************************//
// Name : shiftOutCode, Hello World
// Author : Carlyn Maw,Tom Igoe, David A. Mellis
// Date : 25 Oct, 2006
// Modified: 23 Mar 2010
// Version : 2.0
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255
//****************************************************************

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

void setup() {
//set pins to output so you can control the shift register
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}

void loop() {
// count from 0 to 255 and display the number
// on the LEDs
for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
// take the latchPin low so
// the LEDs don't change while you're sending in bits:
digitalWrite(latchPin, LOW);
// shift out the bits:
shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

//take the latch pin high so the LEDs will light up:
digitalWrite(latchPin, HIGH);
// pause before next value:
delay(500);
}
}
PETERN-5 (1x IC74HC595)

/*
Shift Register Example
Turning on the outputs of a 74HC595 using an array

Hardware:
* 74HC595 shift register
* LEDs attached to each of the outputs of the shift register

*/
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holders for infromation you're going to pass to shifting function


byte data;
byte dataArray[10];

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
Serial.begin(9600);

//Binary notation as comment


dataArray[0] = 0xFF; //0b11111111
dataArray[1] = 0xFE; //0b11111110
dataArray[2] = 0xFC; //0b11111100
dataArray[3] = 0xF8; //0b11111000
dataArray[4] = 0xF0; //0b11110000
dataArray[5] = 0xE0; //0b11100000
dataArray[6] = 0xC0; //0b11000000
dataArray[7] = 0x80; //0b10000000
dataArray[8] = 0x00; //0b00000000
dataArray[9] = 0xE0; //0b11100000

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(2,500);
}

void loop() {

for (int j = 0; j < 10; j++) {


//load the light sequence you want from array
data = dataArray[j];
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
//move 'em out
shiftOut(dataPin, clockPin, data);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(300);
}
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}
//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks the whole register based on the number of times you want to
//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-6 (1x IC74HC595)

int clockPin = 12; //IC Pin 11, Yellow Jumper


int dataPin = 11; //IC Pin 14, Blue Jumper
int latchPin = 8; //IC Pin 12, Green Jumper

byte patterns[30] = {
B00000001, 100,
B00000010, 100,
B00000100, 100,
B00001000, 100,
B00010000, 100,
B00100000, 100,
B01000000, 100,
B10000000, 100,
B01000000, 100,
B00100000, 100,
B00010000, 100,
B00001000, 100,
B00000100, 100,
B00000010, 100
};

int index = 0;
int count = sizeof(patterns) / 2;

void setup() {
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}

void loop() {
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, patterns[index * 2]);
digitalWrite(latchPin, HIGH);
delay(patterns[(index * 2) + 1]);
index++;
if (index >= count){
index = 0;
}
}

PETERN-7 (1x IC74HC595)

int clockPin = 12; //IC Pin 11, Yellow Jumper


int dataPin = 11; //IC Pin 14, Blue Jumper
int latchPin = 8; //IC Pin 12, Green Jumper

byte patterns[30] = {
B00000001, 500,
B00000010, 500,
B00000100, 500,
B00001000, 500,
B00010000, 500,
B00100000, 500,
B01000000, 500,
B10000000, 500,
B00000001, 250

};

int index = 0;
int count = sizeof(patterns) / 2;

void setup() {
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}

void loop() {
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, patterns[index * 2]);
digitalWrite(latchPin, HIGH);
delay(patterns[(index * 2) + 1]);
index++;
if (index >= count){
index = 0;
}
}

PETERN-8 (2x IC74HC595)

//**************************************************************//
// Name : shiftOutCode, Dual One By One //
// Author : Carlyn Maw, Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//**************************************************************//

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holder for infromation you're going to pass to shifting function


byte data = 0;

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);

void loop() {

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(2,100);

// light each pin one by one using a function A


for (int j = 0; j < 8; j++) {
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
//red LEDs
lightShiftPinA(7-j);
//green LEDs
lightShiftPinA(j);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(100);

// light each pin one by one using a function A


for (int j = 0; j < 8; j++) {
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
//red LEDs
lightShiftPinB(j);
//green LEDs
lightShiftPinB(7-j);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(100);

//This function uses bitwise math to move the pins up


void lightShiftPinA(int p) {
//defines a local variable
int pin;

//this is line uses a bitwise operator


//shifting a bit left using << is the same
//as multiplying the decimal number by two.
pin = 1<< p;

//move 'em out


shiftOut(dataPin, clockPin, pin);

//This function uses that fact that each bit in a byte


//is 2 times greater than the one before it to
//shift the bits higher
void lightShiftPinB(int p) {
//defines a local variable
int pin;

//start with the pin = 1 so that if 0 is passed to this


//function pin 0 will light.
pin = 1;
for (int x = 0; x < p; x++) {
pin = pin * 8;
}
//move 'em out
shiftOut(dataPin, clockPin, pin);
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}
//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks both registers based on the number of times you want to


//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-9 (2x IC74HC595)

//**************************************************************//
// Name : shiftOutCode, Predefined Dual Array Style //
// Author : Carlyn Maw, Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//****************************************************************

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holders for infromation you're going to pass to shifting function


byte dataRED;
byte dataGREEN;
byte dataArrayRED[10];
byte dataArrayGREEN[10];

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
Serial.begin(9600);

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.
dataArrayRED[0] = 0xFF; //11111111
dataArrayRED[1] = 0xFE; //11111110
dataArrayRED[2] = 0xFC; //11111100
dataArrayRED[3] = 0xF8; //11111000
dataArrayRED[4] = 0xF0; //11110000
dataArrayRED[5] = 0xE0; //11100000
dataArrayRED[6] = 0xC0; //11000000
dataArrayRED[7] = 0x80; //10000000
dataArrayRED[8] = 0x00; //00000000
dataArrayRED[9] = 0xE0; //11100000
dataArrayRED[10] = 0xAA; //10101010

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.
dataArrayGREEN[0] = 0xFF; //11111111
dataArrayGREEN[1] = 0x7F; //01111111
dataArrayGREEN[2] = 0x3F; //00111111
dataArrayGREEN[3] = 0x1F; //00011111
dataArrayGREEN[4] = 0x0F; //00001111
dataArrayGREEN[5] = 0x07; //00000111
dataArrayGREEN[6] = 0x03; //00000011
dataArrayGREEN[7] = 0x01; //00000001
dataArrayGREEN[8] = 0x00; //00000000
dataArrayGREEN[9] = 0x07; //00000111
dataArrayGREEN[10] = 0x55; //01010101

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(1,100);
}

void loop() {

for (int j = 0; j < 11; j++) {


//load the light sequence you want from array
dataRED = dataArrayRED[j];
dataGREEN = dataArrayGREEN[j];
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 0);
//move 'em out
shiftOut(dataPin, clockPin, dataGREEN);
shiftOut(dataPin, clockPin, dataRED);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 1);
delay(300);
}
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}
//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks the whole register based on the number of times you want to
//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-10 (2x IC74HC595)

int clockPin = 12; //IC Pin 11, Yellow Jumper


int dataPin = 11; //IC Pin 14, Blue Jumper
int latchPin = 8; //IC Pin 12, Green Jumper

byte patterns[30] = {
B00000001, 25,
B00000010, 25,
B00000100, 25,
B00001000, 25,
B00010000, 25,
B00100000, 25,
B01000000, 25,
B10000000, 25,
B00000001, 12.5

};

int index = 0;
int count = sizeof(patterns) / 2;
void setup() {
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}

void loop() {
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, patterns[index * 2]);
digitalWrite(latchPin, HIGH);
delay(patterns[(index * 2) + 1]);
index++;
if (index >= count){
index = 0;
}
}

PETERN-11 (2x IC74HC595)

//**************************************************************//
// Name : shiftOutCode, Predefined Dual Array Style //
// Author : Carlyn Maw, Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//****************************************************************

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holders for infromation you're going to pass to shifting function


byte dataRED;
byte dataGREEN;
byte dataArrayRED[16];
byte dataArrayGREEN[16];

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
Serial.begin(9600);

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.

dataArrayGREEN[0] = 0x80; //10000000


dataArrayGREEN[1] = 0x40; //01000000
dataArrayGREEN[2] = 0x20; //00100000
dataArrayGREEN[3] = 0x10; //00010000
dataArrayGREEN[4] = 0x08; //00001000
dataArrayGREEN[5] = 0x04; //00000100
dataArrayGREEN[6] = 0x02; //00000010
dataArrayGREEN[7] = 0x01; //00000001
dataArrayGREEN[8] = 0x00; //00000000
dataArrayGREEN[9] = 0x00; //00000000
dataArrayGREEN[10] = 0x00; //00000000
dataArrayGREEN[11] = 0x00; //00000000
dataArrayGREEN[12] = 0x00; //00000000
dataArrayGREEN[13] = 0x00; //00000000
dataArrayGREEN[14] = 0x00; //00000000
dataArrayGREEN[15] = 0x00; //00000000

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.

dataArrayRED[0] = 0x00; //00000000


dataArrayRED[1] = 0x00; //00000000
dataArrayRED[2] = 0x00; //00000000
dataArrayRED[3] = 0x00; //00000000
dataArrayRED[4] = 0x00; //00000000
dataArrayRED[5] = 0x00; //00000000
dataArrayRED[6] = 0x00; //00000000
dataArrayRED[7] = 0x00; //00000000
dataArrayRED[8] = 0x80; //10000000
dataArrayRED[9] = 0x40; //01000000
dataArrayRED[10] = 0x20; //00100000
dataArrayRED[11] = 0x10; //00010000
dataArrayRED[12] = 0x08; //00001000
dataArrayRED[13] = 0x04; //00000100
dataArrayRED[14] = 0x02; //00000010
dataArrayRED[15] = 0x01; //00000001

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(2,300);
}

void loop() {

for (int j = 0; j < 16; j++) {


//load the light sequence you want from array
dataRED = dataArrayRED[j];
dataGREEN = dataArrayGREEN[j];
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 1);
//move 'em out
shiftOut(dataPin, clockPin, dataGREEN);
shiftOut(dataPin, clockPin, dataRED);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 0);
delay(100);
}
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}
//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks the whole register based on the number of times you want to
//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-12 (3x IC74HC595)

//**************************************************************//
// Name : shiftOutCode, Predefined Dual Array Style //
// Author : Carlyn Maw, Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//****************************************************************

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holders for infromation you're going to pass to shifting function


byte dataRED;
byte dataGREEN;
byte dataBLUE;
byte dataArrayRED[24];
byte dataArrayGREEN[24];
byte dataArrayBLUE[24];

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
Serial.begin(9600);

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.

dataArrayGREEN[0] = 0x80; //10000000


dataArrayGREEN[1] = 0x40; //01000000
dataArrayGREEN[2] = 0x20; //00100000
dataArrayGREEN[3] = 0x10; //00010000
dataArrayGREEN[4] = 0x08; //00001000
dataArrayGREEN[5] = 0x04; //00000100
dataArrayGREEN[6] = 0x02; //00000010
dataArrayGREEN[7] = 0x01; //00000001
dataArrayGREEN[8] = 0x00; //00000000
dataArrayGREEN[9] = 0x00; //00000000
dataArrayGREEN[10] = 0x00; //00000000
dataArrayGREEN[11] = 0x00; //00000000
dataArrayGREEN[12] = 0x00; //00000000
dataArrayGREEN[13] = 0x00; //00000000
dataArrayGREEN[14] = 0x00; //00000000
dataArrayGREEN[15] = 0x00; //00000000
dataArrayGREEN[16] = 0x00; //00000000
dataArrayGREEN[17] = 0x00; //00000000
dataArrayGREEN[18] = 0x00; //00000000
dataArrayGREEN[19] = 0x00; //00000000
dataArrayGREEN[20] = 0x00; //00000000
dataArrayGREEN[21] = 0x00; //00000000
dataArrayGREEN[22] = 0x00; //00000000
dataArrayGREEN[23] = 0x00; //00000000

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.

dataArrayRED[0] = 0x00; //00000000


dataArrayRED[1] = 0x00; //00000000
dataArrayRED[2] = 0x00; //00000000
dataArrayRED[3] = 0x00; //00000000
dataArrayRED[4] = 0x00; //00000000
dataArrayRED[5] = 0x00; //00000000
dataArrayRED[6] = 0x00; //00000000
dataArrayRED[7] = 0x00; //00000000
dataArrayRED[8] = 0x80; //10000000
dataArrayRED[9] = 0x40; //01000000
dataArrayRED[10] = 0x20; //00100000
dataArrayRED[11] = 0x10; //00010000
dataArrayRED[12] = 0x08; //00001000
dataArrayRED[13] = 0x04; //00000100
dataArrayRED[14] = 0x02; //00000010
dataArrayRED[15] = 0x01; //00000001
dataArrayRED[16] = 0x00; //00000000
dataArrayRED[17] = 0x00; //00000000
dataArrayRED[18] = 0x00; //00000000
dataArrayRED[19] = 0x00; //00000000
dataArrayRED[20] = 0x00; //00000000
dataArrayRED[21] = 0x00; //00000000
dataArrayRED[22] = 0x00; //00000000
dataArrayRED[23] = 0x00; //00000000

dataArrayBLUE[0] = 0x00; //00000000


dataArrayBLUE[1] = 0x00; //00000000
dataArrayBLUE[2] = 0x00; //00000000
dataArrayBLUE[3] = 0x00; //00000000
dataArrayBLUE[4] = 0x00; //00000000
dataArrayBLUE[5] = 0x00; //00000000
dataArrayBLUE[6] = 0x00; //00000000
dataArrayBLUE[7] = 0x00; //00000000
dataArrayBLUE[8] = 0x00; //00000000
dataArrayBLUE[9] = 0x00; //00000000
dataArrayBLUE[10] = 0x00; //00000000
dataArrayBLUE[11] = 0x00; //00000000
dataArrayBLUE[12] = 0x00; //00000000
dataArrayBLUE[13] = 0x00; //00000000
dataArrayBLUE[14] = 0x00; //00000000
dataArrayBLUE[15] = 0x00; //00000000
dataArrayBLUE[16] = 0x80; //10000000
dataArrayBLUE[17] = 0x40; //01000000
dataArrayBLUE[18] = 0x20; //00100000
dataArrayBLUE[19] = 0x10; //00010000
dataArrayBLUE[20] = 0x08; //00001000
dataArrayBLUE[21] = 0x04; //00000100
dataArrayBLUE[22] = 0x02; //00000010
dataArrayBLUE[23] = 0x01; //00000001

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(2,300);
}

void loop() {

for (int j = 0; j < 24; j++) {


//load the light sequence you want from array
dataGREEN = dataArrayGREEN[j];
dataRED = dataArrayRED[j];
dataBLUE = dataArrayBLUE[j];
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 1);
//move 'em out
shiftOut(dataPin, clockPin, dataGREEN);
shiftOut(dataPin, clockPin, dataRED);
shiftOut(dataPin, clockPin, dataBLUE);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 0);
delay(100);
}
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}

//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks the whole register based on the number of times you want to
//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-13 (3x IC74HC595)

//**************************************************************//
// Name : shiftOutCode, Predefined Dual Array Style //
// Author : Carlyn Maw, Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//****************************************************************

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holders for infromation you're going to pass to shifting function


byte dataRED;
byte dataGREEN;
byte dataBLUE;
byte dataArrayRED[24];
byte dataArrayGREEN[24];
byte dataArrayBLUE[24];

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
Serial.begin(9600);

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.

dataArrayGREEN[0] = 0x80; //10000000


dataArrayGREEN[1] = 0x40; //01000000
dataArrayGREEN[2] = 0x20; //00100000
dataArrayGREEN[3] = 0x10; //00010000
dataArrayGREEN[4] = 0x08; //00001000
dataArrayGREEN[5] = 0x04; //00000100
dataArrayGREEN[6] = 0x02; //00000010
dataArrayGREEN[7] = 0x01; //00000001
dataArrayGREEN[8] = 0x00; //00000000
dataArrayGREEN[9] = 0x00; //00000000
dataArrayGREEN[10] = 0x00; //00000000
dataArrayGREEN[11] = 0x00; //00000000
dataArrayGREEN[12] = 0x00; //00000000
dataArrayGREEN[13] = 0x00; //00000000
dataArrayGREEN[14] = 0x00; //00000000
dataArrayGREEN[15] = 0x00; //00000000
dataArrayGREEN[16] = 0x01; //00000000
dataArrayGREEN[17] = 0x02; //00000000
dataArrayGREEN[18] = 0x04; //00000000
dataArrayGREEN[19] = 0x08; //00000000
dataArrayGREEN[20] = 0x10; //00000000
dataArrayGREEN[21] = 0x20; //00000000
dataArrayGREEN[22] = 0x40; //00000000
dataArrayGREEN[23] = 0x80; //00000000

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.

dataArrayRED[0] = 0x00; //00000000


dataArrayRED[1] = 0x00; //00000000
dataArrayRED[2] = 0x00; //00000000
dataArrayRED[3] = 0x00; //00000000
dataArrayRED[4] = 0x00; //00000000
dataArrayRED[5] = 0x00; //00000000
dataArrayRED[6] = 0x00; //00000000
dataArrayRED[7] = 0x00; //00000000
dataArrayRED[8] = 0x81; //10000000
dataArrayRED[9] = 0x42; //01000000
dataArrayRED[10] = 0x24; //00100000
dataArrayRED[11] = 0x18; //00010000
dataArrayRED[12] = 0x18; //00001000
dataArrayRED[13] = 0x24; //00000100
dataArrayRED[14] = 0x42; //00000010
dataArrayRED[15] = 0x81; //00000001
dataArrayRED[16] = 0x00; //00000000
dataArrayRED[17] = 0x00; //00000000
dataArrayRED[18] = 0x00; //00000000
dataArrayRED[19] = 0x00; //00000000
dataArrayRED[20] = 0x00; //00000000
dataArrayRED[21] = 0x00; //00000000
dataArrayRED[22] = 0x00; //00000000
dataArrayRED[23] = 0x00; //00000000

dataArrayBLUE[0] = 0x01; //00000000


dataArrayBLUE[1] = 0x02; //00000000
dataArrayBLUE[2] = 0x04; //00000000
dataArrayBLUE[3] = 0x08; //00000000
dataArrayBLUE[4] = 0x10; //00000000
dataArrayBLUE[5] = 0x20; //00000000
dataArrayBLUE[6] = 0x40; //00000000
dataArrayBLUE[7] = 0x80; //00000000
dataArrayBLUE[8] = 0x00; //00000000
dataArrayBLUE[9] = 0x00; //00000000
dataArrayBLUE[10] = 0x00; //00000000
dataArrayBLUE[11] = 0x00; //00000000
dataArrayBLUE[12] = 0x00; //00000000
dataArrayBLUE[13] = 0x00; //00000000
dataArrayBLUE[14] = 0x00; //00000000
dataArrayBLUE[15] = 0x00; //00000000
dataArrayBLUE[16] = 0x80; //10000000
dataArrayBLUE[17] = 0x40; //01000000
dataArrayBLUE[18] = 0x20; //00100000
dataArrayBLUE[19] = 0x10; //00010000
dataArrayBLUE[20] = 0x08; //00001000
dataArrayBLUE[21] = 0x04; //00000100
dataArrayBLUE[22] = 0x02; //00000010
dataArrayBLUE[23] = 0x01; //00000001

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(2,300);
}
void loop() {

for (int j = 0; j < 24; j++) {


//load the light sequence you want from array
dataGREEN = dataArrayGREEN[j];
dataRED = dataArrayRED[j];
dataBLUE = dataArrayBLUE[j];
//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 1);
//move 'em out
shiftOut(dataPin, clockPin, dataGREEN);
shiftOut(dataPin, clockPin, dataRED);
shiftOut(dataPin, clockPin, dataBLUE);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 0);
delay(100);
}
}

// the heart of the program


void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}

//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks the whole register based on the number of times you want to
//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-14 (2x IC74HC595)

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

byte dataRED;
byte dataGREEN;
byte dataArrayRED[61];
byte dataArrayGREEN[61];

void setup() {

pinMode(latchPin, OUTPUT);
Serial.begin(9600);

dataArrayGREEN[0] = 0xC0; //11000000


dataArrayGREEN[1] = 0xC0; //11000000
dataArrayGREEN[2] = 0x80; //10000000
dataArrayGREEN[3] = 0x80; //10000000
dataArrayGREEN[4] = 0x80; //10000000
dataArrayGREEN[5] = 0x80; //10000000
dataArrayGREEN[6] = 0x80; //10000000
dataArrayGREEN[7] = 0x80; //10000000
dataArrayGREEN[8] = 0x30; //11000000
dataArrayGREEN[9] = 0x30; //11000000
dataArrayGREEN[10] = 0x20; //00100000
dataArrayGREEN[11] = 0x20; //00100000
dataArrayGREEN[12] = 0x20; //00100000
dataArrayGREEN[13] = 0x08; //00001000
dataArrayGREEN[14] = 0x08; //00001000
dataArrayGREEN[15] = 0x08; //00001000
dataArrayGREEN[16] = 0x08; //00001000
dataArrayGREEN[17] = 0x08; //00001000
dataArrayGREEN[18] = 0x08; //00001000
dataArrayGREEN[19] = 0x00; //00000000
dataArrayGREEN[20] = 0x00; //00000000
dataArrayGREEN[21] = 0x00; //00000000
dataArrayGREEN[22] = 0x04; //00000100
dataArrayGREEN[23] = 0x12; //00010010
dataArrayGREEN[24] = 0x12; //00010010
dataArrayGREEN[25] = 0x02; //00000010
dataArrayGREEN[26] = 0x02; //00000010
dataArrayGREEN[27] = 0x02; //00000010
dataArrayGREEN[28] = 0x01; //00000001
dataArrayGREEN[29] = 0x01; //00000001
dataArrayGREEN[30] = 0x01; //00000001
dataArrayGREEN[31] = 0x01; //00000001
dataArrayGREEN[32] = 0x01; //00000001
dataArrayGREEN[33] = 0x01; //00000001
dataArrayGREEN[34] = 0x00; //00000000
dataArrayGREEN[35] = 0x00; //00000000
dataArrayGREEN[36] = 0x00; //00000000
dataArrayGREEN[37] = 0x00; //00000000
dataArrayGREEN[38] = 0x00; //00000000
dataArrayGREEN[39] = 0x00; //00000000
dataArrayGREEN[40] = 0x00; //00000000
dataArrayGREEN[41] = 0x00; //00000000
dataArrayGREEN[42] = 0x00; //00000000
dataArrayGREEN[43] = 0x00; //00000000
dataArrayGREEN[44] = 0x00; //00000000
dataArrayGREEN[45] = 0x00; //00000000
dataArrayGREEN[46] = 0x00; //00000000
dataArrayGREEN[47] = 0x00; //00000000
dataArrayGREEN[48] = 0x00; //10000000
dataArrayGREEN[49] = 0x00; //01000000
dataArrayGREEN[50] = 0x00; //00100000
dataArrayGREEN[51] = 0x00; //00010000
dataArrayGREEN[52] = 0x40; //00100000
dataArrayGREEN[53] = 0x40; //00100000
dataArrayGREEN[54] = 0x00; //00000000
dataArrayGREEN[55] = 0x00; //00000000
dataArrayGREEN[56] = 0x00; //00000000
dataArrayGREEN[57] = 0x00; //00000000
dataArrayGREEN[58] = 0x00; //00000000
dataArrayGREEN[59] = 0x00; //00000000
dataArrayGREEN[60] = 0x00; //00000000

dataArrayRED[0] = 0x00; //00000000


dataArrayRED[1] = 0x00; //00000000
dataArrayRED[2] = 0x00; //00000000
dataArrayRED[3] = 0x00; //00000000
dataArrayRED[4] = 0x00; //00000000
dataArrayRED[5] = 0x00; //00000000
dataArrayRED[6] = 0x00; //00000000
dataArrayRED[7] = 0x00; //00000000
dataArrayRED[8] = 0x00; //00000000
dataArrayRED[9] = 0x00; //00000000
dataArrayRED[10] = 0x00; //00000000
dataArrayRED[11] = 0x00; //00000000
dataArrayRED[12] = 0x00; //00000000
dataArrayRED[13] = 0x00; //00000000
dataArrayRED[14] = 0x00; //00000000
dataArrayRED[15] = 0x00; //00000000
dataArrayRED[16] = 0x00; //00000000
dataArrayRED[17] = 0x00; //00000000
dataArrayRED[18] = 0x00; //00000000
dataArrayRED[19] = 0x00; //00000000
dataArrayRED[20] = 0x00; //00000000
dataArrayRED[21] = 0x00; //00000000
dataArrayRED[22] = 0x00; //00000000
dataArrayRED[23] = 0x00; //00000000
dataArrayRED[24] = 0x00; //00000000
dataArrayRED[25] = 0x00; //00000000
dataArrayRED[26] = 0x00; //00000000
dataArrayRED[27] = 0x00; //00000000
dataArrayRED[28] = 0x00; //00000000
dataArrayRED[29] = 0x00; //00000000
dataArrayRED[30] = 0x00; //00000000
dataArrayRED[31] = 0x00; //00000000
dataArrayRED[32] = 0x00; //00000000
dataArrayRED[33] = 0x00; //00000000
dataArrayRED[34] = 0x80; //10000000
dataArrayRED[35] = 0x60; //01100000
dataArrayRED[36] = 0x60; //01100000
dataArrayRED[37] = 0x40; //00100000
dataArrayRED[38] = 0x40; //00100000
dataArrayRED[39] = 0x40; //00100000
dataArrayRED[40] = 0x10; //00010000
dataArrayRED[41] = 0x10; //00010000
dataArrayRED[42] = 0x10; //00010000
dataArrayRED[43] = 0x10; //00010000
dataArrayRED[44] = 0x10; //00010000
dataArrayRED[45] = 0x10; //00010000
dataArrayRED[46] = 0x28; //00101001
dataArrayRED[47] = 0x28; //00101001
dataArrayRED[48] = 0x08; //00001000
dataArrayRED[49] = 0x08; //00001000
dataArrayRED[50] = 0x08; //00001000
dataArrayRED[51] = 0x04; //00000100
dataArrayRED[52] = 0x02; //00000010
dataArrayRED[53] = 0x02; //00000010
dataArrayRED[54] = 0x02; //00000010
dataArrayRED[55] = 0x02; //00000010
dataArrayRED[56] = 0x02; //00000010
dataArrayRED[57] = 0x02; //00000010
dataArrayRED[58] = 0x02; //00000010
dataArrayRED[59] = 0x02; //00000010
dataArrayRED[60] = 0x01; //00000001

blinkAll_2Bytes(2,300);
}

void loop() {

for (int j = 0; j < 61; j++) {

dataRED = dataArrayRED[j];
dataGREEN = dataArrayGREEN[j];

digitalWrite(latchPin, 1);
shiftOut(dataPin, clockPin, dataGREEN);
shiftOut(dataPin, clockPin, dataRED);

digitalWrite(latchPin, 0);
delay(300);
}
}

void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {

int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

for (i=7; i>=0; i--) {


digitalWrite(myClockPin, 0);

if ( myDataOut & (1<<i) ) {


pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}

//stop shifting
digitalWrite(myClockPin, 0);
}

void blinkAll_2Bytes(int n, int d) {


digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}

PETERN-15 (1x IC74HC595)

int clockPin = 12; //IC Pin 11, Yellow Jumper


int dataPin = 11; //IC Pin 14, Blue Jumper
int latchPin = 8; //IC Pin 12, Green Jumper

byte patterns[30] = {
B00000001, 50,
B00000010, 50,
B00000100, 50,
B00001000, 50,
B00010000, 50,
B00100000, 50,
B01000000, 50,
B10000000, 50,
B01000000, 50,
B00100000, 50,
B00010000, 50,
B00001000, 50,
B00000100, 50,
B00000010, 50,
B00000001, 50
};

int index = 0;
int count = sizeof(patterns) / 2;

void setup() {
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, patterns[index * 2]);
digitalWrite(latchPin, HIGH);
delay(patterns[(index * 2) + 1]);
index++;
if (index >= count){
index = 0;
}
}
====================================================================
32. LED MATRIX MAPPING

Kita demonstrasikan bagaimana menyalakan LED matrix satu atau beberapa titik, kita gunakan satu
LED matrix saja.

//We always have to include the library


#include "LedControlMS.h"

/*
Now we need a LedControl to work with.
***** These pin numbers will probably not work with your hardware *****
pin 12 is connected to the DataIn
pin 10 is connected to the CLK
pin 11 is connected to LOAD
We have only a single MAX72XX.
*/
#define NBR_MTX 1 //jumlah module LED matrix yang kita gunakan
LedControl lc=LedControl(12,11,10, NBR_MTX);
//String digits= "1234567890";
int digitCounter=0;
/* we always wait a bit between updates of the display */
unsigned long delaytime=300;
void setup() {
/*
The MAX72XX is in power-saving mode on startup,
we have to do a wakeup call
*/
Serial.begin (9600);
Serial.println("Setup");
digitCounter=0;
for (int i=0; i< NBR_MTX; i++){
lc.shutdown(i,false);
/* Set the brightness to a medium values */
lc.setIntensity(i,8);
/* and clear the display */
lc.clearDisplay(i);

void loop() {
Serial.println("LED0: 0 0");
lc.setLed(0,2,3,true); // (0,0,7) = (nomor LED matrix terpakai-mulai dari nol, ROW, Column)
lc.setLed(0,5,2,true);
lc.setLed(0,1,6,true);

void scrollLeft(char ch){


int pos =lc.getCharArrayPosition(ch);
for (int scroll =0; scroll<6; scroll++) {
for (int i=scroll; i<6;i++) {
lc.setRow(0,i-scroll, alphabetBitmap[pos][i]);
}
delay(300);
lc.clearDisplay(0);
}
}

void scrollRight(char ch){


int pos =lc.getCharArrayPosition(ch);
for (int scroll =0; scroll<8; scroll++) {
for (int i=0; i<6;i++) {
if (scroll+i<8) lc.setRow(0, scroll+i, alphabetBitmap[pos][i]);
}
delay(300);
lc.clearDisplay(0);
}
}
33. LED MATRIX-1 (satu LED matrix)

unsigned char i;
unsigned char j;
/*Port Definitions*/
int Max7219_pinCLK = 10;
int Max7219_pinCS = 11;
int Max7219_pinDIN = 12;

unsigned char disp1[38][8]={


{0x00,0x7e,0x81,0x81,0x81,0x7e,0x00,0x00},//0
{0x00,0x00,0x82,0xff,0x80,0x00,0x00,0x00},//1
{0x00,0xc2,0xa1,0x91,0x89,0x86,0x00,0x00},//2
{0x00,0x81,0x89,0x89,0x89,0x76,0x00,0x00},//3
{0x00,0x10,0x18,0x14,0x12,0xff,0x10,0x00},//4
{0x00,0x8f,0x89,0x89,0x89,0x71,0x00,0x00},//5
{0x00,0x7e,0x89,0x89,0x89,0x70,0x00,0x00},//6
{0x00,0x83,0x41,0x21,0x11,0x09,0x07,0x00},//7
{0x00,0x76,0x89,0x89,0x89,0x76,0x00,0x00},//8
{0x00,0x4e,0x89,0x89,0x89,0x7e,0x00,0x00},//9
{0x00,0xfe,0x11,0x11,0x11,0xfe,0x00,0x00},//A
{0x00,0xff,0x89,0x89,0x9d,0x76,0x00,0x00},//B
{0x00,0x7e,0x81,0x81,0x81,0x42,0x00,0x00},//C
{0x00,0xff,0x81,0x81,0x81,0x42,0x3c,0x00},//D
{0x00,0xff,0x89,0x89,0x89,0x81,0x00,0x00},//E
{0x00,0xff,0x09,0x09,0x09,0x01,0x00,0x00},//F
{0x00,0x7e,0x89,0x89,0x89,0x72,0x00,0x00},//G
{0x00,0xff,0x08,0x08,0x08,0xff,0x00,0x00},//H
{0x00,0x00,0x81,0xff,0x81,0x00,0x00,0x00},//I
{0x00,0x40,0x80,0x81,0x7f,0x01,0x00,0x00},//J
{0x00,0x00,0xff,0x08,0x14,0x22,0xc1,0x00},//K
{0x00,0x00,0xff,0x80,0x80,0x80,0x00,0x00},//L
{0x00,0xff,0x01,0x02,0x0c,0x02,0x01,0xff},//M
{0x00,0xff,0x02,0x04,0x08,0x10,0x20,0xff},//N
{0x00,0x7e,0x81,0x81,0x81,0x7e,0x00,0x00},//O
{0x00,0xff,0x11,0x11,0x11,0x0e,0x00,0x00},//P
{0x00,0x3e,0x41,0x61,0x41,0xbe,0x00,0x00},//Q
{0x00,0xff,0x31,0x31,0x51,0x8e,0x00,0x00},//R
{0x00,0x4e,0x89,0x89,0x89,0x72,0x00,0x00},//S
{0x00,0x01,0x01,0xff,0x01,0x01,0x00,0x00},//T
{0x00,0x7f,0x80,0x80,0x80,0x7f,0x00,0x00},//U
{0x03,0x0c,0x30,0xc0,0x30,0x0c,0x03,0x00},//V
{0x00,0x1f,0x60,0x80,0x78,0x80,0x60,0x1f},//W
{0x00,0xc3,0x24,0x18,0x18,0x24,0xc3,0x00},//X
{0x01,0x06,0x08,0xf0,0x08,0x06,0x01,0x00},//Y
{0x00,0xc1,0xa1,0x91,0x89,0x85,0x83,0x00},//Z
};
//this character written in hexadecimal mode
//can be design with : http://blog.riyas.org/2013/12/online-led-matrix-font-generator-with.html
void Write_Max7219_byte(unsigned char DATA)
{
unsigned char i;
digitalWrite(Max7219_pinCS,LOW);
for(i=8;i>=1;i--)
{
digitalWrite(Max7219_pinCLK,LOW);
digitalWrite(Max7219_pinDIN,DATA&0x80);// Extracting a bit data
DATA = DATA<<1;
digitalWrite(Max7219_pinCLK,HIGH);
}
}

void Write_Max7219(unsigned char address,unsigned char dat)


{
digitalWrite(Max7219_pinCS,LOW);
Write_Max7219_byte(address); //address,code of LED
Write_Max7219_byte(dat); //data,figure on LED
digitalWrite(Max7219_pinCS,HIGH);
}

void Init_MAX7219(void)
{
Write_Max7219(0x09, 0x00); //decoding :BCD
Write_Max7219(0x0a, 0x03); //brightness
Write_Max7219(0x0b, 0x07); //scanlimit;8 LEDs
Write_Max7219(0x0c, 0x01); //power-down mode:0,normal mode:1
Write_Max7219(0x0f, 0x00); //test display:1;EOT,display:0
}

void setup()
{

pinMode(Max7219_pinCLK,OUTPUT);
pinMode(Max7219_pinCS,OUTPUT);
pinMode(Max7219_pinDIN,OUTPUT);
delay(50);
Init_MAX7219();
}

void loop()
{
for(j=0;j<38;j++)
{
for(i=1;i<9;i++)
Write_Max7219(i,disp1[j][i-1]);
delay(500);
}
}

LED MATRIX-2 (satu LED matrix)

#include "LedControlMS.h"
//pin 12 is connected to the DataIn
// pin 10 is connected to the CLK
//pin 11 is connected to LOAD

#define NBR_MTX 1 //number of matrices attached is one


LedControl lc=LedControl(12,10,11, NBR_MTX);//

void setup()
{
for (int i=0; i< NBR_MTX; i++)
{
lc.shutdown(i,false);
/* Set the brightness to a medium values */
lc.setIntensity(i,8);
/* and clear the display */
lc.clearDisplay(i);
delay(100);
}
}

void loop()
{
lc.writeString(0,"CIRCUITDIGEST");//sending characters to display
lc.clearAll();//clearing the display
delay(1000);
}

LED MATRIX-3 (satu LED matrix)

/*
* Arduino Sweet Heart
* An Arduino & 8x8 LED dot matrix project
* Using Max7219 IC
* Designed by T.K.Hareendran
* Tested at TechNode Protolabz
* 17 July 2014
* http://www.electroschematics.com
*/

unsigned char i;
unsigned char j;
int Max7219_pinCLK = 10;
int Max7219_pinCS = 11;
int Max7219_pinDIN = 12;

unsigned char disp1[19][8]={


0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Heart Pattern
0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x40, 0x40, 0x00, 0x00, 0x00,
0x00, 0x80, 0x80, 0x40, 0x40, 0x00, 0x00, 0x00,
0x40, 0x80, 0x80, 0x40, 0x40, 0x00, 0x00, 0x00,
0x60, 0x80, 0x80, 0x40, 0x40, 0x00, 0x00, 0x00,
0x60, 0x90, 0x80, 0x40, 0x40, 0x00, 0x00, 0x00,
0x60, 0x90, 0x88, 0x40, 0x40, 0x00, 0x00, 0x00,
0x60, 0x90, 0x88, 0x44, 0x40, 0x00, 0x00, 0x00,
0x60, 0x90, 0x88, 0x44, 0x44, 0x00, 0x00, 0x00,
0x60, 0x90, 0x88, 0x44, 0x44, 0x08, 0x00, 0x00,
0x60, 0x90, 0x88, 0x44, 0x44, 0x08, 0x10, 0x00,
0x60, 0x90, 0x88, 0x44, 0x44, 0x08, 0x10, 0x20,
0x60, 0x90, 0x88, 0x44, 0x44, 0x08, 0x10, 0x60,
0x60, 0x90, 0x88, 0x44, 0x44, 0x08, 0x90, 0x60,
0x60, 0x90, 0x88, 0x44, 0x44, 0x88, 0x90, 0x60, // Heart Pattern

};

void Write_Max7219_byte(unsigned char DATA)


{
unsigned char i;
digitalWrite(Max7219_pinCS,LOW);
for(i=8;i>=1;i--)
{
digitalWrite(Max7219_pinCLK,LOW);
digitalWrite(Max7219_pinDIN,DATA&0x80);
DATA = DATA<<1;
digitalWrite(Max7219_pinCLK,HIGH);
}
}

void Write_Max7219(unsigned char address,unsigned char dat)


{
digitalWrite(Max7219_pinCS,LOW);
Write_Max7219_byte(address);
Write_Max7219_byte(dat);
digitalWrite(Max7219_pinCS,HIGH);
}

void Init_MAX7219(void)
{
Write_Max7219(0x09, 0x00);
Write_Max7219(0x0a, 0x03);
Write_Max7219(0x0b, 0x07);
Write_Max7219(0x0c, 0x01);
Write_Max7219(0x0f, 0x00);
}

void setup()
{

pinMode(Max7219_pinCLK,OUTPUT);
pinMode(Max7219_pinCS,OUTPUT);
pinMode(Max7219_pinDIN,OUTPUT);
delay(50);
Init_MAX7219();
}

void loop()
{
for(j=0;j<19;j++)
{
for(i=1;i<9;i++)
Write_Max7219(i,disp1[j][i-1]);
delay(500);
}
}

LED MATRIX-4 (satu LED matrix)

#define Rb5 11 // CS
#define Rb6 12 // DATA
#define Rb7 10 // CLK

// pattern for 8 X 8 LED matrix


char array1[] = {
0x00, 0x00, 0x81, 0x42, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00 };

void setup() {

pinMode(Rb5, OUTPUT);
pinMode(Rb6, OUTPUT);
pinMode(Rb7, OUTPUT);
digitalWrite(Rb5, LOW);
}

void loop() {
delay(1000);

init_MAX7219();

int k = 0;
while(1) {
for (int j=1; j<9; j++) {
writeMAX7219(j+k, array1[j]);
}
delay(50);
k++;
if (k > 8) k = 0;
}
}

// shift data to MAX7219


// Rb7 -> CLK, Rb6 -> DATA, Rb5 -> CS not
void ssrOut(unsigned char val) {
int j;
for(j=1; j<=8; j++) { // shift out MSB first
unsigned char temp = val & 0x80; // MSB out first
if (temp == 0x80) digitalWrite(Rb6, 1); // Rb6 DATA
else digitalWrite(Rb6, 0);
digitalWrite(Rb7, 1);
delayMicroseconds(10);
digitalWrite(Rb7, 0);
val = val << 1; // shift one place left
} // next j
}

void pulseCS(void) {
digitalWrite(Rb5, 1);
delay(1);
digitalWrite(Rb5, 0);
}

void init_MAX7219(void) {
digitalWrite(Rb5, 0); // CS NOT

// set decode mode


ssrOut(0x09);
ssrOut(0x00); // no decode
pulseCS();

// set intensity
ssrOut(0x0A);
ssrOut(0x08); // 0 - F
pulseCS();

// set scan limit


ssrOut(0x0B);
ssrOut(0x07); // 8 digits
pulseCS();

// set for normal operation


ssrOut(0x0C);
ssrOut(0x01);
pulseCS();
}

void writeMAX7219(char address, char data) {


if ((address < 1) || (address > 8)) return;
ssrOut(address); // valid numbers 1-8
ssrOut(data);
pulseCS();
}

LED MATRIX-5 (satu LED matrix)

#include "LedControl.h"

LedControl lc=LedControl(12,10,11,1); // Pins: DIN,CLK,CS, # of Display connected

unsigned long delayTime=200; // Delay between Frames

// Put values in arrays


byte invader1a[] =
{
B00011000, // First frame of invader #1
B00111100,
B01111110,
B11011011,
B11111111,
B00100100,
B01011010,
B10100101
};

byte invader1b[] =
{
B00011000, // Second frame of invader #1
B00111100,
B01111110,
B11011011,
B11111111,
B00100100,
B01011010,
B01000010
};

byte invader2a[] =
{
B00100100, // First frame of invader #2
B00100100,
B01111110,
B11011011,
B11111111,
B11111111,
B10100101,
B00100100
};

byte invader2b[] =
{
B00100100, // Second frame of invader #2
B10100101,
B11111111,
B11011011,
B11111111,
B01111110,
B00100100,
B01000010
};

void setup()
{
lc.shutdown(0,false); // Wake up displays
lc.shutdown(1,false);
lc.setIntensity(0,5); // Set intensity levels
lc.setIntensity(1,5);
lc.clearDisplay(0); // Clear Displays
lc.clearDisplay(1);
}

// Take values in Arrays and Display them


void sinvader1a()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,invader1a[i]);
}
}

void sinvader1b()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,invader1b[i]);
}
}

void sinvader2a()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,invader2a[i]);
}
}
void sinvader2b()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,invader2b[i]);
}
}

void loop()
{
// Put #1 frame on both Display
sinvader1a();
delay(delayTime);
sinvader2a();
delay(delayTime);

// Put #2 frame on both Display


sinvader1b();
delay(delayTime);
sinvader2b();
delay(delayTime);

LED MATRIX-6 ( dua LED matrix)

#include "LedControl.h"

LedControl lc=LedControl(12,10,11,2); // Pins: DIN,CLK,CS, # of Display connected

unsigned long delayTime=1000; // Delay between Frames

// Put values in arrays


byte invader1a[] =
{
B00011000, // First frame of invader #1
B00111100,
B01111110,
B11011011,
B11111111,
B00100100,
B01011010,
B10100101
};
byte one[] =
{
B00000000, // First frame of invader #1
B00000000,
B10000010,
B11111111,
B10000000,
B00000000,
B00000000,
B00000000
};
byte two[] =
{
B00000000, // First frame of invader #1
B00000000,
B11000010,
B10100001,
B10010001,
B10001001,
B10000110,
B00000000
};
byte three[] =
{
B00000000, // First frame of invader #1
B01000010,
B10000001,
B10001001,
B10001001,
B01110110,
B00000000,
B00000000
};
byte four[] =
{
B00000000, // First frame of invader #1
B00110000,
B00101000,
B00100100,
B00100010,
B11110001,
B00100000,
B00000000
};
byte five[] =
{
B00000000, // First frame of invader #1
B00000000,
B01001111,
B10001001,
B10001001,
B10001001,
B01110001,
B00000000
};
byte six[] =
{
B00000000, // First frame of invader #1
B00000000,
B01111110,
B10001001,
B10001001,
B10001001,
B01110010,
B00000000
};
byte seven[] =
{
B00000000,
B11000001,
B00100001,
B00010001,
B00001001,
B00000111,
B00000000,
B00000000
};
byte eight[] =
{
B00000000, // First frame of invader #1
B00000000,
B01110110,
B10001001,
B10001001,
B10001001,
B01110110,
B00000000
};
byte nine[] =
{
B00000000, // First frame of invader #1
B00000000,
B01000110,
B10001001,
B10001001,
B10001001,
B01111110,
B00000000
};
byte zero[] =
{
B00000000, // First frame of invader #1
B00000000,
B01111110,
B10000001,
B10000001,
B10000001,
B01111110,
B00000000
};
byte invader1b[] =
{
B00011000, // Second frame of invader #1
B00111100,
B01111110,
B11011011,
B11111111,
B00100100,
B01011010,
B01000010
};

byte invader2a[] =
{
B00100100, // First frame of invader #2
B00100100,
B01111110,
B11011011,
B11111111,
B11111111,
B10100101,
B00100100
};

byte invader2b[] =
{
B00100100, // Second frame of invader #2
B10100101,
B11111111,
B11011011,
B11111111,
B01111110,
B00100100,
B01000010
};

void setup()
{
lc.shutdown(0,false); // Wake up displays
lc.shutdown(1,false);
lc.setIntensity(0,1); // Set intensity levels
lc.setIntensity(1,1);
lc.clearDisplay(0); // Clear Displays
lc.clearDisplay(1);
}

// Take values in Arrays and Display them


void sone()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,one[i]);
}
}
void stwo()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,two[i]);
}
}
void sthree()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,three[i]);
}
}
void sfour()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,four[i]);
}
}
void sfive()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,five[i]);
}
}
void ssix()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,six[i]);
}
}
void sseven()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,seven[i]);
}
}
void seight()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,eight[i]);
}
}
void snine()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,nine[i]);
}
}
void szero()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,zero[i]);
}
}

void sone1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,one[i]);
}
}
void stwo1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,two[i]);
}
}
void sthree1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,three[i]);
}
}
void sfour1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,four[i]);
}
}
void sfive1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,five[i]);
}
}
void ssix1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,six[i]);
}
}
void sseven1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,seven[i]);
}
}
void seight1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,eight[i]);
}
}
void snine1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,nine[i]);
}
}
void szero1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,zero[i]);
}
}

void sinvader1a()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,invader1a[i]);
}
}

void sinvader1b()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,invader1b[i]);
}
}
void sinvader2a()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,invader2a[i]);
}
}

void sinvader2b()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,invader2b[i]);
}
}

void loop()
{
// Put #1 frame on both Display
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sone();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo();
sone1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree();
stwo1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour();
sthree1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
sfive();
sfour1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
ssix();
sfive1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
sseven();
ssix1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
seight();
sseven1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
snine();
seight1();
delay(delayTime);
lc.clearDisplay(0);
lc.clearDisplay(1);
szero();
sone1();
delay(delayTime);

// Put #2 frame on both Display


//sinvader1b();
//delay(delayTime);
//sinvader2b();
//delay(delayTime);

==================================================================
34. JAM-SUHU-KELEMBABAN-LED MATRIX

#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
#include <MaxMatrix.h> //include matrix library
#include <avr/pgmspace.h>
#include <stdlib.h>
#include "DHT.h" //include the temp sensor library
#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT11 // DHT 11 temp&humid sensor
DHT dht(DHTPIN, DHTTYPE);
const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B00100100, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // DIN pin of MAX7219 module


int load = 10; // CS pin of MAX7219 module
int clock = 11; // CLK pin of MAX7219 module
int maxInUse = 5; //change this variable to set how many MAX7219's you'll use
MaxMatrix m(data, load, clock, maxInUse); // define module
byte buffer[10];
void setup(){
pinMode(2,INPUT); //button input
m.init(); // module initialize
m.setIntensity(1); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
Serial.println("DHTxx test!");
dht.begin();
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
}

void loop(){

float t = dht.readTemperature();
float h = dht.readHumidity();
char temp[4];
char hum[4];
itoa(t,temp,10); //convert int to char!!!!
itoa(h,hum,10); //convert int to char!!!!
DateTime now = RTC.now();

int mt = (now.month());
int dy = (now.day());
int y = (now.year());
int jm = (now.hour());
int men = (now.minute());
int dt = (now.second());
char tahun[5];
char bulan[4];
char tanggal[4];
char jam[4];
char menit[4];
char detik[4];

itoa(mt,bulan,10); //convert int to char!!!!


itoa(dy,tanggal,10); //convert int to char!!!!
itoa(y,tahun,10); //convert int to char!!!!
itoa(jm,jam,10); //convert int to char!!!!
itoa(men,menit,10); //convert int to char!!!!
itoa(dt,detik,10); //convert int to char!!!!

if(now.dayOfWeek()==1){
printStringWithShift("MONDAY", 50);
}
if(now.dayOfWeek()==2){
printStringWithShift("TUESDAY", 50);
}
if(now.dayOfWeek()==3){
printStringWithShift("WEDNESDAY", 50);
}
if(now.dayOfWeek()==4){
printStringWithShift("THURSDAY", 50);
}
if(now.dayOfWeek()==5){
printStringWithShift("FRIDAY", 50);
}
if(now.dayOfWeek()==6){
printStringWithShift("SATURDAY", 50);
}
if(now.dayOfWeek()==0){
printStringWithShift("SUNDAY", 50);
}
printStringWithShift(" ", 50);
printStringWithShift(tanggal, 50);
printStringWithShift("/", 50);
printStringWithShift(bulan, 50);
printStringWithShift("/", 50);
printStringWithShift(tahun, 50);
printStringWithShift(" ", 50);
printStringWithShift(jam, 50);
printStringWithShift(":", 50);
printStringWithShift(menit, 50);
printStringWithShift(":", 50);
printStringWithShift(detik, 50);
printStringWithShift(" ", 50);
printStringWithShift("temp: ", 50);
printStringWithShift(temp, 50);
printStringWithShift(" C ", 50);
printStringWithShift("humidity: ", 50);
printStringWithShift(hum, 50);
printStringWithShift(" % ", 50);
printStringWithShift(" ", 50);

m.shiftLeft(false, true);
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}

============================================================
35. LED MATRIX MAX7219

/*
################################################################################
# File Name: MAX7219_5.ino
# Board: Arduino UNO
# Programming Language: Wiring / C /Processing /Fritzing / Arduino IDE
#
# Objective: Scrolling LED dot Matrix
#
# Operation: Scrolls a message over a 16x8 LED dot matrix
#
# Author: Marcelo Moraes
# Date: July 9th, 2013
# Place: Sorocaba - SP - Brazil
#
################################################################################

This code is a public example.


*/

//******************************************************************************
// visit this web page for further information about MaxMatrix library
// https://code.google.com/p/arudino-maxmatrix-library/
//******************************************************************************

#include <MaxMatrix.h>
#include <avr/pgmspace.h>

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};
int data = 12; // 8, DIN pin of MAX7219 module
int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 5; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];

// active sentenses
char string1[] = " Hello, my name is Marcelo Moraes and... ";
char string2[] = " I am glad to show you my Arduino scrolling dot Matrix ";
char string3[] = " using MAX7219 IC ";
char string4[] = " Visit my blog at: http://arduinobymyself.blogspot.com.br ";
char string5[] = " There you will find a lot of projects with Arduino. ";
char string6[] = " Thanks for watching =) ";

// just for tests


char string7[] = " A B C D E F G H I J K L M N O P Q R S T U V X W Y Z ";
char string8[] = " a b c d e f g h i j k l m n o p q r s t u v x w y z ";
char string9[] = " 1 2 3 4 5 6 7 8 9 0 - = ";
char string10[] = " ! @ # $ % ¨ & * ( ) _ + ";
char string11[] = " ' , . ; ~ ] ´ [ | < > : ^ } ` { / ? ";

char string12[] = " Hello ! ";

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
byte c;
// this is the code if you want to entering a message via serial console
while (Serial.available() > 0){
byte c = Serial.read();
Serial.println(c, DEC);
printCharWithShift(c, 100);
}
delay(100);
m.shiftLeft(false, true);

// 1st block - print the active sentences


// comment this block when using the 2nd messages block

printStringWithShift(string1, 100);
printStringWithShift(string2, 100);
printStringWithShift(string3, 100);
printStringWithShift(string4, 100);
printStringWithShift(string5, 100);
printStringWithShift(string6, 100);

// 2nd block - print sentences just for tests


// uncomment this block to use it
/*
printStringWithShift(string7, 100);
printStringWithShift(string8, 100);
printStringWithShift(string9, 100);
printStringWithShift(string10, 100);
printStringWithShift(string11, 100);
*/
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
36. LED MATRIX MAX7219 tanpa shifting

Pada seksi ini kita tunjukkan bagaimana menuliskan karakter pada LED matrix tanpa shifting. Sket
dan wiring masih sama dengan sebelumnya, hanya ada perbedaan pada bagian loop.

/*
################################################################################
# File Name: MAX7219_5.ino
# Board: Arduino UNO
# Programming Language: Wiring / C /Processing /Fritzing / Arduino IDE
#
# Objective: Scrolling LED dot Matrix
#
# Operation: Scrolls a message over a 16x8 LED dot matrix
#
# Author: Marcelo Moraes
# Date: July 9th, 2013
# Place: Sorocaba - SP - Brazil
#
################################################################################

This code is a public example.


*/

//******************************************************************************
// visit this web page for further information about MaxMatrix library
// https://code.google.com/p/arudino-maxmatrix-library/
//******************************************************************************

#include <MaxMatrix.h>
#include <avr/pgmspace.h>

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 5; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];

// active sentenses
char string1[] = " Hello, my name is Marcelo Moraes and... ";
char string2[] = " I am glad to show you my Arduino scrolling dot Matrix ";
char string3[] = " using MAX7219 IC ";
char string4[] = " Visit my blog at: http://arduinobymyself.blogspot.com.br ";
char string5[] = " There you will find a lot of projects with Arduino. ";
char string6[] = " Thanks for watching =) ";

// just for tests


char string7[] = " A B C D E F G H I J K L M N O P Q R S T U V X W Y Z ";
char string8[] = " a b c d e f g h i j k l m n o p q r s t u v x w y z ";
char string9[] = " 1 2 3 4 5 6 7 8 9 0 - = ";
char string10[] = " ! @ # $ % ¨ & * ( ) _ + ";
char string11[] = " ' , . ; ~ ] ´ [ | < > : ^ } ` { / ? ";
char string12[] = " Hello ! ";
char string13[] = "A ";
char string14[] = " X";

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
byte c;

// this is the code if you want to entering a message via serial console
while (Serial.available() > 0){
byte c = Serial.read();
Serial.println(c, DEC);
printCharWithShift(c, 100);

}
//delay(100);
//m.shiftLeft(false, true);

// 1st block - print the active sentences


// comment this block when using the 2nd messages block
/*
printStringWithShift(string1, 100);
printStringWithShift(string2, 100);
printStringWithShift(string3, 100);
printStringWithShift(string4, 100);
printStringWithShift(string5, 100);
printStringWithShift(string6, 100);
*/
// 2nd block - print sentences just for tests
// uncomment this block to use it
/*
printStringWithShift(string7, 100);
printStringWithShift(string8, 100);
printStringWithShift(string9, 100);
printStringWithShift(string10, 100);
printStringWithShift(string11, 100);
printStringWithShift(string12, 100);
*/
printString(string13);
printString(string14);

}
void printCharWithShift(char c, int shift_speed){
if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
37. LED MATRIX MAX7219 dengan shifting

/*
################################################################################
# File Name: MAX7219_5.ino
# Board: Arduino UNO
# Programming Language: Wiring / C /Processing /Fritzing / Arduino IDE
#
# Objective: Scrolling LED dot Matrix
#
# Operation: Scrolls a message over a 16x8 LED dot matrix
#
# Author: Marcelo Moraes
# Date: July 9th, 2013
# Place: Sorocaba - SP - Brazil
#
################################################################################

This code is a public example.


*/

//******************************************************************************
// visit this web page for further information about MaxMatrix library
// https://code.google.com/p/arudino-maxmatrix-library/
//******************************************************************************

#include <MaxMatrix.h>
#include <avr/pgmspace.h>

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 5; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];

// active sentenses
char string1[] = " Hello, my name is Marcelo Moraes and... ";
char string2[] = " I am glad to show you my Arduino scrolling dot Matrix ";
char string3[] = " using MAX7219 IC ";
char string4[] = " Visit my blog at: http://arduinobymyself.blogspot.com.br ";
char string5[] = " There you will find a lot of projects with Arduino. ";
char string6[] = " Thanks for watching =) ";

// just for tests


char string7[] = " A B C D E F G H I J K L M N O P Q R S T U V X W Y Z ";
char string8[] = " a b c d e f g h i j k l m n o p q r s t u v x w y z ";
char string9[] = " 1 2 3 4 5 6 7 8 9 0 - = ";
char string10[] = " ! @ # $ % ¨ & * ( ) _ + ";
char string11[] = " ' , . ; ~ ] ´ [ | < > : ^ } ` { / ? ";
char string12[] = " Hello ! ";
char string13[] = "A ";
char string14[] = " X";

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
byte c;

// this is the code if you want to entering a message via serial console
while (Serial.available() > 0){
byte c = Serial.read();
Serial.println(c, DEC);
printCharWithShift(c, 100);

}
//delay(100);
//m.shiftLeft(false, true);

// 1st block - print the active sentences


// comment this block when using the 2nd messages block
/*
printStringWithShift(string1, 100);
printStringWithShift(string2, 100);
printStringWithShift(string3, 100);
printStringWithShift(string4, 100);
printStringWithShift(string5, 100);
printStringWithShift(string6, 100);
*/
// 2nd block - print sentences just for tests
// uncomment this block to use it

printStringWithShift(string7, 100);
printStringWithShift(string8, 100);
printStringWithShift(string9, 100);
printStringWithShift(string10, 100);
printStringWithShift(string11, 100);
printStringWithShift(string12, 100);
/*
printString(string13);
printString(string14);
*/
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}

LED MATRIX MAX7219 tanpa shifting

Coba Anda lihat bedanya

/*
################################################################################
# File Name: MAX7219_5.ino
# Board: Arduino UNO
# Programming Language: Wiring / C /Processing /Fritzing / Arduino IDE
#
# Objective: Scrolling LED dot Matrix
#
# Operation: Scrolls a message over a 16x8 LED dot matrix
#
# Author: Marcelo Moraes
# Date: July 9th, 2013
# Place: Sorocaba - SP - Brazil
#
################################################################################
This code is a public example.
*/

//******************************************************************************
// visit this web page for further information about MaxMatrix library
// https://code.google.com/p/arudino-maxmatrix-library/
//******************************************************************************

#include <MaxMatrix.h>
#include <avr/pgmspace.h>

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 5; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];

// active sentenses
char string1[] = " Hello, my name is Marcelo Moraes and... ";
char string2[] = " I am glad to show you my Arduino scrolling dot Matrix ";
char string3[] = " using MAX7219 IC ";
char string4[] = " Visit my blog at: http://arduinobymyself.blogspot.com.br ";
char string5[] = " There you will find a lot of projects with Arduino. ";
char string6[] = " Thanks for watching =) ";

// just for tests


char string7[] = " A B C D E F G H I J K L M N O P Q R S T U V X W Y Z ";
char string8[] = " a b c d e f g h i j k l m n o p q r s t u v x w y z ";
char string9[] = " 1 2 3 4 5 6 7 8 9 0 - = ";
char string10[] = " ! @ # $ % ¨ & * ( ) _ + ";
char string11[] = " ' , . ; ~ ] ´ [ | < > : ^ } ` { / ? ";
char string12[] = " Hello ! ";
char string13[] = "A 0";
char string14[] = "A 1";
char string15[] = "A 2";
char string16[] = "A 3";
char string17[] = "A 4";
char string18[] = "A 5";
char string19[] = "B 6";

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
byte c;
// this is the code if you want to entering a message via serial console
while (Serial.available() > 0){
byte c = Serial.read();
Serial.println(c, DEC);
printCharWithShift(c, 100);

}
//delay(100);
//m.shiftLeft(false, true);

// 1st block - print the active sentences


// comment this block when using the 2nd messages block
/*
printStringWithShift(string1, 100);
printStringWithShift(string2, 100);
printStringWithShift(string3, 100);
printStringWithShift(string4, 100);
printStringWithShift(string5, 100);
printStringWithShift(string6, 100);
*/
// 2nd block - print sentences just for tests
// uncomment this block to use it
/*
printStringWithShift(string7, 100);
printStringWithShift(string8, 100);
printStringWithShift(string9, 100);
printStringWithShift(string10, 100);
printStringWithShift(string11, 100);
printStringWithShift(string12, 100);
*/
printString(string13);
delay(1000);
printString(string14);
delay(1000);
printString(string15);
delay(1000);
printString(string16);
delay(1000);
printString(string17);
delay(1000);
printString(string18);
delay(1000);
printString(string19);
delay(1000);

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
38. LED MATRIX MAX7219 (menghitung detik)

/*
################################################################################
# File Name: MAX7219_5.ino
# Board: Arduino UNO
# Programming Language: Wiring / C /Processing /Fritzing / Arduino IDE
#
# Objective: Scrolling LED dot Matrix
#
# Operation: Scrolls a message over a 16x8 LED dot matrix
#
# Author: Marcelo Moraes
# Date: July 9th, 2013
# Place: Sorocaba - SP - Brazil
#
################################################################################

This code is a public example.


*/

//******************************************************************************
// visit this web page for further information about MaxMatrix library
// https://code.google.com/p/arudino-maxmatrix-library/
//******************************************************************************

#include <MaxMatrix.h>
#include <avr/pgmspace.h>

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 5; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];

// active sentenses
char string1[] = " Hello, my name is Marcelo Moraes and... ";
char string2[] = " I am glad to show you my Arduino scrolling dot Matrix ";
char string3[] = " using MAX7219 IC ";
char string4[] = " Visit my blog at: http://arduinobymyself.blogspot.com.br ";
char string5[] = " There you will find a lot of projects with Arduino. ";
char string6[] = " Thanks for watching =) ";

// just for tests


char string7[] = " A B C D E F G H I J K L M N O P Q R S T U V X W Y Z ";
char string8[] = " a b c d e f g h i j k l m n o p q r s t u v x w y z ";
char string9[] = " 1 2 3 4 5 6 7 8 9 0 - = ";
char string10[] = " ! @ # $ % ¨ & * ( ) _ + ";
char string11[] = " ' , . ; ~ ] ´ [ | < > : ^ } ` { / ? ";
char string12[] = " Hello ! ";
char string13[] = "0 0";
char string14[] = "0 1";
char string15[] = "0 2";
char string16[] = "0 3";
char string17[] = "0 4";
char string18[] = "0 5";
char string19[] = "0 6";
char string20[] = "0 7";
char string21[] = "0 8";
char string22[] = "0 9";
char string23[] = "1 0";
char string24[] = "1 1";
char string25[] = "1 2";
char string26[] = "1 3";
char string27[] = "1 4";
char string28[] = "1 5";
char string29[] = "1 6";
char string30[] = "1 7";
char string31[] = "1 8";
char string32[] = "1 9";
char string33[] = "2 0";
char string34[] = "2 1";
char string35[] = "2 2";
char string36[] = "2 3";
char string37[] = "2 4";
char string38[] = "2 5";
char string39[] = "2 6";
char string40[] = "2 7";
char string41[] = "2 8";
char string42[] = "2 9";
char string43[] = "3 0";
char string44[] = "3 1";
char string45[] = "3 2";
char string46[] = "3 3";
char string47[] = "3 4";
char string48[] = "3 5";
char string49[] = "3 6";
char string50[] = "3 7";
char string51[] = "3 8";
char string52[] = "3 9";
char string53[] = "4 0";
char string54[] = "4 1";
char string55[] = "4 2";
char string56[] = "4 3";
char string57[] = "4 4";
char string58[] = "4 5";
char string59[] = "4 6";
char string60[] = "4 7";
char string61[] = "4 8";
char string62[] = "4 9";
char string63[] = "5 0";
char string64[] = "5 1";
char string65[] = "5 2";
char string66[] = "5 3";
char string67[] = "5 4";
char string68[] = "5 5";
char string69[] = "5 6";
char string70[] = "5 7";
char string71[] = "5 8";
char string72[] = "5 9";

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
byte c;

// this is the code if you want to entering a message via serial console
while (Serial.available() > 0){
byte c = Serial.read();
Serial.println(c, DEC);
printCharWithShift(c, 100);

}
//delay(100);
//m.shiftLeft(false, true);

// 1st block - print the active sentences


// comment this block when using the 2nd messages block
/*
printStringWithShift(string1, 100);
printStringWithShift(string2, 100);
printStringWithShift(string3, 100);
printStringWithShift(string4, 100);
printStringWithShift(string5, 100);
printStringWithShift(string6, 100);
*/
// 2nd block - print sentences just for tests
// uncomment this block to use it
/*
printStringWithShift(string7, 100);
printStringWithShift(string8, 100);
printStringWithShift(string9, 100);
printStringWithShift(string10, 100);
printStringWithShift(string11, 100);
printStringWithShift(string12, 100);
*/
printString(string13);
delay(1000);
printString(string14);
delay(1000);
printString(string15);
delay(1000);
printString(string16);
delay(1000);
printString(string17);
delay(1000);
printString(string18);
delay(1000);
printString(string19);
delay(1000);
printString(string20);
delay(1000);
printString(string21);
delay(1000);
printString(string22);
delay(1000);
printString(string23);
delay(1000);
printString(string24);
delay(1000);
printString(string25);
delay(1000);
printString(string26);
delay(1000);
printString(string27);
delay(1000);
printString(string28);
delay(1000);
printString(string29);
delay(1000);
printString(string30);
delay(1000);
printString(string31);
delay(1000);
printString(string32);
delay(1000);
printString(string33);
delay(1000);
printString(string34);
delay(1000);
printString(string35);
delay(1000);
printString(string36);
delay(1000);
printString(string37);
delay(1000);
printString(string38);
delay(1000);
printString(string39);
delay(1000);
printString(string40);
delay(1000);
printString(string41);
delay(1000);
printString(string42);
delay(1000);
printString(string43);
delay(1000);
printString(string44);
delay(1000);
printString(string45);
delay(1000);
printString(string46);
delay(1000);
printString(string47);
delay(1000);
printString(string48);
delay(1000);
printString(string49);
delay(1000);
printString(string50);
delay(1000);
printString(string51);
delay(1000);
printString(string52);
delay(1000);
printString(string53);
delay(1000);
printString(string54);
delay(1000);
printString(string55);
delay(1000);
printString(string56);
delay(1000);
printString(string57);
delay(1000);
printString(string58);
delay(1000);
printString(string59);
delay(1000);
printString(string60);
delay(1000);
printString(string61);
delay(1000);
printString(string62);
delay(1000);
printString(string63);
delay(1000);
printString(string64);
delay(1000);
printString(string65);
delay(1000);
printString(string66);
delay(1000);
printString(string67);
delay(1000);
printString(string68);
delay(1000);
printString(string69);
delay(1000);
printString(string70);
delay(1000);
printString(string71);
delay(1000);
printString(string72);
delay(1000);
}
void printCharWithShift(char c, int shift_speed){
if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);
for (int i=0; i<buffer[0]+1; i++)
{
delay(shift_speed);
m.shiftLeft(false, false);
}
}
void printStringWithShift(char* s, int shift_speed){
while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}
void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
39. PIN PWM

PWM artinya Pulse Width Modulation, yaitu pin yang output-nya dapat diatur tegangannya. Pada
arduino uno atau nano ada pin yang dapat digunakan menjadi PWM pin yaitu pin 3, 5, 6, 9, 10, 11.

int ledPin = 11; // LED connected to digital pin 11

void setup()
{
pinMode(ledPin, OUTPUT); // sets the pin as output
}

void loop()
{

analogWrite(ledPin, 0); // output range 0 hingga 255


delay(500);
analogWrite(ledPin, 20);
delay(500);
analogWrite(ledPin, 40);
delay(500);
analogWrite(ledPin, 60);
delay(500);
analogWrite(ledPin, 80);
delay(500);
analogWrite(ledPin, 100);
delay(500);
analogWrite(ledPin, 120);
delay(500);
analogWrite(ledPin, 140);
delay(500);
analogWrite(ledPin, 180);
delay(500);
analogWrite(ledPin, 200);
delay(500);
analogWrite(ledPin, 233); // analogRead values go from 0 to 1023, analogWrite values from 0 to
255
delay(500);
}
=============================================================
40. SOFT PWM

Pin arduino selain yang bertanda PWM dapat juga difungsikan menjadi PWM dengan bantuan
softPWM library.

#include <SoftPWM.h>

void setup()
{
SoftPWMBegin();

SoftPWMSet(7, 0);

SoftPWMSetFadeTime(7, 1000, 1000);


}

void loop()
{
SoftPWMSet(7, 255);
delay(1000);
SoftPWMSet(7, 0);
delay(1000);
}

============================================================
41. KONTROL SERVO MOTOR DENGAN POTENSIOMETER

#include <Servo.h>
Servo head;
int sensorPin = A2;
int sensorValue = 0;
int sudut = 0;
void setup()
{
head.attach(9);
head.write(80);
pinMode(sensorPin,INPUT);
Serial.begin(9600);

}
void loop(){
float sensorValue = analogRead(sensorPin);
int sudut = (sensorValue/1023)*180;
Serial.println(sudut);
//delay(100);
head.write(sudut);
}
================================================================
42. DC FAN SPEED CONTROL

Pada proyek ini kita sajikan cara pengontrolan laju motor DC. Bagian penting dari rangkaian ini
adalah transistor mosfet, di mana pin GATE kita kendalikan dengan signal dari pin PWM arduino.
Transistor ini mampu bekerja hingga tegangan 60V DC.

#define fadePin 3 // harus PWM pin


int pot = A2;
int t2 = 0;

void setup(){
Serial.begin(9600);
pinMode(fadePin, OUTPUT);
pinMode(pot, INPUT);
}
void loop(){
//calculate sin of angle as number between 0 and 255
float t2= analogRead(pot);
int sinOut = t2*255/1023;
Serial.println(sinOut);
analogWrite(fadePin, sinOut);
}
=====================================================================
43. MENGUKUR KUAT ARUS

Pada sesi ini didemonstrasikan pengukuran kuat arus dari sumber arus bolak-balik. Pengukuran arus
dengan modul ACS712. Arus yang dapat diukur pada kisaran hingga 30A.

#include <Filters.h>

float testFrequency = 60; // test signal frequency (Hz)


float windowLength = 20.0/testFrequency; // how long to average the signal, for statistist
int sensorValue = 0;
float intercept = -0.1129; // to be adjusted based on calibration testing
float slope = 0.0405; // to be adjusted based on calibration testing
float current_amps; // estimated actual current in amps

unsigned long printPeriod = 100; // in milliseconds


// Track time in milliseconds since last reading
unsigned long previousMillis = 0;

void setup() {
Serial.begin( 9600 ); // start the serial port
}

void loop() {
RunningStatistics inputStats; // create statistics to look at the raw test signal
inputStats.setWindowSecs( windowLength );

while( true ) {
sensorValue = analogRead(A0); // read the analog in value:
inputStats.input(sensorValue); // log to Stats function
if((unsigned long)(millis() - previousMillis) >= printPeriod) {
previousMillis = millis(); // update time

// display current values to the screen

// output sigma or variation values associated with the inputValue itsel


Serial.print("\n" );
Serial.print( "\tsigma: " );
Serial.print( inputStats.sigma() );
// convert signal sigma value to current in amps
current_amps = intercept + slope * inputStats.sigma();
Serial.print( "\tamps: " );
Serial.println( current_amps );

}
}
}
================================================================
44. PUSH BUTTON

/*
Button

Turns on and off a light emitting diode(LED) connected to digital


pin 8, when pressing a pushbutton attached to pin 7.

The circuit:
* LED attached from pin 8 to ground
* pushbutton attached to pin 7 from +5V
* 10M resistor attached to pin 7 from ground

created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Button
*/

// constants won't change. They're used here to


// set pin numbers:
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 8; // the number of the LED pin

// variables will change:


int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}

void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.


// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

===============================================================
45. COUNTER

/*
State change detection (edge detection)

Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.

This example shows how to detect when a button or button changes from off to on
and on to off.

The circuit:
* pushbutton attached to pin 7 from +5V
* 10M resistor attached to pin 7 from ground
* LED attached from pin 8 to ground (or use the built-in LED on
most Arduino boards)

created 27 Sep 2005


modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/ButtonStateChange

*/

// this constant won't change:


const int buttonPin = 7; // the pin that the pushbutton is attached to
const int ledPin = 8; // the pin that the LED is attached to

// Variables will change:


int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}

void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state


if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;

// turns on the LED every four button pushes by


// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}

}
46. COUNTER DENGAN LED MATRIX DISPLAY

//Sket di bawah ini dapat manampilkan hingga 50.


// this constant won't change:
const int buttonPin = 7; // the pin that the pushbutton is attached to
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
int jumlah=0;
#include "LedControl.h"

LedControl lc=LedControl(12,11,10,2); // Pins: DIN,CLK,CS, # of Display connected

unsigned long delayTime=1000; // Delay between Frames

// Put values in arrays

byte one[] =
{
B00000000, // First frame of invader #1
B00000000,
B10000010,
B11111111,
B10000000,
B00000000,
B00000000,
B00000000
};
byte two[] =
{
B00000000, // First frame of invader #1
B00000000,
B11000010,
B10100001,
B10010001,
B10001001,
B10000110,
B00000000
};
byte three[] =
{
B00000000, // First frame of invader #1
B01000010,
B10000001,
B10001001,
B10001001,
B01110110,
B00000000,
B00000000
};
byte four[] =
{
B00000000, // First frame of invader #1
B00110000,
B00101000,
B00100100,
B00100010,
B11110001,
B00100000,
B00000000
};
byte five[] =
{
B00000000, // First frame of invader #1
B00000000,
B01001111,
B10001001,
B10001001,
B10001001,
B01110001,
B00000000
};
byte six[] =
{
B00000000, // First frame of invader #1
B00000000,
B01111110,
B10001001,
B10001001,
B10001001,
B01110010,
B00000000
};
byte seven[] =
{
B00000000, // First frame of invader #1
B00000000,
B10000001,
B01000001,
B00100001,
B00010001,
B00001111,
B00000000
};
byte eight[] =
{
B00000000, // First frame of invader #1
B00000000,
B01110110,
B10001001,
B10001001,
B10001001,
B01110110,
B00000000
};
byte nine[] =
{
B00000000, // First frame of invader #1
B00000000,
B01000110,
B10001001,
B10001001,
B10001001,
B01111110,
B00000000
};
byte zero[] =
{
B00000000, // First frame of invader #1
B00000000,
B01111110,
B10000001,
B10000001,
B10000001,
B01111110,
B00000000
};

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize serial communication:
Serial.begin(9600);
lc.shutdown(0,false); // Wake up displays
lc.shutdown(1,false);
lc.setIntensity(0,0); // Set intensity levels
lc.setIntensity(1,0);
lc.clearDisplay(0); // Clear Displays
lc.clearDisplay(1);
}

void sone()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,one[i]);
}
}
void stwo()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,two[i]);
}
}
void sthree()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,three[i]);
}
}
void sfour()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,four[i]);
}
}
void sfive()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,five[i]);
}
}
void ssix()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,six[i]);
}
}
void sseven()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,seven[i]);
}
}
void seight()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,eight[i]);
}
}
void snine()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,nine[i]);
}
}
void szero()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,zero[i]);
}
}

void sone1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,one[i]);
}
}
void stwo1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,two[i]);
}
}
void sthree1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,three[i]);
}
}
void sfour1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,four[i]);
}
}
void sfive1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,five[i]);
}
}
void ssix1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,six[i]);
}
}
void sseven1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,seven[i]);
}
}
void seight1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,eight[i]);
}
}
void snine1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,nine[i]);
}
}
void szero1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,zero[i]);
}
}

void sepuluh()
{
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sone();
}

void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);

// Delay a little bit to avoid bouncing


delay(100);
}
int jumlah = buttonPushCounter;
if (jumlah==1){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sone();
}
if (jumlah==2){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
stwo();
}
if (jumlah==3){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sthree();
}
if (jumlah==4){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sfour();
}
if (jumlah==5){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sfive();
}
if (jumlah==6){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
ssix();
}
if (jumlah==7){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sseven();
}
if (jumlah==8){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
seight();
}
if (jumlah==9){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
snine();
}
if (jumlah==10){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
szero();
}
if (jumlah==11){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sone();
}
if (jumlah==12){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
stwo();
}
if (jumlah==13){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sthree();
}
if (jumlah==14){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sfour();
}
if (jumlah==15){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sfive();
}
if (jumlah==16){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
ssix();
}
if (jumlah==17){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sseven();
}
if (jumlah==18){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
seight();
}
if (jumlah==19){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
snine();
}
if (jumlah==20){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
szero();
}
if (jumlah==21){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sone();
}
if (jumlah==22){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
stwo();
}
if (jumlah==23){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sthree();
}
if (jumlah==24){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sfour();
}
if (jumlah==25){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sfive();
}
if (jumlah==26){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
ssix();
}
if (jumlah==27){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sseven();
}
if (jumlah==28){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
seight();
}
if (jumlah==29){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
snine();
}
if (jumlah==30){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
szero();
}
if (jumlah==31){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sone();
}
if (jumlah==32){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
stwo();
}
if (jumlah==33){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sthree();
}
if (jumlah==34){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sfour();
}
if (jumlah==35){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sfive();
}
if (jumlah==36){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
ssix();
}
if (jumlah==37){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sseven();
}
if (jumlah==38){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
seight();
}
if (jumlah==39){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
snine();
}
if (jumlah==40){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
szero();
}
if (jumlah==41){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sone();
}
if (jumlah==42){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
stwo();
}
if (jumlah==43){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sthree();
}
if (jumlah==44){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sfour();
}
if (jumlah==45){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sfive();
}
if (jumlah==46){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
ssix();
}
if (jumlah==47){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sseven();
}
if (jumlah==48){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
seight();
}
if (jumlah==49){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
snine();
}
if (jumlah==50){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfive1();
szero();
}

if (jumlah==0){
lc.clearDisplay(0);
lc.clearDisplay(1);
//szero1();
//sone();
}

lastButtonState = buttonState;

==================================================================
47. PENGHITUNG RAKAAT SHOLAT

Program inin adalah gabungan dari beberapa program elementer, antara lain : program untuk
menjalankan LED matrix, program untuk menjalankan ultrasonic sensor, program untuk
menjalankan counter serta untuk push button. Pada proyek ini kita menggunakan sensor ultrasonic
untuk mendeteksi jarak antara sensor dan kepala ketika sujud. Sensor ultrasonik kita pasang pada
board arduino signal (sensor unit), hal ini dilakukan untuk mengisolasi sensor ultrasonic, karena
sensor ultrasonic ini akan terganggu jika dipasangkan pada satu board dengan counter, yaitu
pengukuran jarak menjadi tidak stabil ketika sensor ultrasonic ini tergabung dalam satu mikro
kontroler. Prinsip garis besarnya adalah sensor ultrasonic akan mengukur jarak antara kepala dan
sensor, ketikajarak sensor dan kepala lebih kecil dari 30 cm maka pin D7 akan menjadi HIGH,
signal HIGH dari pin D7 ini akan di-injeksikan ke pin D2 pada board arduino counter, yang pada
dasarnya pin D2 arduino counter ini adalah eks push button, signal yang dihasilkan oleh push button
kita gantikan dengan signal dari D7 dari board sensor. Ketika jarak sensor antara 30 hingga 80 cm
pin D7 tidak berubah status, sedangkan ketika jarak sudah lebih dari 80 cm makan pin D7 akan
berubah menjadi LOW. Hitungan dari board counter akan ditampilkan pada display 2x LED matrix
8x8.
Sket Counter :

const int buttonPin = 2; // the pin that the pushbutton is attached to

// Variables will change:


int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
int jumlah=0;
#include "LedControl.h"

LedControl lc=LedControl(12,11,10,2); // Pins: DIN,CLK,CS, # of Display connected

unsigned long delayTime=1000; // Delay between Frames

// Put values in arrays

byte one[] =
{
B00000000, // First frame of invader #1
B00000000,
B10000010,
B11111111,
B10000000,
B00000000,
B00000000,
B00000000
};
byte two[] =
{
B00000000, // First frame of invader #1
B00000000,
B11000010,
B10100001,
B10010001,
B10001001,
B10000110,
B00000000
};
byte three[] =
{
B00000000, // First frame of invader #1
B01000010,
B10000001,
B10001001,
B10001001,
B01110110,
B00000000,
B00000000
};
byte four[] =
{
B00000000, // First frame of invader #1
B00110000,
B00101000,
B00100100,
B00100010,
B11110001,
B00100000,
B00000000
};
byte five[] =
{
B00000000, // First frame of invader #1
B00000000,
B01001111,
B10001001,
B10001001,
B10001001,
B01110001,
B00000000
};
byte six[] =
{
B00000000, // First frame of invader #1
B00000000,
B01111110,
B10001001,
B10001001,
B10001001,
B01110010,
B00000000
};
byte seven[] =
{
B00000000, // First frame of invader #1
B00000000,
B10000001,
B01000001,
B00100001,
B00010001,
B00001111,
B00000000
};
byte eight[] =
{
B00000000, // First frame of invader #1
B00000000,
B01110110,
B10001001,
B10001001,
B10001001,
B01110110,
B00000000
};
byte nine[] =
{
B00000000, // First frame of invader #1
B00000000,
B01000110,
B10001001,
B10001001,
B10001001,
B01111110,
B00000000
};
byte zero[] =
{
B00000000, // First frame of invader #1
B00000000,
B01111110,
B10000001,
B10000001,
B10000001,
B01111110,
B00000000
};

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
// initialize serial communication:
Serial.begin(9600);
lc.shutdown(0,false); // Wake up displays
lc.shutdown(1,false);
lc.setIntensity(0,0); // Set intensity levels
lc.setIntensity(1,0);
lc.clearDisplay(0); // Clear Displays
lc.clearDisplay(1);
}

void sone()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,one[i]);
}
}
void stwo()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,two[i]);
}
}
void sthree()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,three[i]);
}
}
void sfour()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,four[i]);
}
}
void sfive()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,five[i]);
}
}
void ssix()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,six[i]);
}
}
void sseven()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,seven[i]);
}
}
void seight()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,eight[i]);
}
}
void snine()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,nine[i]);
}
}
void szero()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(0,i,zero[i]);
}
}

void sone1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,one[i]);
}
}
void stwo1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,two[i]);
}
}
void sthree1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,three[i]);
}
}
void sfour1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,four[i]);
}
}
void sfive1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,five[i]);
}
}
void ssix1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,six[i]);
}
}
void sseven1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,seven[i]);
}
}
void seight1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,eight[i]);
}
}
void snine1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,nine[i]);
}
}
void szero1()
{
for (int i = 0; i < 8; i++)
{
lc.setRow(1,i,zero[i]);
}
}

void sepuluh()
{
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sone();
}

void loop() {

buttonState = digitalRead(buttonPin);

if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);

// Delay a little bit to avoid bouncing


delay(2000);
}
int jumlah = buttonPushCounter/2;
if (jumlah==1){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sone();
}
if (jumlah==2){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
stwo();
}
if (jumlah==3){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sthree();
}
if (jumlah==4){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sfour();
}
if (jumlah==5){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sfive();
}
if (jumlah==6){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
ssix();
}
if (jumlah==7){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
sseven();
}
if (jumlah==8){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
seight();
}
if (jumlah==9){
lc.clearDisplay(0);
lc.clearDisplay(1);
szero1();
snine();
}
if (jumlah==10){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
szero();
}
if (jumlah==11){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sone();
}
if (jumlah==12){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
stwo();
}
if (jumlah==13){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sthree();
}
if (jumlah==14){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sfour();
}
if (jumlah==15){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sfive();
}
if (jumlah==16){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
ssix();
}
if (jumlah==17){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
sseven();
}
if (jumlah==18){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
seight();
}
if (jumlah==19){
lc.clearDisplay(0);
lc.clearDisplay(1);
sone1();
snine();
}
if (jumlah==20){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
szero();
}
if (jumlah==21){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sone();
}
if (jumlah==22){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
stwo();
}
if (jumlah==23){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sthree();
}
if (jumlah==24){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sfour();
}
if (jumlah==25){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sfive();
}
if (jumlah==26){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
ssix();
}
if (jumlah==27){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
sseven();
}
if (jumlah==28){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
seight();
}
if (jumlah==29){
lc.clearDisplay(0);
lc.clearDisplay(1);
stwo1();
snine();
}
if (jumlah==30){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
szero();
}
if (jumlah==31){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sone();
}
if (jumlah==32){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
stwo();
}
if (jumlah==33){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sthree();
}
if (jumlah==34){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sfour();
}
if (jumlah==35){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sfive();
}
if (jumlah==36){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
ssix();
}
if (jumlah==37){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
sseven();
}
if (jumlah==38){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
seight();
}
if (jumlah==39){
lc.clearDisplay(0);
lc.clearDisplay(1);
sthree1();
snine();
}
if (jumlah==40){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
szero();
}
if (jumlah==41){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sone();
}
if (jumlah==42){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
stwo();
}
if (jumlah==43){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sthree();
}
if (jumlah==44){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sfour();
}
if (jumlah==45){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sfive();
}
if (jumlah==46){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
ssix();
}
if (jumlah==47){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
sseven();
}
if (jumlah==48){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
seight();
}
if (jumlah==49){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfour1();
snine();
}
if (jumlah==50){
lc.clearDisplay(0);
lc.clearDisplay(1);
sfive1();
szero();
}

if (jumlah==0){
lc.clearDisplay(0);
lc.clearDisplay(1);

lastButtonState = buttonState;

Sket sensor unit :

int led = 7;

#define trigPin1 11
#define echoPin1 10

long duration, distance, UltraSensor;


void setup() {

pinMode(led, OUTPUT);

Serial.begin(9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
}
void loop() {
SonarSensor(trigPin1, echoPin1);
UltraSensor = distance;
Serial.println(UltraSensor);

if (UltraSensor <= 30){


digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
} // wait for a second
if (UltraSensor > 80){
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
} // wait for a second

}
void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
delay(100);
}

===================================================================
48. DC MOTOR SHIELD

#include <AFMotor.h>

AF_DCMotor Motor1(1);
AF_DCMotor Motor2(2);
AF_DCMotor Motor3(3);
AF_DCMotor Motor4(4);

void setup()
{
}

void loop()
{
//setting forward speed
Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//foward
Motor1.run(FORWARD);
Motor2.run(FORWARD);
Motor3.run(FORWARD);
Motor4.run(FORWARD);
delay(1000);
Motor1.run(BRAKE);
Motor2.run(BRAKE);
Motor3.run(BRAKE);
Motor4.run(BRAKE);
delay(1000);
//stop
Motor1.setSpeed(0);
Motor2.setSpeed(0);
Motor3.setSpeed(0);
Motor4.setSpeed(0);
delay(1000);
//setting backward speed
Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//backward
Motor1.run(BACKWARD);
Motor2.run(BACKWARD);
Motor3.run(BACKWARD);
Motor4.run(BACKWARD);
delay(1000);
Motor1.run(BRAKE);
Motor2.run(BRAKE);
Motor3.run(BRAKE);
Motor4.run(BRAKE);
delay(1000);

}
49. MOTOR SHIELD TEST-1

#include <AFMotor.h>

AF_DCMotor motor1(1, MOTOR12_64KHZ); // create motor #2, 64KHz pwm


AF_DCMotor motor2(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor3(3, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor4(4, MOTOR12_64KHZ); // create motor #2, 64KHz pwm

void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Motor test!");

motor1.setSpeed(80); // set the speed to 200/255


motor2.setSpeed(80); // set the speed to 200/255
motor3.setSpeed(80); // set the speed to 200/255
motor4.setSpeed(80);
}

void loop() {
Serial.print("tick");

motor1.run(FORWARD); // turn it on going forward


delay(1000);

Serial.print("tack");
motor1.run(RELEASE); // stopped
delay(1000);

Serial.print("tock");
motor1.run(BACKWARD); // the other way
delay(1000);

Serial.print("tack");
motor1.run(RELEASE); // stopped
delay(1000);

}
50. MOTOR SHIELD TEST-2

#include <AFMotor.h>

AF_DCMotor motor1(1, MOTOR12_64KHZ); // create motor #2, 64KHz pwm


AF_DCMotor motor2(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor3(3, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor4(4, MOTOR12_64KHZ); // create motor #2, 64KHz pwm

void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Motor test!");

motor1.setSpeed(80); // set the speed to 200/255


motor2.setSpeed(80); // set the speed to 200/255
motor3.setSpeed(80); // set the speed to 200/255
motor4.setSpeed(80);
}

void loop() {
Serial.print("M1");

motor1.run(FORWARD); // turn it on going forward


delay(1000);

Serial.print("tack");
motor1.run(RELEASE); // stopped
delay(1000);

Serial.print("tock");
motor1.run(BACKWARD); // the other way
delay(1000);

Serial.println("tack");
motor1.run(RELEASE); // stopped
delay(1000);

//-------------

Serial.print("M2");

motor2.run(FORWARD); // turn it on going forward


delay(1000);

Serial.print("tack");
motor2.run(RELEASE); // stopped
delay(1000);

Serial.print("tock");
motor2.run(BACKWARD); // the other way
delay(1000);
Serial.println("tack");
motor2.run(RELEASE); // stopped
delay(1000);

//----------------

Serial.print("M3");

motor3.run(FORWARD); // turn it on going forward


delay(1000);

Serial.print("tack");
motor3.run(RELEASE); // stopped
delay(1000);

Serial.print("tock");
motor3.run(BACKWARD); // the other way
delay(1000);

Serial.println("tack");
motor3.run(RELEASE); // stopped
delay(1000);

//--------------

Serial.print("M4");

motor4.run(FORWARD); // turn it on going forward


delay(1000);

Serial.print("tack");
motor4.run(RELEASE); // stopped
delay(1000);

Serial.print("tock");
motor4.run(BACKWARD); // the other way
delay(1000);

Serial.println("tack");
motor4.run(RELEASE); // stopped
delay(1000);

}
51. RUN MOTOR SHIELD BY KEYBOARD

#include <AFMotor.h>

AF_DCMotor Motor1(1);
AF_DCMotor Motor2(2);
AF_DCMotor Motor3(3);
AF_DCMotor Motor4(4);

void setup()
{
Serial.begin(9600);
}

void loop()
{
if (Serial.available() > 0) {
int inByte = Serial.read();
int speed; // Local variable

switch (inByte) {

case '1': // Motor 1 Forward

Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//foward
Motor1.run(FORWARD);
Motor2.run(FORWARD);
Motor3.run(FORWARD);
Motor4.run(FORWARD);
break;

case '2': // Motor 1 Stop (Freespin)

Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//backward
Motor1.run(BACKWARD);
Motor2.run(BACKWARD);
Motor3.run(BACKWARD);
Motor4.run(BACKWARD);
break;
case '3': // Motor 1 Reverse
Motor1.setSpeed(0);
Motor2.setSpeed(0);
Motor3.setSpeed(0);
Motor4.setSpeed(0);
break;
default:
break;

}
}
}
52. MOTOR SHIELD DENGAN VOID

#include <AFMotor.h>

AF_DCMotor Motor1(1);
AF_DCMotor Motor2(2);
AF_DCMotor Motor3(3);
AF_DCMotor Motor4(4);

void setup()
{
Serial.begin(9600);
}

void loop()
{
if (Serial.available() > 0) {
int inByte = Serial.read();
int speed; // Local variable

switch (inByte) {

case '8': // Forward


maju();
break;

case '2': // Backward


mundur();
break;

case '6': // Right


kanan();
break;

case '4': // Left


kiri();
break;

case '5': // Motor 1 Stop (Freespin)


stops();
break;

default:
break;

}
}
}

void maju(){
Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//foward
Motor1.run(FORWARD);
Motor2.run(FORWARD);
Motor3.run(FORWARD);
Motor4.run(FORWARD);
}
void mundur(){
Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//backward
Motor1.run(BACKWARD);
Motor2.run(BACKWARD);
Motor3.run(BACKWARD);
Motor4.run(BACKWARD);
}
void kanan(){
Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//foward
Motor1.run(FORWARD);
Motor2.run(FORWARD);
Motor3.run(BACKWARD);
Motor4.run(BACKWARD);
}
void kiri(){
Motor1.setSpeed(70);
Motor2.setSpeed(70);
Motor3.setSpeed(80);
Motor4.setSpeed(80);
//foward
Motor1.run(BACKWARD);
Motor2.run(BACKWARD);
Motor3.run(FORWARD);
Motor4.run(FORWARD);
}
void stops(){
Motor1.setSpeed(0);
Motor2.setSpeed(0);
Motor3.setSpeed(0);
Motor4.setSpeed(0);
}

==============================================================
53. MENGENDALIKAN MOTOR SERVO DENGAN IR REMOTE

#include <IRremote.h> //must copy IRremote library to arduino libraries


#include <Servo.h>
#define plus 0xEF10609F //clockwise rotation button
#define minus 0xEF10E01F //counter clockwise rotation button

int RECV_PIN = 14; //IR receiver pin, pin A0


Servo servo;
int val; //rotation angle
bool cwRotation, ccwRotation; //the states of rotation

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
servo.attach(15); //servo pin, pin A1
}

void loop()
{
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value

if (results.value == plus)
{

servo.write(180);
delay(1);//controlling speed

if (results.value == minus)
{

servo.write(0);
delay(1);

}
}

-------------------------------------------------------------------------------------------------
54. PENGUKURAN SUHU DENGAN SENSOR PT-100

/*
In this project we use LM324 chip for amplify signal from RTD PT100, amplified signal than go to
ADS1015 for increase digital resolution.
*/
#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads(0x48);
int temp0;

void setup() {
Serial.begin(9600);
ads.begin();
}
void loop() {
int16_t adc0; // we read from the ADC, we have a sixteen bit integer as a result
adc0 = ads.readADC_SingleEnded(0);
temp0 = adc0;
float fhrt = (temp0*0.0466)-671.48;//from calabration plot
Serial.print(temp0);
Serial.print(" ");
Serial.println(fhrt);
delay(500);
}

=====================================================================
55. MENGATUR KECERAHAN LED DENGAN PUSH BUTTON

int pinIncrease = 2;
int pinDecrease = 3;
int pinLED = 11;
int brightness = 0;

void setup() {
Serial.begin(9600);
pinMode(pinIncrease, INPUT);
pinMode(pinDecrease, INPUT);
pinMode(pinLED, OUTPUT);
digitalWrite(pinIncrease, HIGH);
digitalWrite(pinDecrease, HIGH);
}

void loop() {
brightness = constrain(brightness, 0, 255);
analogWrite(pinLED, brightness);
Serial.println(brightness);
delay(100);

if(digitalRead(pinIncrease) == LOW){
brightness++;
}else if(digitalRead(pinDecrease) == LOW){
brightness--;
}
}

===================================================================
56. MENGATUR LAJU FAN DENGAN PUSH BUTTON

int pinIncrease = 2;
int pinDecrease = 3;
int pinLED = 11;
int SpeedFan = 0;

void setup() {
Serial.begin(9600);
pinMode(pinIncrease, INPUT);
pinMode(pinDecrease, INPUT);
pinMode(pinLED, OUTPUT);
digitalWrite(pinIncrease, HIGH);
digitalWrite(pinDecrease, HIGH);
}

void loop() {
SpeedFan = constrain(SpeedFan, 0, 255);
analogWrite(pinLED, SpeedFan);
Serial.println(SpeedFan);
delay(20);

if(digitalRead(pinIncrease) == LOW){
SpeedFan++;
}else if(digitalRead(pinDecrease) == LOW){
SpeedFan--;
}
}

===========================================================
57. SETTING LAJU FAN DENGAN EEPROM

Pada proyek ini kita akan tampilkan pengaturan laju dimana nilai laju kita tuliskan dalam EEPROM
ketika push button nomer 1 kita tekan.

#include <EEPROM.h>
int pinIncrease = 2;
int pinDecrease = 3;
int pinLED = 11;
int pinSetting = 10;
int SpeedFan = 0;
byte laju;

void setup() {
Serial.begin(9600);
pinMode(pinIncrease, INPUT);
pinMode(pinDecrease, INPUT);
pinMode(pinSetting, INPUT);
pinMode(pinLED, OUTPUT);
digitalWrite(pinIncrease, HIGH);
digitalWrite(pinDecrease, HIGH);
}

void loop() {
if(digitalRead(pinSetting) == HIGH){
SpeedFan = constrain(SpeedFan, 0, 255);
analogWrite(pinLED, laju);

EEPROM.write(1, SpeedFan);
laju = EEPROM.read(1);
Serial.print(laju);
Serial.print(" ");
Serial.println(SpeedFan);
delay(20);
setting();
}else if(digitalRead(pinSetting) == LOW){
laju = EEPROM.read(1);
analogWrite(pinLED, laju);
Serial.print(laju);
Serial.print(" ");
Serial.println(SpeedFan);
delay(20);
}
}

void setting(){
if(digitalRead(pinIncrease) == LOW){
SpeedFan++;
}else if(digitalRead(pinDecrease) == LOW){
SpeedFan--;
}
}

==================================================================
58. SETUP LCD MENGGUNAKAN IC 74HC595

LCD juga dapat disambungkan memakai IC shift register 74HC595. Keuntungan dari penggunaan
shift register ini adalah dapat mengurangi jumlah penggunaan pin pada arduino, yaitu hanya
menggunakan tiga pin saja.
#include <Wire.h>
#include <LiquidCrystal_SR.h>
//LiquidCrystal_SR lcd Mendefinisikan(DataPin,ClockPin, EnablePin);
LiquidCrystal_SR lcd(2, 3, 4); //D2 to pin14,D3 to pin11,D4 to pin12

void setup() {
lcd.begin(16, 4);
}

void loop() {
int i;

lcd.setCursor(0, 0);
lcd.print("Ayo belajar!");
for (i = 0 ; i < 16; i ++) {
lcd.scrollDisplayLeft();
delay(300);
}
}

===============================================================
59. ACCELEROMETER MPU 6050

// MPU-6050 Accelerometer + Gyro


// -----------------------------
//
// By arduino.cc user "Krodal".
// June 2012
// Open Source / Public Domain
//
// Using Arduino 1.0.1
// It will not work with an older version,
// since Wire.endTransmission() uses a parameter
// to hold or release the I2C bus.
//
// Documentation:
// - The InvenSense documents:
// - "MPU-6000 and MPU-6050 Product Specification",
// PS-MPU-6000A.pdf
// - "MPU-6000 and MPU-6050 Register Map and Descriptions",
// RM-MPU-6000A.pdf or RS-MPU-6000A.pdf
// - "MPU-6000/MPU-6050 9-Axis Evaluation Board User Guide"
// AN-MPU-6000EVB.pdf
//
// The accuracy is 16-bits.
//
// Temperature sensor from -40 to +85 degrees Celsius
// 340 per degrees, -512 at 35 degrees.
//
// At power-up, all registers are zero, except these two:
// Register 0x6B (PWR_MGMT_2) = 0x40 (I read zero).
// Register 0x75 (WHO_AM_I) = 0x68.
//

#include <Wire.h>

// The name of the sensor is "MPU-6050".


// For program code, I omit the '-',
// therefor I use the name "MPU6050....".

// Register names according to the datasheet.


// According to the InvenSense document
// "MPU-6000 and MPU-6050 Register Map
// and Descriptions Revision 3.2", there are no registers
// at 0x02 ... 0x18, but according other information
// the registers in that unknown area are for gain
// and offsets.
//
#define MPU6050_AUX_VDDIO 0x01 // R/W
#define MPU6050_SMPLRT_DIV 0x19 // R/W
#define MPU6050_CONFIG 0x1A // R/W
#define MPU6050_GYRO_CONFIG 0x1B // R/W
#define MPU6050_ACCEL_CONFIG 0x1C // R/W
#define MPU6050_FF_THR 0x1D // R/W
#define MPU6050_FF_DUR 0x1E // R/W
#define MPU6050_MOT_THR 0x1F // R/W
#define MPU6050_MOT_DUR 0x20 // R/W
#define MPU6050_ZRMOT_THR 0x21 // R/W
#define MPU6050_ZRMOT_DUR 0x22 // R/W
#define MPU6050_FIFO_EN 0x23 // R/W
#define MPU6050_I2C_MST_CTRL 0x24 // R/W
#define MPU6050_I2C_SLV0_ADDR 0x25 // R/W
#define MPU6050_I2C_SLV0_REG 0x26 // R/W
#define MPU6050_I2C_SLV0_CTRL 0x27 // R/W
#define MPU6050_I2C_SLV1_ADDR 0x28 // R/W
#define MPU6050_I2C_SLV1_REG 0x29 // R/W
#define MPU6050_I2C_SLV1_CTRL 0x2A // R/W
#define MPU6050_I2C_SLV2_ADDR 0x2B // R/W
#define MPU6050_I2C_SLV2_REG 0x2C // R/W
#define MPU6050_I2C_SLV2_CTRL 0x2D // R/W
#define MPU6050_I2C_SLV3_ADDR 0x2E // R/W
#define MPU6050_I2C_SLV3_REG 0x2F // R/W
#define MPU6050_I2C_SLV3_CTRL 0x30 // R/W
#define MPU6050_I2C_SLV4_ADDR 0x31 // R/W
#define MPU6050_I2C_SLV4_REG 0x32 // R/W
#define MPU6050_I2C_SLV4_DO 0x33 // R/W
#define MPU6050_I2C_SLV4_CTRL 0x34 // R/W
#define MPU6050_I2C_SLV4_DI 0x35 // R
#define MPU6050_I2C_MST_STATUS 0x36 // R
#define MPU6050_INT_PIN_CFG 0x37 // R/W
#define MPU6050_INT_ENABLE 0x38 // R/W
#define MPU6050_INT_STATUS 0x3A // R
#define MPU6050_ACCEL_XOUT_H 0x3B // R
#define MPU6050_ACCEL_XOUT_L 0x3C // R
#define MPU6050_ACCEL_YOUT_H 0x3D // R
#define MPU6050_ACCEL_YOUT_L 0x3E // R
#define MPU6050_ACCEL_ZOUT_H 0x3F // R
#define MPU6050_ACCEL_ZOUT_L 0x40 // R
#define MPU6050_TEMP_OUT_H 0x41 // R
#define MPU6050_TEMP_OUT_L 0x42 // R
#define MPU6050_GYRO_XOUT_H 0x43 // R
#define MPU6050_GYRO_XOUT_L 0x44 // R
#define MPU6050_GYRO_YOUT_H 0x45 // R
#define MPU6050_GYRO_YOUT_L 0x46 // R
#define MPU6050_GYRO_ZOUT_H 0x47 // R
#define MPU6050_GYRO_ZOUT_L 0x48 // R
#define MPU6050_EXT_SENS_DATA_00 0x49 // R
#define MPU6050_EXT_SENS_DATA_01 0x4A // R
#define MPU6050_EXT_SENS_DATA_02 0x4B // R
#define MPU6050_EXT_SENS_DATA_03 0x4C // R
#define MPU6050_EXT_SENS_DATA_04 0x4D // R
#define MPU6050_EXT_SENS_DATA_05 0x4E // R
#define MPU6050_EXT_SENS_DATA_06 0x4F // R
#define MPU6050_EXT_SENS_DATA_07 0x50 // R
#define MPU6050_EXT_SENS_DATA_08 0x51 // R
#define MPU6050_EXT_SENS_DATA_09 0x52 // R
#define MPU6050_EXT_SENS_DATA_10 0x53 // R
#define MPU6050_EXT_SENS_DATA_11 0x54 // R
#define MPU6050_EXT_SENS_DATA_12 0x55 // R
#define MPU6050_EXT_SENS_DATA_13 0x56 // R
#define MPU6050_EXT_SENS_DATA_14 0x57 // R
#define MPU6050_EXT_SENS_DATA_15 0x58 // R
#define MPU6050_EXT_SENS_DATA_16 0x59 // R
#define MPU6050_EXT_SENS_DATA_17 0x5A // R
#define MPU6050_EXT_SENS_DATA_18 0x5B // R
#define MPU6050_EXT_SENS_DATA_19 0x5C // R
#define MPU6050_EXT_SENS_DATA_20 0x5D // R
#define MPU6050_EXT_SENS_DATA_21 0x5E // R
#define MPU6050_EXT_SENS_DATA_22 0x5F // R
#define MPU6050_EXT_SENS_DATA_23 0x60 // R
#define MPU6050_MOT_DETECT_STATUS 0x61 // R
#define MPU6050_I2C_SLV0_DO 0x63 // R/W
#define MPU6050_I2C_SLV1_DO 0x64 // R/W
#define MPU6050_I2C_SLV2_DO 0x65 // R/W
#define MPU6050_I2C_SLV3_DO 0x66 // R/W
#define MPU6050_I2C_MST_DELAY_CTRL 0x67 // R/W
#define MPU6050_SIGNAL_PATH_RESET 0x68 // R/W
#define MPU6050_MOT_DETECT_CTRL 0x69 // R/W
#define MPU6050_USER_CTRL 0x6A // R/W
#define MPU6050_PWR_MGMT_1 0x6B // R/W
#define MPU6050_PWR_MGMT_2 0x6C // R/W
#define MPU6050_FIFO_COUNTH 0x72 // R/W
#define MPU6050_FIFO_COUNTL 0x73 // R/W
#define MPU6050_FIFO_R_W 0x74 // R/W
#define MPU6050_WHO_AM_I 0x75 // R

// Defines for the bits, to be able to change


// between bit number and binary definition.
// By using the bit number, programming the sensor
// is like programming the AVR microcontroller.
// But instead of using "(1<<X)", or "_BV(X)",
// the Arduino "bit(X)" is used.
#define MPU6050_D0 0
#define MPU6050_D1 1
#define MPU6050_D2 2
#define MPU6050_D3 3
#define MPU6050_D4 4
#define MPU6050_D5 5
#define MPU6050_D6 6
#define MPU6050_D7 7

// AUX_VDDIO Register
#define MPU6050_AUX_VDDIO MPU6050_D7 // I2C high: 1=VDD, 0=VLOGIC

// CONFIG Register
// DLPF is Digital Low Pass Filter for both gyro and accelerometers.
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_DLPF_CFG0 MPU6050_D0
#define MPU6050_DLPF_CFG1 MPU6050_D1
#define MPU6050_DLPF_CFG2 MPU6050_D2
#define MPU6050_EXT_SYNC_SET0 MPU6050_D3
#define MPU6050_EXT_SYNC_SET1 MPU6050_D4
#define MPU6050_EXT_SYNC_SET2 MPU6050_D5

// Combined definitions for the EXT_SYNC_SET values


#define MPU6050_EXT_SYNC_SET_0 (0)
#define MPU6050_EXT_SYNC_SET_1 (bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_2 (bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_3 (bit(MPU6050_EXT_SYNC_SET1)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_4 (bit(MPU6050_EXT_SYNC_SET2))
#define MPU6050_EXT_SYNC_SET_5 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_6 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_7 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1)|bit(MPU6050_EXT_SYNC_SET0))
// Alternative names for the combined definitions.
#define MPU6050_EXT_SYNC_DISABLED MPU6050_EXT_SYNC_SET_0
#define MPU6050_EXT_SYNC_TEMP_OUT_L MPU6050_EXT_SYNC_SET_1
#define MPU6050_EXT_SYNC_GYRO_XOUT_L MPU6050_EXT_SYNC_SET_2
#define MPU6050_EXT_SYNC_GYRO_YOUT_L MPU6050_EXT_SYNC_SET_3
#define MPU6050_EXT_SYNC_GYRO_ZOUT_L MPU6050_EXT_SYNC_SET_4
#define MPU6050_EXT_SYNC_ACCEL_XOUT_L MPU6050_EXT_SYNC_SET_5
#define MPU6050_EXT_SYNC_ACCEL_YOUT_L MPU6050_EXT_SYNC_SET_6
#define MPU6050_EXT_SYNC_ACCEL_ZOUT_L MPU6050_EXT_SYNC_SET_7

// Combined definitions for the DLPF_CFG values


#define MPU6050_DLPF_CFG_0 (0)
#define MPU6050_DLPF_CFG_1 (bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_2 (bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_3 (bit(MPU6050_DLPF_CFG1)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_4 (bit(MPU6050_DLPF_CFG2))
#define MPU6050_DLPF_CFG_5 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_6 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_7 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1)|
bit(MPU6050_DLPF_CFG0))

// Alternative names for the combined definitions


// This name uses the bandwidth (Hz) for the accelometer,
// for the gyro the bandwidth is almost the same.
#define MPU6050_DLPF_260HZ MPU6050_DLPF_CFG_0
#define MPU6050_DLPF_184HZ MPU6050_DLPF_CFG_1
#define MPU6050_DLPF_94HZ MPU6050_DLPF_CFG_2
#define MPU6050_DLPF_44HZ MPU6050_DLPF_CFG_3
#define MPU6050_DLPF_21HZ MPU6050_DLPF_CFG_4
#define MPU6050_DLPF_10HZ MPU6050_DLPF_CFG_5
#define MPU6050_DLPF_5HZ MPU6050_DLPF_CFG_6
#define MPU6050_DLPF_RESERVED MPU6050_DLPF_CFG_7

// GYRO_CONFIG Register
// The XG_ST, YG_ST, ZG_ST are bits for selftest.
// The FS_SEL sets the range for the gyro.
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_FS_SEL0 MPU6050_D3
#define MPU6050_FS_SEL1 MPU6050_D4
#define MPU6050_ZG_ST MPU6050_D5
#define MPU6050_YG_ST MPU6050_D6
#define MPU6050_XG_ST MPU6050_D7

// Combined definitions for the FS_SEL values


#define MPU6050_FS_SEL_0 (0)
#define MPU6050_FS_SEL_1 (bit(MPU6050_FS_SEL0))
#define MPU6050_FS_SEL_2 (bit(MPU6050_FS_SEL1))
#define MPU6050_FS_SEL_3 (bit(MPU6050_FS_SEL1)|bit(MPU6050_FS_SEL0))

// Alternative names for the combined definitions


// The name uses the range in degrees per second.
#define MPU6050_FS_SEL_250 MPU6050_FS_SEL_0
#define MPU6050_FS_SEL_500 MPU6050_FS_SEL_1
#define MPU6050_FS_SEL_1000 MPU6050_FS_SEL_2
#define MPU6050_FS_SEL_2000 MPU6050_FS_SEL_3

// ACCEL_CONFIG Register
// The XA_ST, YA_ST, ZA_ST are bits for selftest.
// The AFS_SEL sets the range for the accelerometer.
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_ACCEL_HPF0 MPU6050_D0
#define MPU6050_ACCEL_HPF1 MPU6050_D1
#define MPU6050_ACCEL_HPF2 MPU6050_D2
#define MPU6050_AFS_SEL0 MPU6050_D3
#define MPU6050_AFS_SEL1 MPU6050_D4
#define MPU6050_ZA_ST MPU6050_D5
#define MPU6050_YA_ST MPU6050_D6
#define MPU6050_XA_ST MPU6050_D7

// Combined definitions for the ACCEL_HPF values


#define MPU6050_ACCEL_HPF_0 (0)
#define MPU6050_ACCEL_HPF_1 (bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_2 (bit(MPU6050_ACCEL_HPF1))
#define MPU6050_ACCEL_HPF_3 (bit(MPU6050_ACCEL_HPF1)|
bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_4 (bit(MPU6050_ACCEL_HPF2))
#define MPU6050_ACCEL_HPF_7 (bit(MPU6050_ACCEL_HPF2)|
bit(MPU6050_ACCEL_HPF1)|bit(MPU6050_ACCEL_HPF0))

// Alternative names for the combined definitions


// The name uses the Cut-off frequency.
#define MPU6050_ACCEL_HPF_RESET MPU6050_ACCEL_HPF_0
#define MPU6050_ACCEL_HPF_5HZ MPU6050_ACCEL_HPF_1
#define MPU6050_ACCEL_HPF_2_5HZ MPU6050_ACCEL_HPF_2
#define MPU6050_ACCEL_HPF_1_25HZ MPU6050_ACCEL_HPF_3
#define MPU6050_ACCEL_HPF_0_63HZ MPU6050_ACCEL_HPF_4
#define MPU6050_ACCEL_HPF_HOLD MPU6050_ACCEL_HPF_7

// Combined definitions for the AFS_SEL values


#define MPU6050_AFS_SEL_0 (0)
#define MPU6050_AFS_SEL_1 (bit(MPU6050_AFS_SEL0))
#define MPU6050_AFS_SEL_2 (bit(MPU6050_AFS_SEL1))
#define MPU6050_AFS_SEL_3 (bit(MPU6050_AFS_SEL1)|bit(MPU6050_AFS_SEL0))

// Alternative names for the combined definitions


// The name uses the full scale range for the accelerometer.
#define MPU6050_AFS_SEL_2G MPU6050_AFS_SEL_0
#define MPU6050_AFS_SEL_4G MPU6050_AFS_SEL_1
#define MPU6050_AFS_SEL_8G MPU6050_AFS_SEL_2
#define MPU6050_AFS_SEL_16G MPU6050_AFS_SEL_3

// FIFO_EN Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_SLV0_FIFO_EN MPU6050_D0
#define MPU6050_SLV1_FIFO_EN MPU6050_D1
#define MPU6050_SLV2_FIFO_EN MPU6050_D2
#define MPU6050_ACCEL_FIFO_EN MPU6050_D3
#define MPU6050_ZG_FIFO_EN MPU6050_D4
#define MPU6050_YG_FIFO_EN MPU6050_D5
#define MPU6050_XG_FIFO_EN MPU6050_D6
#define MPU6050_TEMP_FIFO_EN MPU6050_D7

// I2C_MST_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_MST_CLK0 MPU6050_D0
#define MPU6050_I2C_MST_CLK1 MPU6050_D1
#define MPU6050_I2C_MST_CLK2 MPU6050_D2
#define MPU6050_I2C_MST_CLK3 MPU6050_D3
#define MPU6050_I2C_MST_P_NSR MPU6050_D4
#define MPU6050_SLV_3_FIFO_EN MPU6050_D5
#define MPU6050_WAIT_FOR_ES MPU6050_D6
#define MPU6050_MULT_MST_EN MPU6050_D7

// Combined definitions for the I2C_MST_CLK


#define MPU6050_I2C_MST_CLK_0 (0)
#define MPU6050_I2C_MST_CLK_1 (bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_2 (bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_3 (bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_4 (bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_5 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_6 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_7 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_8 (bit(MPU6050_I2C_MST_CLK3))
#define MPU6050_I2C_MST_CLK_9 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_10 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_11 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_12 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_13 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_14 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_15 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))
// Alternative names for the combined definitions
// The names uses I2C Master Clock Speed in kHz.
#define MPU6050_I2C_MST_CLK_348KHZ MPU6050_I2C_MST_CLK_0
#define MPU6050_I2C_MST_CLK_333KHZ MPU6050_I2C_MST_CLK_1
#define MPU6050_I2C_MST_CLK_320KHZ MPU6050_I2C_MST_CLK_2
#define MPU6050_I2C_MST_CLK_308KHZ MPU6050_I2C_MST_CLK_3
#define MPU6050_I2C_MST_CLK_296KHZ MPU6050_I2C_MST_CLK_4
#define MPU6050_I2C_MST_CLK_286KHZ MPU6050_I2C_MST_CLK_5
#define MPU6050_I2C_MST_CLK_276KHZ MPU6050_I2C_MST_CLK_6
#define MPU6050_I2C_MST_CLK_267KHZ MPU6050_I2C_MST_CLK_7
#define MPU6050_I2C_MST_CLK_258KHZ MPU6050_I2C_MST_CLK_8
#define MPU6050_I2C_MST_CLK_500KHZ MPU6050_I2C_MST_CLK_9
#define MPU6050_I2C_MST_CLK_471KHZ MPU6050_I2C_MST_CLK_10
#define MPU6050_I2C_MST_CLK_444KHZ MPU6050_I2C_MST_CLK_11
#define MPU6050_I2C_MST_CLK_421KHZ MPU6050_I2C_MST_CLK_12
#define MPU6050_I2C_MST_CLK_400KHZ MPU6050_I2C_MST_CLK_13
#define MPU6050_I2C_MST_CLK_381KHZ MPU6050_I2C_MST_CLK_14
#define MPU6050_I2C_MST_CLK_364KHZ MPU6050_I2C_MST_CLK_15

// I2C_SLV0_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_RW MPU6050_D7

// I2C_SLV0_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV0_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV0_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV0_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV0_GRP MPU6050_D4
#define MPU6050_I2C_SLV0_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV0_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV0_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV0_LEN_MASK 0x0F

// I2C_SLV1_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV1_RW MPU6050_D7

// I2C_SLV1_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV1_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV1_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV1_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV1_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV1_GRP MPU6050_D4
#define MPU6050_I2C_SLV1_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV1_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV1_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV1_LEN_MASK 0x0F

// I2C_SLV2_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV2_RW MPU6050_D7

// I2C_SLV2_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV2_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV2_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV2_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV2_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV2_GRP MPU6050_D4
#define MPU6050_I2C_SLV2_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV2_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV2_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV2_LEN_MASK 0x0F

// I2C_SLV3_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV3_RW MPU6050_D7

// I2C_SLV3_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV3_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV3_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV3_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV3_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV3_GRP MPU6050_D4
#define MPU6050_I2C_SLV3_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV3_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV3_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV3_LEN_MASK 0x0F

// I2C_SLV4_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV4_RW MPU6050_D7
// I2C_SLV4_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_MST_DLY0 MPU6050_D0
#define MPU6050_I2C_MST_DLY1 MPU6050_D1
#define MPU6050_I2C_MST_DLY2 MPU6050_D2
#define MPU6050_I2C_MST_DLY3 MPU6050_D3
#define MPU6050_I2C_MST_DLY4 MPU6050_D4
#define MPU6050_I2C_SLV4_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV4_INT_EN MPU6050_D6
#define MPU6050_I2C_SLV4_EN MPU6050_D7

// A mask for the delay


#define MPU6050_I2C_MST_DLY_MASK 0x1F

// I2C_MST_STATUS Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_NACK MPU6050_D0
#define MPU6050_I2C_SLV1_NACK MPU6050_D1
#define MPU6050_I2C_SLV2_NACK MPU6050_D2
#define MPU6050_I2C_SLV3_NACK MPU6050_D3
#define MPU6050_I2C_SLV4_NACK MPU6050_D4
#define MPU6050_I2C_LOST_ARB MPU6050_D5
#define MPU6050_I2C_SLV4_DONE MPU6050_D6
#define MPU6050_PASS_THROUGH MPU6050_D7

// I2C_PIN_CFG Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_CLKOUT_EN MPU6050_D0
#define MPU6050_I2C_BYPASS_EN MPU6050_D1
#define MPU6050_FSYNC_INT_EN MPU6050_D2
#define MPU6050_FSYNC_INT_LEVEL MPU6050_D3
#define MPU6050_INT_RD_CLEAR MPU6050_D4
#define MPU6050_LATCH_INT_EN MPU6050_D5
#define MPU6050_INT_OPEN MPU6050_D6
#define MPU6050_INT_LEVEL MPU6050_D7

// INT_ENABLE Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_DATA_RDY_EN MPU6050_D0
#define MPU6050_I2C_MST_INT_EN MPU6050_D3
#define MPU6050_FIFO_OFLOW_EN MPU6050_D4
#define MPU6050_ZMOT_EN MPU6050_D5
#define MPU6050_MOT_EN MPU6050_D6
#define MPU6050_FF_EN MPU6050_D7

// INT_STATUS Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_DATA_RDY_INT MPU6050_D0
#define MPU6050_I2C_MST_INT MPU6050_D3
#define MPU6050_FIFO_OFLOW_INT MPU6050_D4
#define MPU6050_ZMOT_INT MPU6050_D5
#define MPU6050_MOT_INT MPU6050_D6
#define MPU6050_FF_INT MPU6050_D7

// MOT_DETECT_STATUS Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_MOT_ZRMOT MPU6050_D0
#define MPU6050_MOT_ZPOS MPU6050_D2
#define MPU6050_MOT_ZNEG MPU6050_D3
#define MPU6050_MOT_YPOS MPU6050_D4
#define MPU6050_MOT_YNEG MPU6050_D5
#define MPU6050_MOT_XPOS MPU6050_D6
#define MPU6050_MOT_XNEG MPU6050_D7

// IC2_MST_DELAY_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_DLY_EN MPU6050_D0
#define MPU6050_I2C_SLV1_DLY_EN MPU6050_D1
#define MPU6050_I2C_SLV2_DLY_EN MPU6050_D2
#define MPU6050_I2C_SLV3_DLY_EN MPU6050_D3
#define MPU6050_I2C_SLV4_DLY_EN MPU6050_D4
#define MPU6050_DELAY_ES_SHADOW MPU6050_D7

// SIGNAL_PATH_RESET Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_TEMP_RESET MPU6050_D0
#define MPU6050_ACCEL_RESET MPU6050_D1
#define MPU6050_GYRO_RESET MPU6050_D2

// MOT_DETECT_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_MOT_COUNT0 MPU6050_D0
#define MPU6050_MOT_COUNT1 MPU6050_D1
#define MPU6050_FF_COUNT0 MPU6050_D2
#define MPU6050_FF_COUNT1 MPU6050_D3
#define MPU6050_ACCEL_ON_DELAY0 MPU6050_D4
#define MPU6050_ACCEL_ON_DELAY1 MPU6050_D5

// Combined definitions for the MOT_COUNT


#define MPU6050_MOT_COUNT_0 (0)
#define MPU6050_MOT_COUNT_1 (bit(MPU6050_MOT_COUNT0))
#define MPU6050_MOT_COUNT_2 (bit(MPU6050_MOT_COUNT1))
#define MPU6050_MOT_COUNT_3 (bit(MPU6050_MOT_COUNT1)|
bit(MPU6050_MOT_COUNT0))
// Alternative names for the combined definitions
#define MPU6050_MOT_COUNT_RESET MPU6050_MOT_COUNT_0

// Combined definitions for the FF_COUNT


#define MPU6050_FF_COUNT_0 (0)
#define MPU6050_FF_COUNT_1 (bit(MPU6050_FF_COUNT0))
#define MPU6050_FF_COUNT_2 (bit(MPU6050_FF_COUNT1))
#define MPU6050_FF_COUNT_3 (bit(MPU6050_FF_COUNT1)|bit(MPU6050_FF_COUNT0))

// Alternative names for the combined definitions


#define MPU6050_FF_COUNT_RESET MPU6050_FF_COUNT_0

// Combined definitions for the ACCEL_ON_DELAY


#define MPU6050_ACCEL_ON_DELAY_0 (0)
#define MPU6050_ACCEL_ON_DELAY_1 (bit(MPU6050_ACCEL_ON_DELAY0))
#define MPU6050_ACCEL_ON_DELAY_2 (bit(MPU6050_ACCEL_ON_DELAY1))
#define MPU6050_ACCEL_ON_DELAY_3 (bit(MPU6050_ACCEL_ON_DELAY1)|
bit(MPU6050_ACCEL_ON_DELAY0))

// Alternative names for the ACCEL_ON_DELAY


#define MPU6050_ACCEL_ON_DELAY_0MS MPU6050_ACCEL_ON_DELAY_0
#define MPU6050_ACCEL_ON_DELAY_1MS MPU6050_ACCEL_ON_DELAY_1
#define MPU6050_ACCEL_ON_DELAY_2MS MPU6050_ACCEL_ON_DELAY_2
#define MPU6050_ACCEL_ON_DELAY_3MS MPU6050_ACCEL_ON_DELAY_3

// USER_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_SIG_COND_RESET MPU6050_D0
#define MPU6050_I2C_MST_RESET MPU6050_D1
#define MPU6050_FIFO_RESET MPU6050_D2
#define MPU6050_I2C_IF_DIS MPU6050_D4 // must be 0 for MPU-6050
#define MPU6050_I2C_MST_EN MPU6050_D5
#define MPU6050_FIFO_EN MPU6050_D6

// PWR_MGMT_1 Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_CLKSEL0 MPU6050_D0
#define MPU6050_CLKSEL1 MPU6050_D1
#define MPU6050_CLKSEL2 MPU6050_D2
#define MPU6050_TEMP_DIS MPU6050_D3 // 1: disable temperature sensor
#define MPU6050_CYCLE MPU6050_D5 // 1: sample and sleep
#define MPU6050_SLEEP MPU6050_D6 // 1: sleep mode
#define MPU6050_DEVICE_RESET MPU6050_D7 // 1: reset to default values

// Combined definitions for the CLKSEL


#define MPU6050_CLKSEL_0 (0)
#define MPU6050_CLKSEL_1 (bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_2 (bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_3 (bit(MPU6050_CLKSEL1)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_4 (bit(MPU6050_CLKSEL2))
#define MPU6050_CLKSEL_5 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_6 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_7 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1)|
bit(MPU6050_CLKSEL0))

// Alternative names for the combined definitions


#define MPU6050_CLKSEL_INTERNAL MPU6050_CLKSEL_0
#define MPU6050_CLKSEL_X MPU6050_CLKSEL_1
#define MPU6050_CLKSEL_Y MPU6050_CLKSEL_2
#define MPU6050_CLKSEL_Z MPU6050_CLKSEL_3
#define MPU6050_CLKSEL_EXT_32KHZ MPU6050_CLKSEL_4
#define MPU6050_CLKSEL_EXT_19_2MHZ MPU6050_CLKSEL_5
#define MPU6050_CLKSEL_RESERVED MPU6050_CLKSEL_6
#define MPU6050_CLKSEL_STOP MPU6050_CLKSEL_7

// PWR_MGMT_2 Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_STBY_ZG MPU6050_D0
#define MPU6050_STBY_YG MPU6050_D1
#define MPU6050_STBY_XG MPU6050_D2
#define MPU6050_STBY_ZA MPU6050_D3
#define MPU6050_STBY_YA MPU6050_D4
#define MPU6050_STBY_XA MPU6050_D5
#define MPU6050_LP_WAKE_CTRL0 MPU6050_D6
#define MPU6050_LP_WAKE_CTRL1 MPU6050_D7

// Combined definitions for the LP_WAKE_CTRL


#define MPU6050_LP_WAKE_CTRL_0 (0)
#define MPU6050_LP_WAKE_CTRL_1 (bit(MPU6050_LP_WAKE_CTRL0))
#define MPU6050_LP_WAKE_CTRL_2 (bit(MPU6050_LP_WAKE_CTRL1))
#define MPU6050_LP_WAKE_CTRL_3 (bit(MPU6050_LP_WAKE_CTRL1)|
bit(MPU6050_LP_WAKE_CTRL0))

// Alternative names for the combined definitions


// The names uses the Wake-up Frequency.
#define MPU6050_LP_WAKE_1_25HZ MPU6050_LP_WAKE_CTRL_0
#define MPU6050_LP_WAKE_2_5HZ MPU6050_LP_WAKE_CTRL_1
#define MPU6050_LP_WAKE_5HZ MPU6050_LP_WAKE_CTRL_2
#define MPU6050_LP_WAKE_10HZ MPU6050_LP_WAKE_CTRL_3

// Default I2C address for the MPU-6050 is 0x68.


// But only if the AD0 pin is low.
// Some sensor boards have AD0 high, and the
// I2C address thus becomes 0x69.
#define MPU6050_I2C_ADDRESS 0x68

// Declaring an union for the registers and the axis values.


// The byte order does not match the byte order of
// the compiler and AVR chip.
// The AVR chip (on the Arduino board) has the Low Byte
// at the lower address.
// But the MPU-6050 has a different order: High Byte at
// lower address, so that has to be corrected.
// The register part "reg" is only used internally,
// and are swapped in code.
typedef union accel_t_gyro_union
{
struct
{
uint8_t x_accel_h;
uint8_t x_accel_l;
uint8_t y_accel_h;
uint8_t y_accel_l;
uint8_t z_accel_h;
uint8_t z_accel_l;
uint8_t t_h;
uint8_t t_l;
uint8_t x_gyro_h;
uint8_t x_gyro_l;
uint8_t y_gyro_h;
uint8_t y_gyro_l;
uint8_t z_gyro_h;
uint8_t z_gyro_l;
} reg;
struct
{
int x_accel;
int y_accel;
int z_accel;
int temperature;
int x_gyro;
int y_gyro;
int z_gyro;
} value;
};

// Use the following global variables and access functions to help store the overall
// rotation angle of the sensor
unsigned long last_read_time;
float last_x_angle; // These are the filtered angles
float last_y_angle;
float last_z_angle;
float last_gyro_x_angle; // Store the gyro angles to compare drift
float last_gyro_y_angle;
float last_gyro_z_angle;

void set_last_read_angle_data(unsigned long time, float x, float y, float z, float x_gyro, float
y_gyro, float z_gyro) {
last_read_time = time;
last_x_angle = x;
last_y_angle = y;
last_z_angle = z;
last_gyro_x_angle = x_gyro;
last_gyro_y_angle = y_gyro;
last_gyro_z_angle = z_gyro;
}

inline unsigned long get_last_time() {return last_read_time;}


inline float get_last_x_angle() {return last_x_angle;}
inline float get_last_y_angle() {return last_y_angle;}
inline float get_last_z_angle() {return last_z_angle;}
inline float get_last_gyro_x_angle() {return last_gyro_x_angle;}
inline float get_last_gyro_y_angle() {return last_gyro_y_angle;}
inline float get_last_gyro_z_angle() {return last_gyro_z_angle;}

// Use the following global variables and access functions


// to calibrate the acceleration sensor
float base_x_accel;
float base_y_accel;
float base_z_accel;

float base_x_gyro;
float base_y_gyro;
float base_z_gyro;

int read_gyro_accel_vals(uint8_t* accel_t_gyro_ptr) {


// Read the raw values.
// Read 14 bytes at once,
// containing acceleration, temperature and gyro.
// With the default settings of the MPU-6050,
// there is no filter enabled, and the values
// are not very stable. Returns the error value

accel_t_gyro_union* accel_t_gyro = (accel_t_gyro_union *) accel_t_gyro_ptr;

int error = MPU6050_read (MPU6050_ACCEL_XOUT_H, (uint8_t *) accel_t_gyro,


sizeof(*accel_t_gyro));

// Swap all high and low bytes.


// After this, the registers values are swapped,
// so the structure name like x_accel_l does no
// longer contain the lower byte.
uint8_t swap;
#define SWAP(x,y) swap = x; x = y; y = swap

SWAP ((*accel_t_gyro).reg.x_accel_h, (*accel_t_gyro).reg.x_accel_l);


SWAP ((*accel_t_gyro).reg.y_accel_h, (*accel_t_gyro).reg.y_accel_l);
SWAP ((*accel_t_gyro).reg.z_accel_h, (*accel_t_gyro).reg.z_accel_l);
SWAP ((*accel_t_gyro).reg.t_h, (*accel_t_gyro).reg.t_l);
SWAP ((*accel_t_gyro).reg.x_gyro_h, (*accel_t_gyro).reg.x_gyro_l);
SWAP ((*accel_t_gyro).reg.y_gyro_h, (*accel_t_gyro).reg.y_gyro_l);
SWAP ((*accel_t_gyro).reg.z_gyro_h, (*accel_t_gyro).reg.z_gyro_l);

return error;
}

// The sensor should be motionless on a horizontal surface


// while calibration is happening
void calibrate_sensors() {
int num_readings = 10;
float x_accel = 0;
float y_accel = 0;
float z_accel = 0;
float x_gyro = 0;
float y_gyro = 0;
float z_gyro = 0;
accel_t_gyro_union accel_t_gyro;

//Serial.println("Starting Calibration");

// Discard the first set of values read from the IMU


read_gyro_accel_vals((uint8_t *) &accel_t_gyro);

// Read and average the raw values from the IMU


for (int i = 0; i < num_readings; i++) {
read_gyro_accel_vals((uint8_t *) &accel_t_gyro);
x_accel += accel_t_gyro.value.x_accel;
y_accel += accel_t_gyro.value.y_accel;
z_accel += accel_t_gyro.value.z_accel;
x_gyro += accel_t_gyro.value.x_gyro;
y_gyro += accel_t_gyro.value.y_gyro;
z_gyro += accel_t_gyro.value.z_gyro;
delay(100);
}
x_accel /= num_readings;
y_accel /= num_readings;
z_accel /= num_readings;
x_gyro /= num_readings;
y_gyro /= num_readings;
z_gyro /= num_readings;

// Store the raw calibration values globally


base_x_accel = x_accel;
base_y_accel = y_accel;
base_z_accel = z_accel;
base_x_gyro = x_gyro;
base_y_gyro = y_gyro;
base_z_gyro = z_gyro;

//Serial.println("Finishing Calibration");
}
void setup()
{

int error;
uint8_t c;

Serial.begin(9600);
/*
Serial.println(F("InvenSense MPU-6050"));
Serial.println(F("June 2012"));
*/
// Initialize the 'Wire' class for the I2C-bus.
Wire.begin();

// default at power-up:
// Gyro at 250 degrees second
// Acceleration at 2g
// Clock source at internal 8MHz
// The device is in sleep mode.
//

error = MPU6050_read (MPU6050_WHO_AM_I, &c, 1);


/*
Serial.print(F("WHO_AM_I : "));
Serial.print(c,HEX);
Serial.print(F(", error = "));
Serial.println(error,DEC);
*/

// According to the datasheet, the 'sleep' bit


// should read a '1'. But I read a '0'.
// That bit has to be cleared, since the sensor
// is in sleep mode at power-up. Even if the
// bit reads '0'.
error = MPU6050_read (MPU6050_PWR_MGMT_2, &c, 1);
/*
Serial.print(F("PWR_MGMT_2 : "));
Serial.print(c,HEX);
Serial.print(F(", error = "));
Serial.println(error,DEC);
*/

// Clear the 'sleep' bit to start the sensor.


MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);

//Initialize the angles


calibrate_sensors();
set_last_read_angle_data(millis(), 0, 0, 0, 0, 0, 0);
}
void(* resetFunc) (void) = 0; //declare reset function @ address 0
void loop()
{

int error;
double dT;
accel_t_gyro_union accel_t_gyro;

/*
Serial.println(F(""));
Serial.println(F("MPU-6050"));
*/

// Read the raw values.


error = read_gyro_accel_vals((uint8_t*) &accel_t_gyro);

// Get the time of reading for rotation computations


unsigned long t_now = millis();

/*
Serial.print(F("Read accel, temp and gyro, error = "));
Serial.println(error,DEC);

// Print the raw acceleration values


Serial.print(F("accel x,y,z: "));
Serial.print(accel_t_gyro.value.x_accel, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.y_accel, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.z_accel, DEC);
Serial.println(F(""));
*/

// The temperature sensor is -40 to +85 degrees Celsius.


// It is a signed integer.
// According to the datasheet:
// 340 per degrees Celsius, -512 at 35 degrees.
// At 0 degrees: -512 - (340 * 35) = -12412
/*
Serial.print(F("temperature: "));
dT = ( (double) accel_t_gyro.value.temperature + 12412.0) / 340.0;
Serial.print(dT, 3);
Serial.print(F(" degrees Celsius"));
Serial.println(F(""));

// Print the raw gyro values.


Serial.print(F("raw gyro x,y,z : "));
Serial.print(accel_t_gyro.value.x_gyro, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.y_gyro, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.z_gyro, DEC);
Serial.print(F(", "));
Serial.println(F(""));
*/

// Convert gyro values to degrees/sec


float FS_SEL = 131;
/*
float gyro_x = (accel_t_gyro.value.x_gyro - base_x_gyro)/FS_SEL;
float gyro_y = (accel_t_gyro.value.y_gyro - base_y_gyro)/FS_SEL;
float gyro_z = (accel_t_gyro.value.z_gyro - base_z_gyro)/FS_SEL;
*/
float gyro_x = (accel_t_gyro.value.x_gyro - base_x_gyro)/FS_SEL;
float gyro_y = (accel_t_gyro.value.y_gyro - base_y_gyro)/FS_SEL;
float gyro_z = (accel_t_gyro.value.z_gyro - base_z_gyro)/FS_SEL;

// Get raw acceleration values


//float G_CONVERT = 16384;
float accel_x = accel_t_gyro.value.x_accel;
float accel_y = accel_t_gyro.value.y_accel;
float accel_z = accel_t_gyro.value.z_accel;

// Get angle values from accelerometer


float RADIANS_TO_DEGREES = 180/3.14159;
// float accel_vector_length = sqrt(pow(accel_x,2) + pow(accel_y,2) + pow(accel_z,2));
float accel_angle_y = atan(-1*accel_x/sqrt(pow(accel_y,2) +
pow(accel_z,2)))*RADIANS_TO_DEGREES;
float accel_angle_x = atan(accel_y/sqrt(pow(accel_x,2) +
pow(accel_z,2)))*RADIANS_TO_DEGREES;

float accel_angle_z = 0;

// Compute the (filtered) gyro angles


float dt =(t_now - get_last_time())/1000.0;
float gyro_angle_x = gyro_x*dt + get_last_x_angle();
float gyro_angle_y = gyro_y*dt + get_last_y_angle();
float gyro_angle_z = gyro_z*dt + get_last_z_angle();

// Compute the drifting gyro angles


float unfiltered_gyro_angle_x = gyro_x*dt + get_last_gyro_x_angle();
float unfiltered_gyro_angle_y = gyro_y*dt + get_last_gyro_y_angle();
float unfiltered_gyro_angle_z = gyro_z*dt + get_last_gyro_z_angle();

// Apply the complementary filter to figure out the change in angle - choice of alpha is
// estimated now. Alpha depends on the sampling rate...
float alpha = 0.96;
float angle_x = alpha*gyro_angle_x + (1.0 - alpha)*accel_angle_x;
float angle_y = alpha*gyro_angle_y + (1.0 - alpha)*accel_angle_y;
float angle_z = gyro_angle_z; //Accelerometer doesn't give z-angle
// Update the saved data with the latest values
set_last_read_angle_data(t_now, angle_x, angle_y, angle_z, unfiltered_gyro_angle_x,
unfiltered_gyro_angle_y, unfiltered_gyro_angle_z);

// Send the data to the serial port


Serial.print(F("DEL:")); //Delta T
Serial.print(dt, DEC);
Serial.print(F(" #ACC:")); //Accelerometer angle
Serial.print(accel_angle_x, 2);
Serial.print(F(","));
Serial.print(accel_angle_y, 2);
Serial.print(F(","));
Serial.print(accel_angle_z, 2);
Serial.print(F(" #GYR:"));
Serial.print(unfiltered_gyro_angle_x, 2); //Gyroscope angle
Serial.print(F(","));
Serial.print(unfiltered_gyro_angle_y, 2);
Serial.print(F(","));
Serial.print(unfiltered_gyro_angle_z, 2);
Serial.print(F(" #FIL:")); //Filtered angle
Serial.print(angle_x, 2);
Serial.print(F(","));
Serial.print(angle_y, 2);
Serial.print(F(","));
Serial.print(angle_z, 2);
Serial.println(F(""));

delay(5);
}

// --------------------------------------------------------
// MPU6050_read
//
// This is a common function to read multiple bytes
// from an I2C device.
//
// It uses the boolean parameter for Wire.endTransMission()
// to be able to hold or release the I2C-bus.
// This is implemented in Arduino 1.0.1.
//
// Only this function is used to read.
// There is no function for a single byte.
//
int MPU6050_read(int start, uint8_t *buffer, int size)
{
int i, n, error;

Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start);
if (n != 1)
return (-10);

n = Wire.endTransmission(false); // hold the I2C-bus


if (n != 0)
return (n);

// Third parameter is true: relase I2C-bus after data is read.


Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true);
i = 0;
while(Wire.available() && i<size)
{
buffer[i++]=Wire.read();
}
if ( i != size)
return (-11);

return (0); // return : no error


}

// --------------------------------------------------------
// MPU6050_write
//
// This is a common function to write multiple bytes to an I2C device.
//
// If only a single register is written,
// use the function MPU_6050_write_reg().
//
// Parameters:
// start : Start address, use a define for the register
// pData : A pointer to the data to write.
// size : The number of bytes to write.
//
// If only a single register is written, a pointer
// to the data has to be used, and the size is
// a single byte:
// int data = 0; // the data to write
// MPU6050_write (MPU6050_PWR_MGMT_1, &c, 1);
//
int MPU6050_write(int start, const uint8_t *pData, int size)
{
int n, error;

Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start); // write the start address
if (n != 1)
return (-20);

n = Wire.write(pData, size); // write data bytes


if (n != size)
return (-21);
error = Wire.endTransmission(true); // release the I2C-bus
if (error != 0)
return (error);

return (0); // return : no error


}

// --------------------------------------------------------
// MPU6050_write_reg
//
// An extra function to write a single register.
// It is just a wrapper around the MPU_6050_write()
// function, and it is only a convenient function
// to make it easier to write a single register.
//
int MPU6050_write_reg(int reg, uint8_t data)
{
int error;

error = MPU6050_write(reg, &data, 1);

return (error);
}
==================================================================
60. ALARM GEMPA BUMI

atau
Pada proyek ini kita memanfaatkan MPU6050 untuk mendeteksi adanya akselerasi pada arah
mendatar. Ketika akselerasi di atas tresshold maka bell akan aktif.

// MPU-6050 Accelerometer + Gyro


// -----------------------------
//
// By arduino.cc user "Krodal".
// June 2012
// Open Source / Public Domain
//
// Using Arduino 1.0.1
// It will not work with an older version,
// since Wire.endTransmission() uses a parameter
// to hold or release the I2C bus.
//
// Documentation:
// - The InvenSense documents:
// - "MPU-6000 and MPU-6050 Product Specification",
// PS-MPU-6000A.pdf
// - "MPU-6000 and MPU-6050 Register Map and Descriptions",
// RM-MPU-6000A.pdf or RS-MPU-6000A.pdf
// - "MPU-6000/MPU-6050 9-Axis Evaluation Board User Guide"
// AN-MPU-6000EVB.pdf
//
// The accuracy is 16-bits.
//
// Temperature sensor from -40 to +85 degrees Celsius
// 340 per degrees, -512 at 35 degrees.
//
// At power-up, all registers are zero, except these two:
// Register 0x6B (PWR_MGMT_2) = 0x40 (I read zero).
// Register 0x75 (WHO_AM_I) = 0x68.
//

#include <Wire.h>

#define MPU6050_AUX_VDDIO 0x01 // R/W


#define MPU6050_SMPLRT_DIV 0x19 // R/W
#define MPU6050_CONFIG 0x1A // R/W
#define MPU6050_GYRO_CONFIG 0x1B // R/W
#define MPU6050_ACCEL_CONFIG 0x1C // R/W
#define MPU6050_FF_THR 0x1D // R/W
#define MPU6050_FF_DUR 0x1E // R/W
#define MPU6050_MOT_THR 0x1F // R/W
#define MPU6050_MOT_DUR 0x20 // R/W
#define MPU6050_ZRMOT_THR 0x21 // R/W
#define MPU6050_ZRMOT_DUR 0x22 // R/W
#define MPU6050_FIFO_EN 0x23 // R/W
#define MPU6050_I2C_MST_CTRL 0x24 // R/W
#define MPU6050_I2C_SLV0_ADDR 0x25 // R/W
#define MPU6050_I2C_SLV0_REG 0x26 // R/W
#define MPU6050_I2C_SLV0_CTRL 0x27 // R/W
#define MPU6050_I2C_SLV1_ADDR 0x28 // R/W
#define MPU6050_I2C_SLV1_REG 0x29 // R/W
#define MPU6050_I2C_SLV1_CTRL 0x2A // R/W
#define MPU6050_I2C_SLV2_ADDR 0x2B // R/W
#define MPU6050_I2C_SLV2_REG 0x2C // R/W
#define MPU6050_I2C_SLV2_CTRL 0x2D // R/W
#define MPU6050_I2C_SLV3_ADDR 0x2E // R/W
#define MPU6050_I2C_SLV3_REG 0x2F // R/W
#define MPU6050_I2C_SLV3_CTRL 0x30 // R/W
#define MPU6050_I2C_SLV4_ADDR 0x31 // R/W
#define MPU6050_I2C_SLV4_REG 0x32 // R/W
#define MPU6050_I2C_SLV4_DO 0x33 // R/W
#define MPU6050_I2C_SLV4_CTRL 0x34 // R/W
#define MPU6050_I2C_SLV4_DI 0x35 // R
#define MPU6050_I2C_MST_STATUS 0x36 // R
#define MPU6050_INT_PIN_CFG 0x37 // R/W
#define MPU6050_INT_ENABLE 0x38 // R/W
#define MPU6050_INT_STATUS 0x3A // R
#define MPU6050_ACCEL_XOUT_H 0x3B // R
#define MPU6050_ACCEL_XOUT_L 0x3C // R
#define MPU6050_ACCEL_YOUT_H 0x3D // R
#define MPU6050_ACCEL_YOUT_L 0x3E // R
#define MPU6050_ACCEL_ZOUT_H 0x3F // R
#define MPU6050_ACCEL_ZOUT_L 0x40 // R
#define MPU6050_TEMP_OUT_H 0x41 // R
#define MPU6050_TEMP_OUT_L 0x42 // R
#define MPU6050_GYRO_XOUT_H 0x43 // R
#define MPU6050_GYRO_XOUT_L 0x44 // R
#define MPU6050_GYRO_YOUT_H 0x45 // R
#define MPU6050_GYRO_YOUT_L 0x46 // R
#define MPU6050_GYRO_ZOUT_H 0x47 // R
#define MPU6050_GYRO_ZOUT_L 0x48 // R
#define MPU6050_EXT_SENS_DATA_00 0x49 // R
#define MPU6050_EXT_SENS_DATA_01 0x4A // R
#define MPU6050_EXT_SENS_DATA_02 0x4B // R
#define MPU6050_EXT_SENS_DATA_03 0x4C // R
#define MPU6050_EXT_SENS_DATA_04 0x4D // R
#define MPU6050_EXT_SENS_DATA_05 0x4E // R
#define MPU6050_EXT_SENS_DATA_06 0x4F // R
#define MPU6050_EXT_SENS_DATA_07 0x50 // R
#define MPU6050_EXT_SENS_DATA_08 0x51 // R
#define MPU6050_EXT_SENS_DATA_09 0x52 // R
#define MPU6050_EXT_SENS_DATA_10 0x53 // R
#define MPU6050_EXT_SENS_DATA_11 0x54 // R
#define MPU6050_EXT_SENS_DATA_12 0x55 // R
#define MPU6050_EXT_SENS_DATA_13 0x56 // R
#define MPU6050_EXT_SENS_DATA_14 0x57 // R
#define MPU6050_EXT_SENS_DATA_15 0x58 // R
#define MPU6050_EXT_SENS_DATA_16 0x59 // R
#define MPU6050_EXT_SENS_DATA_17 0x5A // R
#define MPU6050_EXT_SENS_DATA_18 0x5B // R
#define MPU6050_EXT_SENS_DATA_19 0x5C // R
#define MPU6050_EXT_SENS_DATA_20 0x5D // R
#define MPU6050_EXT_SENS_DATA_21 0x5E // R
#define MPU6050_EXT_SENS_DATA_22 0x5F // R
#define MPU6050_EXT_SENS_DATA_23 0x60 // R
#define MPU6050_MOT_DETECT_STATUS 0x61 // R
#define MPU6050_I2C_SLV0_DO 0x63 // R/W
#define MPU6050_I2C_SLV1_DO 0x64 // R/W
#define MPU6050_I2C_SLV2_DO 0x65 // R/W
#define MPU6050_I2C_SLV3_DO 0x66 // R/W
#define MPU6050_I2C_MST_DELAY_CTRL 0x67 // R/W
#define MPU6050_SIGNAL_PATH_RESET 0x68 // R/W
#define MPU6050_MOT_DETECT_CTRL 0x69 // R/W
#define MPU6050_USER_CTRL 0x6A // R/W
#define MPU6050_PWR_MGMT_1 0x6B // R/W
#define MPU6050_PWR_MGMT_2 0x6C // R/W
#define MPU6050_FIFO_COUNTH 0x72 // R/W
#define MPU6050_FIFO_COUNTL 0x73 // R/W
#define MPU6050_FIFO_R_W 0x74 // R/W
#define MPU6050_WHO_AM_I 0x75 // R
#define MPU6050_D0 0
#define MPU6050_D1 1
#define MPU6050_D2 2
#define MPU6050_D3 3
#define MPU6050_D4 4
#define MPU6050_D5 5
#define MPU6050_D6 6
#define MPU6050_D7 7

// AUX_VDDIO Register
#define MPU6050_AUX_VDDIO MPU6050_D7 // I2C high: 1=VDD, 0=VLOGIC

#define MPU6050_DLPF_CFG0 MPU6050_D0


#define MPU6050_DLPF_CFG1 MPU6050_D1
#define MPU6050_DLPF_CFG2 MPU6050_D2
#define MPU6050_EXT_SYNC_SET0 MPU6050_D3
#define MPU6050_EXT_SYNC_SET1 MPU6050_D4
#define MPU6050_EXT_SYNC_SET2 MPU6050_D5

#define MPU6050_EXT_SYNC_SET_0 (0)


#define MPU6050_EXT_SYNC_SET_1 (bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_2 (bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_3 (bit(MPU6050_EXT_SYNC_SET1)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_4 (bit(MPU6050_EXT_SYNC_SET2))
#define MPU6050_EXT_SYNC_SET_5 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_6 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_7 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1)|bit(MPU6050_EXT_SYNC_SET0))

#define MPU6050_EXT_SYNC_DISABLED MPU6050_EXT_SYNC_SET_0


#define MPU6050_EXT_SYNC_TEMP_OUT_L MPU6050_EXT_SYNC_SET_1
#define MPU6050_EXT_SYNC_GYRO_XOUT_L MPU6050_EXT_SYNC_SET_2
#define MPU6050_EXT_SYNC_GYRO_YOUT_L MPU6050_EXT_SYNC_SET_3
#define MPU6050_EXT_SYNC_GYRO_ZOUT_L MPU6050_EXT_SYNC_SET_4
#define MPU6050_EXT_SYNC_ACCEL_XOUT_L MPU6050_EXT_SYNC_SET_5
#define MPU6050_EXT_SYNC_ACCEL_YOUT_L MPU6050_EXT_SYNC_SET_6
#define MPU6050_EXT_SYNC_ACCEL_ZOUT_L MPU6050_EXT_SYNC_SET_7

#define MPU6050_DLPF_CFG_0 (0)


#define MPU6050_DLPF_CFG_1 (bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_2 (bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_3 (bit(MPU6050_DLPF_CFG1)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_4 (bit(MPU6050_DLPF_CFG2))
#define MPU6050_DLPF_CFG_5 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_6 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_7 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1)|
bit(MPU6050_DLPF_CFG0))

#define MPU6050_DLPF_260HZ MPU6050_DLPF_CFG_0


#define MPU6050_DLPF_184HZ MPU6050_DLPF_CFG_1
#define MPU6050_DLPF_94HZ MPU6050_DLPF_CFG_2
#define MPU6050_DLPF_44HZ MPU6050_DLPF_CFG_3
#define MPU6050_DLPF_21HZ MPU6050_DLPF_CFG_4
#define MPU6050_DLPF_10HZ MPU6050_DLPF_CFG_5
#define MPU6050_DLPF_5HZ MPU6050_DLPF_CFG_6
#define MPU6050_DLPF_RESERVED MPU6050_DLPF_CFG_7

#define MPU6050_FS_SEL0 MPU6050_D3


#define MPU6050_FS_SEL1 MPU6050_D4
#define MPU6050_ZG_ST MPU6050_D5
#define MPU6050_YG_ST MPU6050_D6
#define MPU6050_XG_ST MPU6050_D7

#define MPU6050_FS_SEL_0 (0)


#define MPU6050_FS_SEL_1 (bit(MPU6050_FS_SEL0))
#define MPU6050_FS_SEL_2 (bit(MPU6050_FS_SEL1))
#define MPU6050_FS_SEL_3 (bit(MPU6050_FS_SEL1)|bit(MPU6050_FS_SEL0))

#define MPU6050_FS_SEL_250 MPU6050_FS_SEL_0


#define MPU6050_FS_SEL_500 MPU6050_FS_SEL_1
#define MPU6050_FS_SEL_1000 MPU6050_FS_SEL_2
#define MPU6050_FS_SEL_2000 MPU6050_FS_SEL_3

#define MPU6050_ACCEL_HPF0 MPU6050_D0


#define MPU6050_ACCEL_HPF1 MPU6050_D1
#define MPU6050_ACCEL_HPF2 MPU6050_D2
#define MPU6050_AFS_SEL0 MPU6050_D3
#define MPU6050_AFS_SEL1 MPU6050_D4
#define MPU6050_ZA_ST MPU6050_D5
#define MPU6050_YA_ST MPU6050_D6
#define MPU6050_XA_ST MPU6050_D7

#define MPU6050_ACCEL_HPF_0 (0)


#define MPU6050_ACCEL_HPF_1 (bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_2 (bit(MPU6050_ACCEL_HPF1))
#define MPU6050_ACCEL_HPF_3 (bit(MPU6050_ACCEL_HPF1)|
bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_4 (bit(MPU6050_ACCEL_HPF2))
#define MPU6050_ACCEL_HPF_7 (bit(MPU6050_ACCEL_HPF2)|
bit(MPU6050_ACCEL_HPF1)|bit(MPU6050_ACCEL_HPF0))

#define MPU6050_ACCEL_HPF_RESET MPU6050_ACCEL_HPF_0


#define MPU6050_ACCEL_HPF_5HZ MPU6050_ACCEL_HPF_1
#define MPU6050_ACCEL_HPF_2_5HZ MPU6050_ACCEL_HPF_2
#define MPU6050_ACCEL_HPF_1_25HZ MPU6050_ACCEL_HPF_3
#define MPU6050_ACCEL_HPF_0_63HZ MPU6050_ACCEL_HPF_4
#define MPU6050_ACCEL_HPF_HOLD MPU6050_ACCEL_HPF_7

#define MPU6050_AFS_SEL_0 (0)


#define MPU6050_AFS_SEL_1 (bit(MPU6050_AFS_SEL0))
#define MPU6050_AFS_SEL_2 (bit(MPU6050_AFS_SEL1))
#define MPU6050_AFS_SEL_3 (bit(MPU6050_AFS_SEL1)|bit(MPU6050_AFS_SEL0))

#define MPU6050_AFS_SEL_2G MPU6050_AFS_SEL_0


#define MPU6050_AFS_SEL_4G MPU6050_AFS_SEL_1
#define MPU6050_AFS_SEL_8G MPU6050_AFS_SEL_2
#define MPU6050_AFS_SEL_16G MPU6050_AFS_SEL_3

#define MPU6050_SLV0_FIFO_EN MPU6050_D0


#define MPU6050_SLV1_FIFO_EN MPU6050_D1
#define MPU6050_SLV2_FIFO_EN MPU6050_D2
#define MPU6050_ACCEL_FIFO_EN MPU6050_D3
#define MPU6050_ZG_FIFO_EN MPU6050_D4
#define MPU6050_YG_FIFO_EN MPU6050_D5
#define MPU6050_XG_FIFO_EN MPU6050_D6
#define MPU6050_TEMP_FIFO_EN MPU6050_D7

#define MPU6050_I2C_MST_CLK0 MPU6050_D0


#define MPU6050_I2C_MST_CLK1 MPU6050_D1
#define MPU6050_I2C_MST_CLK2 MPU6050_D2
#define MPU6050_I2C_MST_CLK3 MPU6050_D3
#define MPU6050_I2C_MST_P_NSR MPU6050_D4
#define MPU6050_SLV_3_FIFO_EN MPU6050_D5
#define MPU6050_WAIT_FOR_ES MPU6050_D6
#define MPU6050_MULT_MST_EN MPU6050_D7

// Combined definitions for the I2C_MST_CLK


#define MPU6050_I2C_MST_CLK_0 (0)
#define MPU6050_I2C_MST_CLK_1 (bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_2 (bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_3 (bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_4 (bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_5 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_6 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_7 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_8 (bit(MPU6050_I2C_MST_CLK3))
#define MPU6050_I2C_MST_CLK_9 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_10 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_11 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_12 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_13 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_14 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_15 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))

#define MPU6050_I2C_MST_CLK_348KHZ MPU6050_I2C_MST_CLK_0


#define MPU6050_I2C_MST_CLK_333KHZ MPU6050_I2C_MST_CLK_1
#define MPU6050_I2C_MST_CLK_320KHZ MPU6050_I2C_MST_CLK_2
#define MPU6050_I2C_MST_CLK_308KHZ MPU6050_I2C_MST_CLK_3
#define MPU6050_I2C_MST_CLK_296KHZ MPU6050_I2C_MST_CLK_4
#define MPU6050_I2C_MST_CLK_286KHZ MPU6050_I2C_MST_CLK_5
#define MPU6050_I2C_MST_CLK_276KHZ MPU6050_I2C_MST_CLK_6
#define MPU6050_I2C_MST_CLK_267KHZ MPU6050_I2C_MST_CLK_7
#define MPU6050_I2C_MST_CLK_258KHZ MPU6050_I2C_MST_CLK_8
#define MPU6050_I2C_MST_CLK_500KHZ MPU6050_I2C_MST_CLK_9
#define MPU6050_I2C_MST_CLK_471KHZ MPU6050_I2C_MST_CLK_10
#define MPU6050_I2C_MST_CLK_444KHZ MPU6050_I2C_MST_CLK_11
#define MPU6050_I2C_MST_CLK_421KHZ MPU6050_I2C_MST_CLK_12
#define MPU6050_I2C_MST_CLK_400KHZ MPU6050_I2C_MST_CLK_13
#define MPU6050_I2C_MST_CLK_381KHZ MPU6050_I2C_MST_CLK_14
#define MPU6050_I2C_MST_CLK_364KHZ MPU6050_I2C_MST_CLK_15

#define MPU6050_I2C_SLV0_RW MPU6050_D7

#define MPU6050_I2C_SLV0_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV0_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV0_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV0_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV0_GRP MPU6050_D4
#define MPU6050_I2C_SLV0_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV0_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV0_EN MPU6050_D7

#define MPU6050_I2C_SLV0_LEN_MASK 0x0F


#define MPU6050_I2C_SLV1_RW MPU6050_D7

#define MPU6050_I2C_SLV1_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV1_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV1_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV1_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV1_GRP MPU6050_D4
#define MPU6050_I2C_SLV1_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV1_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV1_EN MPU6050_D7

#define MPU6050_I2C_SLV1_LEN_MASK 0x0F

#define MPU6050_I2C_SLV2_RW MPU6050_D7

#define MPU6050_I2C_SLV2_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV2_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV2_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV2_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV2_GRP MPU6050_D4
#define MPU6050_I2C_SLV2_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV2_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV2_EN MPU6050_D7

#define MPU6050_I2C_SLV2_LEN_MASK 0x0F

#define MPU6050_I2C_SLV3_RW MPU6050_D7

#define MPU6050_I2C_SLV3_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV3_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV3_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV3_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV3_GRP MPU6050_D4
#define MPU6050_I2C_SLV3_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV3_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV3_EN MPU6050_D7

#define MPU6050_I2C_SLV3_LEN_MASK 0x0F

#define MPU6050_I2C_SLV4_RW MPU6050_D7


#define MPU6050_I2C_MST_DLY0 MPU6050_D0
#define MPU6050_I2C_MST_DLY1 MPU6050_D1
#define MPU6050_I2C_MST_DLY2 MPU6050_D2
#define MPU6050_I2C_MST_DLY3 MPU6050_D3
#define MPU6050_I2C_MST_DLY4 MPU6050_D4
#define MPU6050_I2C_SLV4_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV4_INT_EN MPU6050_D6
#define MPU6050_I2C_SLV4_EN MPU6050_D7

#define MPU6050_I2C_MST_DLY_MASK 0x1F

#define MPU6050_I2C_SLV0_NACK MPU6050_D0


#define MPU6050_I2C_SLV1_NACK MPU6050_D1
#define MPU6050_I2C_SLV2_NACK MPU6050_D2
#define MPU6050_I2C_SLV3_NACK MPU6050_D3
#define MPU6050_I2C_SLV4_NACK MPU6050_D4
#define MPU6050_I2C_LOST_ARB MPU6050_D5
#define MPU6050_I2C_SLV4_DONE MPU6050_D6
#define MPU6050_PASS_THROUGH MPU6050_D7

#define MPU6050_CLKOUT_EN MPU6050_D0


#define MPU6050_I2C_BYPASS_EN MPU6050_D1
#define MPU6050_FSYNC_INT_EN MPU6050_D2
#define MPU6050_FSYNC_INT_LEVEL MPU6050_D3
#define MPU6050_INT_RD_CLEAR MPU6050_D4
#define MPU6050_LATCH_INT_EN MPU6050_D5
#define MPU6050_INT_OPEN MPU6050_D6
#define MPU6050_INT_LEVEL MPU6050_D7

#define MPU6050_DATA_RDY_EN MPU6050_D0


#define MPU6050_I2C_MST_INT_EN MPU6050_D3
#define MPU6050_FIFO_OFLOW_EN MPU6050_D4
#define MPU6050_ZMOT_EN MPU6050_D5
#define MPU6050_MOT_EN MPU6050_D6
#define MPU6050_FF_EN MPU6050_D7

#define MPU6050_DATA_RDY_INT MPU6050_D0


#define MPU6050_I2C_MST_INT MPU6050_D3
#define MPU6050_FIFO_OFLOW_INT MPU6050_D4
#define MPU6050_ZMOT_INT MPU6050_D5
#define MPU6050_MOT_INT MPU6050_D6
#define MPU6050_FF_INT MPU6050_D7

#define MPU6050_MOT_ZRMOT MPU6050_D0


#define MPU6050_MOT_ZPOS MPU6050_D2
#define MPU6050_MOT_ZNEG MPU6050_D3
#define MPU6050_MOT_YPOS MPU6050_D4
#define MPU6050_MOT_YNEG MPU6050_D5
#define MPU6050_MOT_XPOS MPU6050_D6
#define MPU6050_MOT_XNEG MPU6050_D7

#define MPU6050_I2C_SLV0_DLY_EN MPU6050_D0


#define MPU6050_I2C_SLV1_DLY_EN MPU6050_D1
#define MPU6050_I2C_SLV2_DLY_EN MPU6050_D2
#define MPU6050_I2C_SLV3_DLY_EN MPU6050_D3
#define MPU6050_I2C_SLV4_DLY_EN MPU6050_D4
#define MPU6050_DELAY_ES_SHADOW MPU6050_D7

#define MPU6050_TEMP_RESET MPU6050_D0


#define MPU6050_ACCEL_RESET MPU6050_D1
#define MPU6050_GYRO_RESET MPU6050_D2

#define MPU6050_MOT_COUNT0 MPU6050_D0


#define MPU6050_MOT_COUNT1 MPU6050_D1
#define MPU6050_FF_COUNT0 MPU6050_D2
#define MPU6050_FF_COUNT1 MPU6050_D3
#define MPU6050_ACCEL_ON_DELAY0 MPU6050_D4
#define MPU6050_ACCEL_ON_DELAY1 MPU6050_D5

#define MPU6050_MOT_COUNT_0 (0)


#define MPU6050_MOT_COUNT_1 (bit(MPU6050_MOT_COUNT0))
#define MPU6050_MOT_COUNT_2 (bit(MPU6050_MOT_COUNT1))
#define MPU6050_MOT_COUNT_3 (bit(MPU6050_MOT_COUNT1)|
bit(MPU6050_MOT_COUNT0))

#define MPU6050_MOT_COUNT_RESET MPU6050_MOT_COUNT_0

#define MPU6050_FF_COUNT_0 (0)


#define MPU6050_FF_COUNT_1 (bit(MPU6050_FF_COUNT0))
#define MPU6050_FF_COUNT_2 (bit(MPU6050_FF_COUNT1))
#define MPU6050_FF_COUNT_3 (bit(MPU6050_FF_COUNT1)|bit(MPU6050_FF_COUNT0))

#define MPU6050_FF_COUNT_RESET MPU6050_FF_COUNT_0

#define MPU6050_ACCEL_ON_DELAY_0 (0)


#define MPU6050_ACCEL_ON_DELAY_1 (bit(MPU6050_ACCEL_ON_DELAY0))
#define MPU6050_ACCEL_ON_DELAY_2 (bit(MPU6050_ACCEL_ON_DELAY1))
#define MPU6050_ACCEL_ON_DELAY_3 (bit(MPU6050_ACCEL_ON_DELAY1)|
bit(MPU6050_ACCEL_ON_DELAY0))
#define MPU6050_ACCEL_ON_DELAY_0MS MPU6050_ACCEL_ON_DELAY_0
#define MPU6050_ACCEL_ON_DELAY_1MS MPU6050_ACCEL_ON_DELAY_1
#define MPU6050_ACCEL_ON_DELAY_2MS MPU6050_ACCEL_ON_DELAY_2
#define MPU6050_ACCEL_ON_DELAY_3MS MPU6050_ACCEL_ON_DELAY_3

#define MPU6050_SIG_COND_RESET MPU6050_D0


#define MPU6050_I2C_MST_RESET MPU6050_D1
#define MPU6050_FIFO_RESET MPU6050_D2
#define MPU6050_I2C_IF_DIS MPU6050_D4 // must be 0 for MPU-6050
#define MPU6050_I2C_MST_EN MPU6050_D5
#define MPU6050_FIFO_EN MPU6050_D6

#define MPU6050_CLKSEL0 MPU6050_D0


#define MPU6050_CLKSEL1 MPU6050_D1
#define MPU6050_CLKSEL2 MPU6050_D2
#define MPU6050_TEMP_DIS MPU6050_D3 // 1: disable temperature sensor
#define MPU6050_CYCLE MPU6050_D5 // 1: sample and sleep
#define MPU6050_SLEEP MPU6050_D6 // 1: sleep mode
#define MPU6050_DEVICE_RESET MPU6050_D7 // 1: reset to default values

#define MPU6050_CLKSEL_0 (0)


#define MPU6050_CLKSEL_1 (bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_2 (bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_3 (bit(MPU6050_CLKSEL1)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_4 (bit(MPU6050_CLKSEL2))
#define MPU6050_CLKSEL_5 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_6 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_7 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1)|
bit(MPU6050_CLKSEL0))

#define MPU6050_CLKSEL_INTERNAL MPU6050_CLKSEL_0


#define MPU6050_CLKSEL_X MPU6050_CLKSEL_1
#define MPU6050_CLKSEL_Y MPU6050_CLKSEL_2
#define MPU6050_CLKSEL_Z MPU6050_CLKSEL_3
#define MPU6050_CLKSEL_EXT_32KHZ MPU6050_CLKSEL_4
#define MPU6050_CLKSEL_EXT_19_2MHZ MPU6050_CLKSEL_5
#define MPU6050_CLKSEL_RESERVED MPU6050_CLKSEL_6
#define MPU6050_CLKSEL_STOP MPU6050_CLKSEL_7

#define MPU6050_STBY_ZG MPU6050_D0


#define MPU6050_STBY_YG MPU6050_D1
#define MPU6050_STBY_XG MPU6050_D2
#define MPU6050_STBY_ZA MPU6050_D3
#define MPU6050_STBY_YA MPU6050_D4
#define MPU6050_STBY_XA MPU6050_D5
#define MPU6050_LP_WAKE_CTRL0 MPU6050_D6
#define MPU6050_LP_WAKE_CTRL1 MPU6050_D7

#define MPU6050_LP_WAKE_CTRL_0 (0)


#define MPU6050_LP_WAKE_CTRL_1 (bit(MPU6050_LP_WAKE_CTRL0))
#define MPU6050_LP_WAKE_CTRL_2 (bit(MPU6050_LP_WAKE_CTRL1))
#define MPU6050_LP_WAKE_CTRL_3 (bit(MPU6050_LP_WAKE_CTRL1)|
bit(MPU6050_LP_WAKE_CTRL0))

#define MPU6050_LP_WAKE_1_25HZ MPU6050_LP_WAKE_CTRL_0


#define MPU6050_LP_WAKE_2_5HZ MPU6050_LP_WAKE_CTRL_1
#define MPU6050_LP_WAKE_5HZ MPU6050_LP_WAKE_CTRL_2
#define MPU6050_LP_WAKE_10HZ MPU6050_LP_WAKE_CTRL_3

#define MPU6050_I2C_ADDRESS 0x68

typedef union accel_t_gyro_union


{
struct
{
uint8_t x_accel_h;
uint8_t x_accel_l;
uint8_t y_accel_h;
uint8_t y_accel_l;
uint8_t z_accel_h;
uint8_t z_accel_l;
uint8_t t_h;
uint8_t t_l;
uint8_t x_gyro_h;
uint8_t x_gyro_l;
uint8_t y_gyro_h;
uint8_t y_gyro_l;
uint8_t z_gyro_h;
uint8_t z_gyro_l;
} reg;
struct
{
int x_accel;
int y_accel;
int z_accel;
int temperature;
int x_gyro;
int y_gyro;
int z_gyro;
} value;
};

// Use the following global variables and access functions to help store the overall
// rotation angle of the sensor
unsigned long last_read_time;
float last_x_angle; // These are the filtered angles
float last_y_angle;
float last_z_angle;
float last_gyro_x_angle; // Store the gyro angles to compare drift
float last_gyro_y_angle;
float last_gyro_z_angle;

void set_last_read_angle_data(unsigned long time, float x, float y, float z, float x_gyro, float
y_gyro, float z_gyro) {
last_read_time = time;
last_x_angle = x;
last_y_angle = y;
last_z_angle = z;
last_gyro_x_angle = x_gyro;
last_gyro_y_angle = y_gyro;
last_gyro_z_angle = z_gyro;
}

inline unsigned long get_last_time() {return last_read_time;}


inline float get_last_x_angle() {return last_x_angle;}
inline float get_last_y_angle() {return last_y_angle;}
inline float get_last_z_angle() {return last_z_angle;}
inline float get_last_gyro_x_angle() {return last_gyro_x_angle;}
inline float get_last_gyro_y_angle() {return last_gyro_y_angle;}
inline float get_last_gyro_z_angle() {return last_gyro_z_angle;}

// Use the following global variables and access functions


// to calibrate the acceleration sensor
float base_x_accel;
float base_y_accel;
float base_z_accel;

float base_x_gyro;
float base_y_gyro;
float base_z_gyro;

int read_gyro_accel_vals(uint8_t* accel_t_gyro_ptr) {


// Read the raw values.
// Read 14 bytes at once,
// containing acceleration, temperature and gyro.
// With the default settings of the MPU-6050,
// there is no filter enabled, and the values
// are not very stable. Returns the error value

accel_t_gyro_union* accel_t_gyro = (accel_t_gyro_union *) accel_t_gyro_ptr;

int error = MPU6050_read (MPU6050_ACCEL_XOUT_H, (uint8_t *) accel_t_gyro,


sizeof(*accel_t_gyro));

// Swap all high and low bytes.


// After this, the registers values are swapped,
// so the structure name like x_accel_l does no
// longer contain the lower byte.
uint8_t swap;
#define SWAP(x,y) swap = x; x = y; y = swap

SWAP ((*accel_t_gyro).reg.x_accel_h, (*accel_t_gyro).reg.x_accel_l);


SWAP ((*accel_t_gyro).reg.y_accel_h, (*accel_t_gyro).reg.y_accel_l);
SWAP ((*accel_t_gyro).reg.z_accel_h, (*accel_t_gyro).reg.z_accel_l);
SWAP ((*accel_t_gyro).reg.t_h, (*accel_t_gyro).reg.t_l);
SWAP ((*accel_t_gyro).reg.x_gyro_h, (*accel_t_gyro).reg.x_gyro_l);
SWAP ((*accel_t_gyro).reg.y_gyro_h, (*accel_t_gyro).reg.y_gyro_l);
SWAP ((*accel_t_gyro).reg.z_gyro_h, (*accel_t_gyro).reg.z_gyro_l);

return error;
}

// The sensor should be motionless on a horizontal surface


// while calibration is happening
void calibrate_sensors() {
int num_readings = 10;
float x_accel = 0;
float y_accel = 0;
float z_accel = 0;
float x_gyro = 0;
float y_gyro = 0;
float z_gyro = 0;
accel_t_gyro_union accel_t_gyro;

//Serial.println("Starting Calibration");

// Discard the first set of values read from the IMU


read_gyro_accel_vals((uint8_t *) &accel_t_gyro);

// Read and average the raw values from the IMU


for (int i = 0; i < num_readings; i++) {
read_gyro_accel_vals((uint8_t *) &accel_t_gyro);
x_accel += accel_t_gyro.value.x_accel;
y_accel += accel_t_gyro.value.y_accel;
z_accel += accel_t_gyro.value.z_accel;
x_gyro += accel_t_gyro.value.x_gyro;
y_gyro += accel_t_gyro.value.y_gyro;
z_gyro += accel_t_gyro.value.z_gyro;
delay(100);
}
x_accel /= num_readings;
y_accel /= num_readings;
z_accel /= num_readings;
x_gyro /= num_readings;
y_gyro /= num_readings;
z_gyro /= num_readings;
// Store the raw calibration values globally
base_x_accel = x_accel;
base_y_accel = y_accel;
base_z_accel = z_accel;
base_x_gyro = x_gyro;
base_y_gyro = y_gyro;
base_z_gyro = z_gyro;

//Serial.println("Finishing Calibration");
}

int led30 = 13;

float diffy;
float lasty; //previous "action number"
float y;
float diffx;
float lastx; //previous "action number"
float x;
void setup()
{

pinMode(led30, OUTPUT);

int error;
uint8_t c;

Serial.begin(9600);

Wire.begin();

error = MPU6050_read (MPU6050_WHO_AM_I, &c, 1);

error = MPU6050_read (MPU6050_PWR_MGMT_2, &c, 1);

MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);

calibrate_sensors();
set_last_read_angle_data(millis(), 0, 0, 0, 0, 0, 0);
}
void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()
{

int error;
double dT;
accel_t_gyro_union accel_t_gyro;
error = read_gyro_accel_vals((uint8_t*) &accel_t_gyro);

unsigned long t_now = millis();

float FS_SEL = 131;

float gyro_x = (accel_t_gyro.value.x_gyro - base_x_gyro)/FS_SEL;


float gyro_y = (accel_t_gyro.value.y_gyro - base_y_gyro)/FS_SEL;
float gyro_z = (accel_t_gyro.value.z_gyro - base_z_gyro)/FS_SEL;

float accel_x = accel_t_gyro.value.x_accel;


float accel_y = accel_t_gyro.value.y_accel;
float accel_z = accel_t_gyro.value.z_accel;

float RADIANS_TO_DEGREES = 180/3.14159;

float accel_angle_y = atan(-1*accel_x/sqrt(pow(accel_y,2) +


pow(accel_z,2)))*RADIANS_TO_DEGREES;
float accel_angle_x = atan(accel_y/sqrt(pow(accel_x,2) +
pow(accel_z,2)))*RADIANS_TO_DEGREES;

float accel_angle_z = 0;

float dt =(t_now - get_last_time())/1000.0;


float gyro_angle_x = gyro_x*dt + get_last_x_angle();
float gyro_angle_y = gyro_y*dt + get_last_y_angle();
float gyro_angle_z = gyro_z*dt + get_last_z_angle();

float unfiltered_gyro_angle_x = gyro_x*dt + get_last_gyro_x_angle();


float unfiltered_gyro_angle_y = gyro_y*dt + get_last_gyro_y_angle();
float unfiltered_gyro_angle_z = gyro_z*dt + get_last_gyro_z_angle();

float alpha = 0.96;


float angle_x = alpha*gyro_angle_x + (1.0 - alpha)*accel_angle_x;
float angle_y = alpha*gyro_angle_y + (1.0 - alpha)*accel_angle_y;
float angle_z = gyro_angle_z; //Accelerometer doesn't give z-angle

// Update the saved data with the latest values


set_last_read_angle_data(t_now, angle_x, angle_y, angle_z, unfiltered_gyro_angle_x,
unfiltered_gyro_angle_y, unfiltered_gyro_angle_z);

// Send the data to the serial port


y=abs(accel_angle_y);
diffy = y-lasty;
lasty = y;
x=abs(accel_angle_x);
diffx = x-lastx;
lastx = x;
float a = pow(diffx,2);
float b = pow(diffy,2);
float c = a + b;
float force = sqrt(c);

Serial.print("diffx: ");
Serial.print(abs(diffx));
Serial.print(" diffy: ");
Serial.print(abs(diffy));
Serial.print(" a: ");
Serial.print(a);
Serial.print(" b: ");
Serial.print(b);
Serial.print(" c: ");
Serial.print(c);
Serial.print(" force: ");
Serial.println(force);

if(force > 1.6) //check that the proximity of the first floor is low
//the motor begins and stops when the appropriate floor proximity give the
signal
{
digitalWrite(led30, HIGH);
delay(2000);
}

else {
digitalWrite(led30, LOW);
delay(100);
}
}

int MPU6050_read(int start, uint8_t *buffer, int size)


{
int i, n, error;

Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start);
if (n != 1)
return (-10);

n = Wire.endTransmission(false); // hold the I2C-bus


if (n != 0)
return (n);

// Third parameter is true: relase I2C-bus after data is read.


Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true);
i = 0;
while(Wire.available() && i<size)
{
buffer[i++]=Wire.read();
}
if ( i != size)
return (-11);

return (0); // return : no error


}

int MPU6050_write(int start, const uint8_t *pData, int size)


{
int n, error;

Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start); // write the start address
if (n != 1)
return (-20);

n = Wire.write(pData, size); // write data bytes


if (n != size)
return (-21);

error = Wire.endTransmission(true); // release the I2C-bus


if (error != 0)
return (error);

return (0); // return : no error


}

int MPU6050_write_reg(int reg, uint8_t data)


{
int error;

error = MPU6050_write(reg, &data, 1);

return (error);
}

====================================================================
61. MENGENDALIKAN ARAH DAN LAJU PUTARAN MOTOR DENGAN MPU

Pada protek ini kita akan coba mengaplikasikan MPU6050 dan motor board L293N, yang mana
MPU dengan kemampuan mendeteksi kemiringan untuk mengendalikan arah dan laju DC motor.

//Code by Reichenstein7 (thejamerson.com)

//Keyboard Controls:
//
// 1 -Motor 1 Left
// 2 -Motor 1 Stop
// 3 -Motor 1 Right
//
// 4 -Motor 2 Left
// 5 -Motor 2 Stop
// 6 -Motor 2 Right

// Declare L298N Dual H-Bridge Motor Controller directly since there is not a library to load.

// Motor 1
int dir1PinA = 7;
int dir2PinA = 3;
int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed

// Motor 2
int dir1PinB = 4;
int dir2PinB = 5;
int speedPinB = 10; // Needs to be a PWM pin to be able to control motor speed

//-------------------------MPU--------------------
// MPU-6050 Accelerometer + Gyro
// -----------------------------
//
// By arduino.cc user "Krodal".
// June 2012
// Open Source / Public Domain
//
// Using Arduino 1.0.1
// It will not work with an older version,
// since Wire.endTransmission() uses a parameter
// to hold or release the I2C bus.
//
// Documentation:
// - The InvenSense documents:
// - "MPU-6000 and MPU-6050 Product Specification",
// PS-MPU-6000A.pdf
// - "MPU-6000 and MPU-6050 Register Map and Descriptions",
// RM-MPU-6000A.pdf or RS-MPU-6000A.pdf
// - "MPU-6000/MPU-6050 9-Axis Evaluation Board User Guide"
// AN-MPU-6000EVB.pdf
//
// The accuracy is 16-bits.
//
// Temperature sensor from -40 to +85 degrees Celsius
// 340 per degrees, -512 at 35 degrees.
//
// At power-up, all registers are zero, except these two:
// Register 0x6B (PWR_MGMT_2) = 0x40 (I read zero).
// Register 0x75 (WHO_AM_I) = 0x68.
//
#include <Wire.h>

// The name of the sensor is "MPU-6050".


// For program code, I omit the '-',
// therefor I use the name "MPU6050....".

// Register names according to the datasheet.


// According to the InvenSense document
// "MPU-6000 and MPU-6050 Register Map
// and Descriptions Revision 3.2", there are no registers
// at 0x02 ... 0x18, but according other information
// the registers in that unknown area are for gain
// and offsets.
//
#define MPU6050_AUX_VDDIO 0x01 // R/W
#define MPU6050_SMPLRT_DIV 0x19 // R/W
#define MPU6050_CONFIG 0x1A // R/W
#define MPU6050_GYRO_CONFIG 0x1B // R/W
#define MPU6050_ACCEL_CONFIG 0x1C // R/W
#define MPU6050_FF_THR 0x1D // R/W
#define MPU6050_FF_DUR 0x1E // R/W
#define MPU6050_MOT_THR 0x1F // R/W
#define MPU6050_MOT_DUR 0x20 // R/W
#define MPU6050_ZRMOT_THR 0x21 // R/W
#define MPU6050_ZRMOT_DUR 0x22 // R/W
#define MPU6050_FIFO_EN 0x23 // R/W
#define MPU6050_I2C_MST_CTRL 0x24 // R/W
#define MPU6050_I2C_SLV0_ADDR 0x25 // R/W
#define MPU6050_I2C_SLV0_REG 0x26 // R/W
#define MPU6050_I2C_SLV0_CTRL 0x27 // R/W
#define MPU6050_I2C_SLV1_ADDR 0x28 // R/W
#define MPU6050_I2C_SLV1_REG 0x29 // R/W
#define MPU6050_I2C_SLV1_CTRL 0x2A // R/W
#define MPU6050_I2C_SLV2_ADDR 0x2B // R/W
#define MPU6050_I2C_SLV2_REG 0x2C // R/W
#define MPU6050_I2C_SLV2_CTRL 0x2D // R/W
#define MPU6050_I2C_SLV3_ADDR 0x2E // R/W
#define MPU6050_I2C_SLV3_REG 0x2F // R/W
#define MPU6050_I2C_SLV3_CTRL 0x30 // R/W
#define MPU6050_I2C_SLV4_ADDR 0x31 // R/W
#define MPU6050_I2C_SLV4_REG 0x32 // R/W
#define MPU6050_I2C_SLV4_DO 0x33 // R/W
#define MPU6050_I2C_SLV4_CTRL 0x34 // R/W
#define MPU6050_I2C_SLV4_DI 0x35 // R
#define MPU6050_I2C_MST_STATUS 0x36 // R
#define MPU6050_INT_PIN_CFG 0x37 // R/W
#define MPU6050_INT_ENABLE 0x38 // R/W
#define MPU6050_INT_STATUS 0x3A // R
#define MPU6050_ACCEL_XOUT_H 0x3B // R
#define MPU6050_ACCEL_XOUT_L 0x3C // R
#define MPU6050_ACCEL_YOUT_H 0x3D // R
#define MPU6050_ACCEL_YOUT_L 0x3E // R
#define MPU6050_ACCEL_ZOUT_H 0x3F // R
#define MPU6050_ACCEL_ZOUT_L 0x40 // R
#define MPU6050_TEMP_OUT_H 0x41 // R
#define MPU6050_TEMP_OUT_L 0x42 // R
#define MPU6050_GYRO_XOUT_H 0x43 // R
#define MPU6050_GYRO_XOUT_L 0x44 // R
#define MPU6050_GYRO_YOUT_H 0x45 // R
#define MPU6050_GYRO_YOUT_L 0x46 // R
#define MPU6050_GYRO_ZOUT_H 0x47 // R
#define MPU6050_GYRO_ZOUT_L 0x48 // R
#define MPU6050_EXT_SENS_DATA_00 0x49 // R
#define MPU6050_EXT_SENS_DATA_01 0x4A // R
#define MPU6050_EXT_SENS_DATA_02 0x4B // R
#define MPU6050_EXT_SENS_DATA_03 0x4C // R
#define MPU6050_EXT_SENS_DATA_04 0x4D // R
#define MPU6050_EXT_SENS_DATA_05 0x4E // R
#define MPU6050_EXT_SENS_DATA_06 0x4F // R
#define MPU6050_EXT_SENS_DATA_07 0x50 // R
#define MPU6050_EXT_SENS_DATA_08 0x51 // R
#define MPU6050_EXT_SENS_DATA_09 0x52 // R
#define MPU6050_EXT_SENS_DATA_10 0x53 // R
#define MPU6050_EXT_SENS_DATA_11 0x54 // R
#define MPU6050_EXT_SENS_DATA_12 0x55 // R
#define MPU6050_EXT_SENS_DATA_13 0x56 // R
#define MPU6050_EXT_SENS_DATA_14 0x57 // R
#define MPU6050_EXT_SENS_DATA_15 0x58 // R
#define MPU6050_EXT_SENS_DATA_16 0x59 // R
#define MPU6050_EXT_SENS_DATA_17 0x5A // R
#define MPU6050_EXT_SENS_DATA_18 0x5B // R
#define MPU6050_EXT_SENS_DATA_19 0x5C // R
#define MPU6050_EXT_SENS_DATA_20 0x5D // R
#define MPU6050_EXT_SENS_DATA_21 0x5E // R
#define MPU6050_EXT_SENS_DATA_22 0x5F // R
#define MPU6050_EXT_SENS_DATA_23 0x60 // R
#define MPU6050_MOT_DETECT_STATUS 0x61 // R
#define MPU6050_I2C_SLV0_DO 0x63 // R/W
#define MPU6050_I2C_SLV1_DO 0x64 // R/W
#define MPU6050_I2C_SLV2_DO 0x65 // R/W
#define MPU6050_I2C_SLV3_DO 0x66 // R/W
#define MPU6050_I2C_MST_DELAY_CTRL 0x67 // R/W
#define MPU6050_SIGNAL_PATH_RESET 0x68 // R/W
#define MPU6050_MOT_DETECT_CTRL 0x69 // R/W
#define MPU6050_USER_CTRL 0x6A // R/W
#define MPU6050_PWR_MGMT_1 0x6B // R/W
#define MPU6050_PWR_MGMT_2 0x6C // R/W
#define MPU6050_FIFO_COUNTH 0x72 // R/W
#define MPU6050_FIFO_COUNTL 0x73 // R/W
#define MPU6050_FIFO_R_W 0x74 // R/W
#define MPU6050_WHO_AM_I 0x75 // R
// Defines for the bits, to be able to change
// between bit number and binary definition.
// By using the bit number, programming the sensor
// is like programming the AVR microcontroller.
// But instead of using "(1<<X)", or "_BV(X)",
// the Arduino "bit(X)" is used.
#define MPU6050_D0 0
#define MPU6050_D1 1
#define MPU6050_D2 2
#define MPU6050_D3 3
#define MPU6050_D4 4
#define MPU6050_D5 5
#define MPU6050_D6 6
#define MPU6050_D7 7

// AUX_VDDIO Register
#define MPU6050_AUX_VDDIO MPU6050_D7 // I2C high: 1=VDD, 0=VLOGIC

// CONFIG Register
// DLPF is Digital Low Pass Filter for both gyro and accelerometers.
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_DLPF_CFG0 MPU6050_D0
#define MPU6050_DLPF_CFG1 MPU6050_D1
#define MPU6050_DLPF_CFG2 MPU6050_D2
#define MPU6050_EXT_SYNC_SET0 MPU6050_D3
#define MPU6050_EXT_SYNC_SET1 MPU6050_D4
#define MPU6050_EXT_SYNC_SET2 MPU6050_D5

// Combined definitions for the EXT_SYNC_SET values


#define MPU6050_EXT_SYNC_SET_0 (0)
#define MPU6050_EXT_SYNC_SET_1 (bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_2 (bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_3 (bit(MPU6050_EXT_SYNC_SET1)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_4 (bit(MPU6050_EXT_SYNC_SET2))
#define MPU6050_EXT_SYNC_SET_5 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_6 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_7 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1)|bit(MPU6050_EXT_SYNC_SET0))

// Alternative names for the combined definitions.


#define MPU6050_EXT_SYNC_DISABLED MPU6050_EXT_SYNC_SET_0
#define MPU6050_EXT_SYNC_TEMP_OUT_L MPU6050_EXT_SYNC_SET_1
#define MPU6050_EXT_SYNC_GYRO_XOUT_L MPU6050_EXT_SYNC_SET_2
#define MPU6050_EXT_SYNC_GYRO_YOUT_L MPU6050_EXT_SYNC_SET_3
#define MPU6050_EXT_SYNC_GYRO_ZOUT_L MPU6050_EXT_SYNC_SET_4
#define MPU6050_EXT_SYNC_ACCEL_XOUT_L MPU6050_EXT_SYNC_SET_5
#define MPU6050_EXT_SYNC_ACCEL_YOUT_L MPU6050_EXT_SYNC_SET_6
#define MPU6050_EXT_SYNC_ACCEL_ZOUT_L MPU6050_EXT_SYNC_SET_7

// Combined definitions for the DLPF_CFG values


#define MPU6050_DLPF_CFG_0 (0)
#define MPU6050_DLPF_CFG_1 (bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_2 (bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_3 (bit(MPU6050_DLPF_CFG1)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_4 (bit(MPU6050_DLPF_CFG2))
#define MPU6050_DLPF_CFG_5 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_6 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_7 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1)|
bit(MPU6050_DLPF_CFG0))

// Alternative names for the combined definitions


// This name uses the bandwidth (Hz) for the accelometer,
// for the gyro the bandwidth is almost the same.
#define MPU6050_DLPF_260HZ MPU6050_DLPF_CFG_0
#define MPU6050_DLPF_184HZ MPU6050_DLPF_CFG_1
#define MPU6050_DLPF_94HZ MPU6050_DLPF_CFG_2
#define MPU6050_DLPF_44HZ MPU6050_DLPF_CFG_3
#define MPU6050_DLPF_21HZ MPU6050_DLPF_CFG_4
#define MPU6050_DLPF_10HZ MPU6050_DLPF_CFG_5
#define MPU6050_DLPF_5HZ MPU6050_DLPF_CFG_6
#define MPU6050_DLPF_RESERVED MPU6050_DLPF_CFG_7

// GYRO_CONFIG Register
// The XG_ST, YG_ST, ZG_ST are bits for selftest.
// The FS_SEL sets the range for the gyro.
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_FS_SEL0 MPU6050_D3
#define MPU6050_FS_SEL1 MPU6050_D4
#define MPU6050_ZG_ST MPU6050_D5
#define MPU6050_YG_ST MPU6050_D6
#define MPU6050_XG_ST MPU6050_D7

// Combined definitions for the FS_SEL values


#define MPU6050_FS_SEL_0 (0)
#define MPU6050_FS_SEL_1 (bit(MPU6050_FS_SEL0))
#define MPU6050_FS_SEL_2 (bit(MPU6050_FS_SEL1))
#define MPU6050_FS_SEL_3 (bit(MPU6050_FS_SEL1)|bit(MPU6050_FS_SEL0))

// Alternative names for the combined definitions


// The name uses the range in degrees per second.
#define MPU6050_FS_SEL_250 MPU6050_FS_SEL_0
#define MPU6050_FS_SEL_500 MPU6050_FS_SEL_1
#define MPU6050_FS_SEL_1000 MPU6050_FS_SEL_2
#define MPU6050_FS_SEL_2000 MPU6050_FS_SEL_3

// ACCEL_CONFIG Register
// The XA_ST, YA_ST, ZA_ST are bits for selftest.
// The AFS_SEL sets the range for the accelerometer.
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_ACCEL_HPF0 MPU6050_D0
#define MPU6050_ACCEL_HPF1 MPU6050_D1
#define MPU6050_ACCEL_HPF2 MPU6050_D2
#define MPU6050_AFS_SEL0 MPU6050_D3
#define MPU6050_AFS_SEL1 MPU6050_D4
#define MPU6050_ZA_ST MPU6050_D5
#define MPU6050_YA_ST MPU6050_D6
#define MPU6050_XA_ST MPU6050_D7

// Combined definitions for the ACCEL_HPF values


#define MPU6050_ACCEL_HPF_0 (0)
#define MPU6050_ACCEL_HPF_1 (bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_2 (bit(MPU6050_ACCEL_HPF1))
#define MPU6050_ACCEL_HPF_3 (bit(MPU6050_ACCEL_HPF1)|
bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_4 (bit(MPU6050_ACCEL_HPF2))
#define MPU6050_ACCEL_HPF_7 (bit(MPU6050_ACCEL_HPF2)|
bit(MPU6050_ACCEL_HPF1)|bit(MPU6050_ACCEL_HPF0))

// Alternative names for the combined definitions


// The name uses the Cut-off frequency.
#define MPU6050_ACCEL_HPF_RESET MPU6050_ACCEL_HPF_0
#define MPU6050_ACCEL_HPF_5HZ MPU6050_ACCEL_HPF_1
#define MPU6050_ACCEL_HPF_2_5HZ MPU6050_ACCEL_HPF_2
#define MPU6050_ACCEL_HPF_1_25HZ MPU6050_ACCEL_HPF_3
#define MPU6050_ACCEL_HPF_0_63HZ MPU6050_ACCEL_HPF_4
#define MPU6050_ACCEL_HPF_HOLD MPU6050_ACCEL_HPF_7

// Combined definitions for the AFS_SEL values


#define MPU6050_AFS_SEL_0 (0)
#define MPU6050_AFS_SEL_1 (bit(MPU6050_AFS_SEL0))
#define MPU6050_AFS_SEL_2 (bit(MPU6050_AFS_SEL1))
#define MPU6050_AFS_SEL_3 (bit(MPU6050_AFS_SEL1)|bit(MPU6050_AFS_SEL0))

// Alternative names for the combined definitions


// The name uses the full scale range for the accelerometer.
#define MPU6050_AFS_SEL_2G MPU6050_AFS_SEL_0
#define MPU6050_AFS_SEL_4G MPU6050_AFS_SEL_1
#define MPU6050_AFS_SEL_8G MPU6050_AFS_SEL_2
#define MPU6050_AFS_SEL_16G MPU6050_AFS_SEL_3

// FIFO_EN Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_SLV0_FIFO_EN MPU6050_D0
#define MPU6050_SLV1_FIFO_EN MPU6050_D1
#define MPU6050_SLV2_FIFO_EN MPU6050_D2
#define MPU6050_ACCEL_FIFO_EN MPU6050_D3
#define MPU6050_ZG_FIFO_EN MPU6050_D4
#define MPU6050_YG_FIFO_EN MPU6050_D5
#define MPU6050_XG_FIFO_EN MPU6050_D6
#define MPU6050_TEMP_FIFO_EN MPU6050_D7

// I2C_MST_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_MST_CLK0 MPU6050_D0
#define MPU6050_I2C_MST_CLK1 MPU6050_D1
#define MPU6050_I2C_MST_CLK2 MPU6050_D2
#define MPU6050_I2C_MST_CLK3 MPU6050_D3
#define MPU6050_I2C_MST_P_NSR MPU6050_D4
#define MPU6050_SLV_3_FIFO_EN MPU6050_D5
#define MPU6050_WAIT_FOR_ES MPU6050_D6
#define MPU6050_MULT_MST_EN MPU6050_D7

// Combined definitions for the I2C_MST_CLK


#define MPU6050_I2C_MST_CLK_0 (0)
#define MPU6050_I2C_MST_CLK_1 (bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_2 (bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_3 (bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_4 (bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_5 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_6 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_7 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_8 (bit(MPU6050_I2C_MST_CLK3))
#define MPU6050_I2C_MST_CLK_9 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_10 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_11 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_12 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_13 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_14 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_15 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))

// Alternative names for the combined definitions


// The names uses I2C Master Clock Speed in kHz.
#define MPU6050_I2C_MST_CLK_348KHZ MPU6050_I2C_MST_CLK_0
#define MPU6050_I2C_MST_CLK_333KHZ MPU6050_I2C_MST_CLK_1
#define MPU6050_I2C_MST_CLK_320KHZ MPU6050_I2C_MST_CLK_2
#define MPU6050_I2C_MST_CLK_308KHZ MPU6050_I2C_MST_CLK_3
#define MPU6050_I2C_MST_CLK_296KHZ MPU6050_I2C_MST_CLK_4
#define MPU6050_I2C_MST_CLK_286KHZ MPU6050_I2C_MST_CLK_5
#define MPU6050_I2C_MST_CLK_276KHZ MPU6050_I2C_MST_CLK_6
#define MPU6050_I2C_MST_CLK_267KHZ MPU6050_I2C_MST_CLK_7
#define MPU6050_I2C_MST_CLK_258KHZ MPU6050_I2C_MST_CLK_8
#define MPU6050_I2C_MST_CLK_500KHZ MPU6050_I2C_MST_CLK_9
#define MPU6050_I2C_MST_CLK_471KHZ MPU6050_I2C_MST_CLK_10
#define MPU6050_I2C_MST_CLK_444KHZ MPU6050_I2C_MST_CLK_11
#define MPU6050_I2C_MST_CLK_421KHZ MPU6050_I2C_MST_CLK_12
#define MPU6050_I2C_MST_CLK_400KHZ MPU6050_I2C_MST_CLK_13
#define MPU6050_I2C_MST_CLK_381KHZ MPU6050_I2C_MST_CLK_14
#define MPU6050_I2C_MST_CLK_364KHZ MPU6050_I2C_MST_CLK_15

// I2C_SLV0_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_RW MPU6050_D7

// I2C_SLV0_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV0_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV0_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV0_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV0_GRP MPU6050_D4
#define MPU6050_I2C_SLV0_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV0_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV0_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV0_LEN_MASK 0x0F

// I2C_SLV1_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV1_RW MPU6050_D7

// I2C_SLV1_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV1_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV1_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV1_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV1_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV1_GRP MPU6050_D4
#define MPU6050_I2C_SLV1_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV1_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV1_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV1_LEN_MASK 0x0F
// I2C_SLV2_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV2_RW MPU6050_D7

// I2C_SLV2_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV2_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV2_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV2_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV2_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV2_GRP MPU6050_D4
#define MPU6050_I2C_SLV2_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV2_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV2_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV2_LEN_MASK 0x0F

// I2C_SLV3_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV3_RW MPU6050_D7

// I2C_SLV3_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV3_LEN0 MPU6050_D0
#define MPU6050_I2C_SLV3_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV3_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV3_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV3_GRP MPU6050_D4
#define MPU6050_I2C_SLV3_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV3_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV3_EN MPU6050_D7

// A mask for the length


#define MPU6050_I2C_SLV3_LEN_MASK 0x0F

// I2C_SLV4_ADDR Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV4_RW MPU6050_D7

// I2C_SLV4_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_MST_DLY0 MPU6050_D0
#define MPU6050_I2C_MST_DLY1 MPU6050_D1
#define MPU6050_I2C_MST_DLY2 MPU6050_D2
#define MPU6050_I2C_MST_DLY3 MPU6050_D3
#define MPU6050_I2C_MST_DLY4 MPU6050_D4
#define MPU6050_I2C_SLV4_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV4_INT_EN MPU6050_D6
#define MPU6050_I2C_SLV4_EN MPU6050_D7

// A mask for the delay


#define MPU6050_I2C_MST_DLY_MASK 0x1F

// I2C_MST_STATUS Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_NACK MPU6050_D0
#define MPU6050_I2C_SLV1_NACK MPU6050_D1
#define MPU6050_I2C_SLV2_NACK MPU6050_D2
#define MPU6050_I2C_SLV3_NACK MPU6050_D3
#define MPU6050_I2C_SLV4_NACK MPU6050_D4
#define MPU6050_I2C_LOST_ARB MPU6050_D5
#define MPU6050_I2C_SLV4_DONE MPU6050_D6
#define MPU6050_PASS_THROUGH MPU6050_D7

// I2C_PIN_CFG Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_CLKOUT_EN MPU6050_D0
#define MPU6050_I2C_BYPASS_EN MPU6050_D1
#define MPU6050_FSYNC_INT_EN MPU6050_D2
#define MPU6050_FSYNC_INT_LEVEL MPU6050_D3
#define MPU6050_INT_RD_CLEAR MPU6050_D4
#define MPU6050_LATCH_INT_EN MPU6050_D5
#define MPU6050_INT_OPEN MPU6050_D6
#define MPU6050_INT_LEVEL MPU6050_D7

// INT_ENABLE Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_DATA_RDY_EN MPU6050_D0
#define MPU6050_I2C_MST_INT_EN MPU6050_D3
#define MPU6050_FIFO_OFLOW_EN MPU6050_D4
#define MPU6050_ZMOT_EN MPU6050_D5
#define MPU6050_MOT_EN MPU6050_D6
#define MPU6050_FF_EN MPU6050_D7

// INT_STATUS Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_DATA_RDY_INT MPU6050_D0
#define MPU6050_I2C_MST_INT MPU6050_D3
#define MPU6050_FIFO_OFLOW_INT MPU6050_D4
#define MPU6050_ZMOT_INT MPU6050_D5
#define MPU6050_MOT_INT MPU6050_D6
#define MPU6050_FF_INT MPU6050_D7
// MOT_DETECT_STATUS Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_MOT_ZRMOT MPU6050_D0
#define MPU6050_MOT_ZPOS MPU6050_D2
#define MPU6050_MOT_ZNEG MPU6050_D3
#define MPU6050_MOT_YPOS MPU6050_D4
#define MPU6050_MOT_YNEG MPU6050_D5
#define MPU6050_MOT_XPOS MPU6050_D6
#define MPU6050_MOT_XNEG MPU6050_D7

// IC2_MST_DELAY_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_I2C_SLV0_DLY_EN MPU6050_D0
#define MPU6050_I2C_SLV1_DLY_EN MPU6050_D1
#define MPU6050_I2C_SLV2_DLY_EN MPU6050_D2
#define MPU6050_I2C_SLV3_DLY_EN MPU6050_D3
#define MPU6050_I2C_SLV4_DLY_EN MPU6050_D4
#define MPU6050_DELAY_ES_SHADOW MPU6050_D7

// SIGNAL_PATH_RESET Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_TEMP_RESET MPU6050_D0
#define MPU6050_ACCEL_RESET MPU6050_D1
#define MPU6050_GYRO_RESET MPU6050_D2

// MOT_DETECT_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_MOT_COUNT0 MPU6050_D0
#define MPU6050_MOT_COUNT1 MPU6050_D1
#define MPU6050_FF_COUNT0 MPU6050_D2
#define MPU6050_FF_COUNT1 MPU6050_D3
#define MPU6050_ACCEL_ON_DELAY0 MPU6050_D4
#define MPU6050_ACCEL_ON_DELAY1 MPU6050_D5

// Combined definitions for the MOT_COUNT


#define MPU6050_MOT_COUNT_0 (0)
#define MPU6050_MOT_COUNT_1 (bit(MPU6050_MOT_COUNT0))
#define MPU6050_MOT_COUNT_2 (bit(MPU6050_MOT_COUNT1))
#define MPU6050_MOT_COUNT_3 (bit(MPU6050_MOT_COUNT1)|
bit(MPU6050_MOT_COUNT0))

// Alternative names for the combined definitions


#define MPU6050_MOT_COUNT_RESET MPU6050_MOT_COUNT_0

// Combined definitions for the FF_COUNT


#define MPU6050_FF_COUNT_0 (0)
#define MPU6050_FF_COUNT_1 (bit(MPU6050_FF_COUNT0))
#define MPU6050_FF_COUNT_2 (bit(MPU6050_FF_COUNT1))
#define MPU6050_FF_COUNT_3 (bit(MPU6050_FF_COUNT1)|bit(MPU6050_FF_COUNT0))

// Alternative names for the combined definitions


#define MPU6050_FF_COUNT_RESET MPU6050_FF_COUNT_0

// Combined definitions for the ACCEL_ON_DELAY


#define MPU6050_ACCEL_ON_DELAY_0 (0)
#define MPU6050_ACCEL_ON_DELAY_1 (bit(MPU6050_ACCEL_ON_DELAY0))
#define MPU6050_ACCEL_ON_DELAY_2 (bit(MPU6050_ACCEL_ON_DELAY1))
#define MPU6050_ACCEL_ON_DELAY_3 (bit(MPU6050_ACCEL_ON_DELAY1)|
bit(MPU6050_ACCEL_ON_DELAY0))

// Alternative names for the ACCEL_ON_DELAY


#define MPU6050_ACCEL_ON_DELAY_0MS MPU6050_ACCEL_ON_DELAY_0
#define MPU6050_ACCEL_ON_DELAY_1MS MPU6050_ACCEL_ON_DELAY_1
#define MPU6050_ACCEL_ON_DELAY_2MS MPU6050_ACCEL_ON_DELAY_2
#define MPU6050_ACCEL_ON_DELAY_3MS MPU6050_ACCEL_ON_DELAY_3

// USER_CTRL Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_SIG_COND_RESET MPU6050_D0
#define MPU6050_I2C_MST_RESET MPU6050_D1
#define MPU6050_FIFO_RESET MPU6050_D2
#define MPU6050_I2C_IF_DIS MPU6050_D4 // must be 0 for MPU-6050
#define MPU6050_I2C_MST_EN MPU6050_D5
#define MPU6050_FIFO_EN MPU6050_D6

// PWR_MGMT_1 Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_CLKSEL0 MPU6050_D0
#define MPU6050_CLKSEL1 MPU6050_D1
#define MPU6050_CLKSEL2 MPU6050_D2
#define MPU6050_TEMP_DIS MPU6050_D3 // 1: disable temperature sensor
#define MPU6050_CYCLE MPU6050_D5 // 1: sample and sleep
#define MPU6050_SLEEP MPU6050_D6 // 1: sleep mode
#define MPU6050_DEVICE_RESET MPU6050_D7 // 1: reset to default values

// Combined definitions for the CLKSEL


#define MPU6050_CLKSEL_0 (0)
#define MPU6050_CLKSEL_1 (bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_2 (bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_3 (bit(MPU6050_CLKSEL1)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_4 (bit(MPU6050_CLKSEL2))
#define MPU6050_CLKSEL_5 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_6 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_7 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1)|
bit(MPU6050_CLKSEL0))

// Alternative names for the combined definitions


#define MPU6050_CLKSEL_INTERNAL MPU6050_CLKSEL_0
#define MPU6050_CLKSEL_X MPU6050_CLKSEL_1
#define MPU6050_CLKSEL_Y MPU6050_CLKSEL_2
#define MPU6050_CLKSEL_Z MPU6050_CLKSEL_3
#define MPU6050_CLKSEL_EXT_32KHZ MPU6050_CLKSEL_4
#define MPU6050_CLKSEL_EXT_19_2MHZ MPU6050_CLKSEL_5
#define MPU6050_CLKSEL_RESERVED MPU6050_CLKSEL_6
#define MPU6050_CLKSEL_STOP MPU6050_CLKSEL_7

// PWR_MGMT_2 Register
// These are the names for the bits.
// Use these only with the bit() macro.
#define MPU6050_STBY_ZG MPU6050_D0
#define MPU6050_STBY_YG MPU6050_D1
#define MPU6050_STBY_XG MPU6050_D2
#define MPU6050_STBY_ZA MPU6050_D3
#define MPU6050_STBY_YA MPU6050_D4
#define MPU6050_STBY_XA MPU6050_D5
#define MPU6050_LP_WAKE_CTRL0 MPU6050_D6
#define MPU6050_LP_WAKE_CTRL1 MPU6050_D7

// Combined definitions for the LP_WAKE_CTRL


#define MPU6050_LP_WAKE_CTRL_0 (0)
#define MPU6050_LP_WAKE_CTRL_1 (bit(MPU6050_LP_WAKE_CTRL0))
#define MPU6050_LP_WAKE_CTRL_2 (bit(MPU6050_LP_WAKE_CTRL1))
#define MPU6050_LP_WAKE_CTRL_3 (bit(MPU6050_LP_WAKE_CTRL1)|
bit(MPU6050_LP_WAKE_CTRL0))

// Alternative names for the combined definitions


// The names uses the Wake-up Frequency.
#define MPU6050_LP_WAKE_1_25HZ MPU6050_LP_WAKE_CTRL_0
#define MPU6050_LP_WAKE_2_5HZ MPU6050_LP_WAKE_CTRL_1
#define MPU6050_LP_WAKE_5HZ MPU6050_LP_WAKE_CTRL_2
#define MPU6050_LP_WAKE_10HZ MPU6050_LP_WAKE_CTRL_3

// Default I2C address for the MPU-6050 is 0x68.


// But only if the AD0 pin is low.
// Some sensor boards have AD0 high, and the
// I2C address thus becomes 0x69.
#define MPU6050_I2C_ADDRESS 0x68

// Declaring an union for the registers and the axis values.


// The byte order does not match the byte order of
// the compiler and AVR chip.
// The AVR chip (on the Arduino board) has the Low Byte
// at the lower address.
// But the MPU-6050 has a different order: High Byte at
// lower address, so that has to be corrected.
// The register part "reg" is only used internally,
// and are swapped in code.
typedef union accel_t_gyro_union
{
struct
{
uint8_t x_accel_h;
uint8_t x_accel_l;
uint8_t y_accel_h;
uint8_t y_accel_l;
uint8_t z_accel_h;
uint8_t z_accel_l;
uint8_t t_h;
uint8_t t_l;
uint8_t x_gyro_h;
uint8_t x_gyro_l;
uint8_t y_gyro_h;
uint8_t y_gyro_l;
uint8_t z_gyro_h;
uint8_t z_gyro_l;
} reg;
struct
{
int x_accel;
int y_accel;
int z_accel;
int temperature;
int x_gyro;
int y_gyro;
int z_gyro;
} value;
};

// Use the following global variables and access functions to help store the overall
// rotation angle of the sensor
unsigned long last_read_time;
float last_x_angle; // These are the filtered angles
float last_y_angle;
float last_z_angle;
float last_gyro_x_angle; // Store the gyro angles to compare drift
float last_gyro_y_angle;
float last_gyro_z_angle;

void set_last_read_angle_data(unsigned long time, float x, float y, float z, float x_gyro, float
y_gyro, float z_gyro) {
last_read_time = time;
last_x_angle = x;
last_y_angle = y;
last_z_angle = z;
last_gyro_x_angle = x_gyro;
last_gyro_y_angle = y_gyro;
last_gyro_z_angle = z_gyro;
}

inline unsigned long get_last_time() {return last_read_time;}


inline float get_last_x_angle() {return last_x_angle;}
inline float get_last_y_angle() {return last_y_angle;}
inline float get_last_z_angle() {return last_z_angle;}
inline float get_last_gyro_x_angle() {return last_gyro_x_angle;}
inline float get_last_gyro_y_angle() {return last_gyro_y_angle;}
inline float get_last_gyro_z_angle() {return last_gyro_z_angle;}

// Use the following global variables and access functions


// to calibrate the acceleration sensor
float base_x_accel;
float base_y_accel;
float base_z_accel;

float base_x_gyro;
float base_y_gyro;
float base_z_gyro;

int read_gyro_accel_vals(uint8_t* accel_t_gyro_ptr) {


// Read the raw values.
// Read 14 bytes at once,
// containing acceleration, temperature and gyro.
// With the default settings of the MPU-6050,
// there is no filter enabled, and the values
// are not very stable. Returns the error value

accel_t_gyro_union* accel_t_gyro = (accel_t_gyro_union *) accel_t_gyro_ptr;

int error = MPU6050_read (MPU6050_ACCEL_XOUT_H, (uint8_t *) accel_t_gyro,


sizeof(*accel_t_gyro));

// Swap all high and low bytes.


// After this, the registers values are swapped,
// so the structure name like x_accel_l does no
// longer contain the lower byte.
uint8_t swap;
#define SWAP(x,y) swap = x; x = y; y = swap

SWAP ((*accel_t_gyro).reg.x_accel_h, (*accel_t_gyro).reg.x_accel_l);


SWAP ((*accel_t_gyro).reg.y_accel_h, (*accel_t_gyro).reg.y_accel_l);
SWAP ((*accel_t_gyro).reg.z_accel_h, (*accel_t_gyro).reg.z_accel_l);
SWAP ((*accel_t_gyro).reg.t_h, (*accel_t_gyro).reg.t_l);
SWAP ((*accel_t_gyro).reg.x_gyro_h, (*accel_t_gyro).reg.x_gyro_l);
SWAP ((*accel_t_gyro).reg.y_gyro_h, (*accel_t_gyro).reg.y_gyro_l);
SWAP ((*accel_t_gyro).reg.z_gyro_h, (*accel_t_gyro).reg.z_gyro_l);

return error;
}

// The sensor should be motionless on a horizontal surface


// while calibration is happening
void calibrate_sensors() {
int num_readings = 10;
float x_accel = 0;
float y_accel = 0;
float z_accel = 0;
float x_gyro = 0;
float y_gyro = 0;
float z_gyro = 0;
accel_t_gyro_union accel_t_gyro;

//Serial.println("Starting Calibration");

// Discard the first set of values read from the IMU


read_gyro_accel_vals((uint8_t *) &accel_t_gyro);

// Read and average the raw values from the IMU


for (int i = 0; i < num_readings; i++) {
read_gyro_accel_vals((uint8_t *) &accel_t_gyro);
x_accel += accel_t_gyro.value.x_accel;
y_accel += accel_t_gyro.value.y_accel;
z_accel += accel_t_gyro.value.z_accel;
x_gyro += accel_t_gyro.value.x_gyro;
y_gyro += accel_t_gyro.value.y_gyro;
z_gyro += accel_t_gyro.value.z_gyro;
delay(100);
}
x_accel /= num_readings;
y_accel /= num_readings;
z_accel /= num_readings;
x_gyro /= num_readings;
y_gyro /= num_readings;
z_gyro /= num_readings;

// Store the raw calibration values globally


base_x_accel = x_accel;
base_y_accel = y_accel;
base_z_accel = z_accel;
base_x_gyro = x_gyro;
base_y_gyro = y_gyro;
base_z_gyro = z_gyro;

//Serial.println("Finishing Calibration");
}

//-------------------------MPU---------------------

void setup() { // Setup runs once per reset


// initialize serial communication @ 9600 baud:
Serial.begin(9600);
//------------------------MPU---------------
int error;
uint8_t c;
//Serial.begin(9600);
/*
Serial.println(F("InvenSense MPU-6050"));
Serial.println(F("June 2012"));
*/
// Initialize the 'Wire' class for the I2C-bus.
Wire.begin();

// default at power-up:
// Gyro at 250 degrees second
// Acceleration at 2g
// Clock source at internal 8MHz
// The device is in sleep mode.
//

error = MPU6050_read (MPU6050_WHO_AM_I, &c, 1);


/*
Serial.print(F("WHO_AM_I : "));
Serial.print(c,HEX);
Serial.print(F(", error = "));
Serial.println(error,DEC);
*/

// According to the datasheet, the 'sleep' bit


// should read a '1'. But I read a '0'.
// That bit has to be cleared, since the sensor
// is in sleep mode at power-up. Even if the
// bit reads '0'.
error = MPU6050_read (MPU6050_PWR_MGMT_2, &c, 1);
/*
Serial.print(F("PWR_MGMT_2 : "));
Serial.print(c,HEX);
Serial.print(F(", error = "));
Serial.println(error,DEC);
*/

// Clear the 'sleep' bit to start the sensor.


MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);

//Initialize the angles


calibrate_sensors();
set_last_read_angle_data(millis(), 0, 0, 0, 0, 0, 0);
//--------------------------MPU-------------------
//Define L298N Dual H-Bridge Motor Controller Pins

pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
pinMode(dir1PinB,OUTPUT);
pinMode(dir2PinB,OUTPUT);
pinMode(speedPinB,OUTPUT);

//----------------------MPU-----------------
void(* resetFunc) (void) = 0; //declare reset function @ address 0
//----------------------MPU-------------------

void loop() {

//------------------------MPU--------------------------

int error;
double dT;
accel_t_gyro_union accel_t_gyro;

/*
Serial.println(F(""));
Serial.println(F("MPU-6050"));
*/

// Read the raw values.


error = read_gyro_accel_vals((uint8_t*) &accel_t_gyro);

// Get the time of reading for rotation computations


unsigned long t_now = millis();

/*
Serial.print(F("Read accel, temp and gyro, error = "));
Serial.println(error,DEC);

// Print the raw acceleration values


Serial.print(F("accel x,y,z: "));
Serial.print(accel_t_gyro.value.x_accel, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.y_accel, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.z_accel, DEC);
Serial.println(F(""));
*/

// The temperature sensor is -40 to +85 degrees Celsius.


// It is a signed integer.
// According to the datasheet:
// 340 per degrees Celsius, -512 at 35 degrees.
// At 0 degrees: -512 - (340 * 35) = -12412
/*
Serial.print(F("temperature: "));
dT = ( (double) accel_t_gyro.value.temperature + 12412.0) / 340.0;
Serial.print(dT, 3);
Serial.print(F(" degrees Celsius"));
Serial.println(F(""));

// Print the raw gyro values.


Serial.print(F("raw gyro x,y,z : "));
Serial.print(accel_t_gyro.value.x_gyro, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.y_gyro, DEC);
Serial.print(F(", "));
Serial.print(accel_t_gyro.value.z_gyro, DEC);
Serial.print(F(", "));
Serial.println(F(""));
*/

// Convert gyro values to degrees/sec


float FS_SEL = 131;
/*
float gyro_x = (accel_t_gyro.value.x_gyro - base_x_gyro)/FS_SEL;
float gyro_y = (accel_t_gyro.value.y_gyro - base_y_gyro)/FS_SEL;
float gyro_z = (accel_t_gyro.value.z_gyro - base_z_gyro)/FS_SEL;
*/
float gyro_x = (accel_t_gyro.value.x_gyro - base_x_gyro)/FS_SEL;
float gyro_y = (accel_t_gyro.value.y_gyro - base_y_gyro)/FS_SEL;
float gyro_z = (accel_t_gyro.value.z_gyro - base_z_gyro)/FS_SEL;

// Get raw acceleration values


//float G_CONVERT = 16384;
float accel_x = accel_t_gyro.value.x_accel;
float accel_y = accel_t_gyro.value.y_accel;
float accel_z = accel_t_gyro.value.z_accel;

// Get angle values from accelerometer


float RADIANS_TO_DEGREES = 180/3.14159;
// float accel_vector_length = sqrt(pow(accel_x,2) + pow(accel_y,2) + pow(accel_z,2));
float accel_angle_y = atan(-1*accel_x/sqrt(pow(accel_y,2) +
pow(accel_z,2)))*RADIANS_TO_DEGREES;
float accel_angle_x = atan(accel_y/sqrt(pow(accel_x,2) +
pow(accel_z,2)))*RADIANS_TO_DEGREES;

float accel_angle_z = 0;

// Compute the (filtered) gyro angles


float dt =(t_now - get_last_time())/1000.0;
float gyro_angle_x = gyro_x*dt + get_last_x_angle();
float gyro_angle_y = gyro_y*dt + get_last_y_angle();
float gyro_angle_z = gyro_z*dt + get_last_z_angle();

// Compute the drifting gyro angles


float unfiltered_gyro_angle_x = gyro_x*dt + get_last_gyro_x_angle();
float unfiltered_gyro_angle_y = gyro_y*dt + get_last_gyro_y_angle();
float unfiltered_gyro_angle_z = gyro_z*dt + get_last_gyro_z_angle();
// Apply the complementary filter to figure out the change in angle - choice of alpha is
// estimated now. Alpha depends on the sampling rate...
float alpha = 0.96;
float angle_x = alpha*gyro_angle_x + (1.0 - alpha)*accel_angle_x;
float angle_y = alpha*gyro_angle_y + (1.0 - alpha)*accel_angle_y;
float angle_z = gyro_angle_z; //Accelerometer doesn't give z-angle

// Update the saved data with the latest values


set_last_read_angle_data(t_now, angle_x, angle_y, angle_z, unfiltered_gyro_angle_x,
unfiltered_gyro_angle_y, unfiltered_gyro_angle_z);

// Send the data to the serial port


Serial.print(F("DEL:")); //Delta T
Serial.print(dt, DEC);
Serial.print(F(" #ACC:")); //Accelerometer angle
Serial.print(accel_angle_x, 2);
Serial.print(F(","));
Serial.print(accel_angle_y, 2);
Serial.print(F(","));
Serial.print(accel_angle_z, 2);
Serial.print(F(" #GYR:"));
Serial.print(unfiltered_gyro_angle_x, 2); //Gyroscope angle
Serial.print(F(","));
Serial.print(unfiltered_gyro_angle_y, 2);
Serial.print(F(","));
Serial.print(unfiltered_gyro_angle_z, 2);
Serial.print(F(" #FIL:")); //Filtered angle
Serial.print(angle_x, 2);
Serial.print(F(","));
Serial.print(angle_y, 2);
Serial.print(F(","));
Serial.print(angle_z, 2);
Serial.println(F(""));

//------------------------MPU-------------------------------------
//int a= (abs(angle_y))*1.56+80;
int a= map(abs(angle_y), 0, 45, 50, 255); // speed control on various slope
if (angle_y > 0) {
analogWrite(speedPinA, a);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
analogWrite(speedPinB, a);
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);

}
if (angle_y < 0) {
analogWrite(speedPinA, a);
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, a);
digitalWrite(dir1PinB, HIGH);
digitalWrite(dir2PinB, LOW);

/*

void maju(){
analogWrite(speedPinA, 100);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
analogWrite(speedPinB, 100);
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
}
void mundur(){
analogWrite(speedPinA, 100);
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, 100);
digitalWrite(dir1PinB, HIGH);
digitalWrite(dir2PinB, LOW);
}
void kanan(){
analogWrite(speedPinA, 80);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
analogWrite(speedPinB, 80);
digitalWrite(dir1PinB, HIGH);
digitalWrite(dir2PinB, LOW);
}
void kiri(){
analogWrite(speedPinA, 80);
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, 80);
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
}
void henti(){
analogWrite(speedPinA, 0);
analogWrite(speedPinB, 0);
}
*/
//----------------------MPU------------------
int MPU6050_read(int start, uint8_t *buffer, int size)
{
int i, n, error;
Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start);
if (n != 1)
return (-10);

n = Wire.endTransmission(false); // hold the I2C-bus


if (n != 0)
return (n);

// Third parameter is true: relase I2C-bus after data is read.


Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true);
i = 0;
while(Wire.available() && i<size)
{
buffer[i++]=Wire.read();
}
if ( i != size)
return (-11);

return (0); // return : no error


}

// --------------------------------------------------------
// MPU6050_write
//
// This is a common function to write multiple bytes to an I2C device.
//
// If only a single register is written,
// use the function MPU_6050_write_reg().
//
// Parameters:
// start : Start address, use a define for the register
// pData : A pointer to the data to write.
// size : The number of bytes to write.
//
// If only a single register is written, a pointer
// to the data has to be used, and the size is
// a single byte:
// int data = 0; // the data to write
// MPU6050_write (MPU6050_PWR_MGMT_1, &c, 1);
//
int MPU6050_write(int start, const uint8_t *pData, int size)
{
int n, error;

Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start); // write the start address
if (n != 1)
return (-20);

n = Wire.write(pData, size); // write data bytes


if (n != size)
return (-21);

error = Wire.endTransmission(true); // release the I2C-bus


if (error != 0)
return (error);

return (0); // return : no error


}

// --------------------------------------------------------
// MPU6050_write_reg
//
// An extra function to write a single register.
// It is just a wrapper around the MPU_6050_write()
// function, and it is only a convenient function
// to make it easier to write a single register.
//
int MPU6050_write_reg(int reg, uint8_t data)
{
int error;

error = MPU6050_write(reg, &data, 1);

return (error);
}

//-----------------------MPU-------------------

=============================================================
62. CONTINOUS SERVO MOTOR

#include <ContinuousServo.h>

ContinuousServo servo(10);

void setup()
{

}
void loop()
{

servo.step(65);//140 for 180deg, 70 for 90deg


delay(2000);
servo.step(1.5);//stop
delay(1000);
servo.step(100);//full speed
delay(2000);
servo.step(-100);//counterclockwise
delay(2000);

}
#include <ContinuousServo.h>

// Initialize ContinuousServo library with servo signal wire connected to pin 10


ContinuousServo servo(10);

void setup()
{
Serial.begin(9600);

// Step 50 steps forward, then output steps


servo.step(100, stepDone);
}

void stepDone()
{
Serial.print(F("Servo completed. Now at "));
Serial.print(servo.getSteps());
Serial.println(F(" steps."));
}

// Do nothing in loop
void loop()
{
}

#include <ContinuousServo.h>

ContinuousServo servo(10);

void setup()
{
Serial.begin(9600);
}

void loop()
{

servo.step(100, stepDone);
delay(5000);
servo.step(-100, stepDone);
delay(5000);

}
void stepDone()
{
Serial.print(F("Servo completed. Now at "));
Serial.print(servo.getSteps());
Serial.println(F(" steps."));
}

===============================================================
#include <ContinuousServo.h>

// Use this to try to get the steps forward and backwards to match
ContinuousServo servo(10, 564, 1733);

int steps = 250;


int step = 0;
boolean fwd = true;

void setup()
{
Serial.begin(9600);

servo.step(steps, doneStepping);
}

void loop()
{
if (step != 0)
{
delay(2000);
servo.step(step, doneStepping);
step = 0;
}
}

void doneStepping()
{
Serial.println(F("Done stepping, switching direction"));

fwd = !fwd;
step = fwd ? steps : -steps;
}

---------------------------------------------------------------------------------------------------

// http://www.bajdi.com
// Rotating a continuous servo (tested with a SpringRC SM-S4306R)

#include <Servo.h>

Servo myservo; // create servo object to control a servo

void setup()
{
myservo.attach(10); // attaches the servo on pin 9 to the servo object
}

void loop()
{
myservo.write(45); // rotate counterclockwise full speed
delay(2000);
myservo.write(90); // stop
delay(100);
myservo.write(135); // rotate clockwise full speed
delay(2000);
myservo.write(90); // stop
delay(100);
myservo.write(80); // rotate very slowly counterclockwise
delay(2000);
myservo.write(90); // stop
delay(100);
myservo.write(100); // rotate very slowly clockwise
delay(2000);
}

=======================================================

#include <ContinuousServo.h>

ContinuousServo servo1(2);
ContinuousServo servo2(10);
void setup()
{

}
void loop()
{

servo1.step(65);//140 for 180deg, 70 for 90deg


servo2.step(-65);
delay(2000);
servo1.step(1.5);//stop
servo2.step(1.5);//stop
delay(1000);
servo1.step(100);//full speed
servo2.step(-100);//full speed
delay(2000);
servo1.step(1.5);//stop
servo2.step(1.5);//stop
delay(1000);
servo1.step(-100);//counterclockwise
servo2.step(100);//counterclockwise
delay(2000);

======================================================
// http://www.bajdi.com
// Rotating a continuous servo (tested with a SpringRC SM-S4306R)

#include <Servo.h>

Servo myservo1; // create servo object to control a servo


Servo myservo2;

void setup()
{
myservo1.attach(10); // attaches the servo on pin 9 to the servo object
myservo2.attach(2);

void loop()
{

myservo1.write(45); // rotate counterclockwise full speed


myservo2.write(135);
delay(2000);
myservo1.write(90); // stop
myservo2.write(90);
delay(100);
myservo1.write(135); // rotate clockwise full speed
myservo2.write(45);
delay(2000);
myservo1.write(90); // stop
myservo2.write(90);
delay(100);
myservo1.write(80); // rotate very slowly counterclockwise
myservo2.write(100);
delay(2000);
myservo1.write(90); // stop
myservo2.write(90);
delay(100);
myservo1.write(80); // rotate very slowly clockwise
myservo2.write(100);
delay(2000);

==================================================================
63. RF CONTROL 433 MHz

Transmitter sket

//simple Tx on pin D12


//Written By : Mohannad Rawashdeh
// 3:00pm , 13/6/2013
//http://www.genotronex.com/
//..................................
#include <VirtualWire.h>
char *controller;
void setup() {
pinMode(13,OUTPUT);
vw_set_ptt_inverted(true); //
vw_set_tx_pin(12);
vw_setup(4000);// speed of data transfer Kbps
}

void loop(){
controller="1";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,1);
delay(2000);
controller="0";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,0);
delay(2000);

Receiver sket

//simple Tx on pin D12


//Written By : Mohannad Rawashdeh
// 3:00pm , 13/6/2013
//http://www.genotronex.com/
//..................................
#include <VirtualWire.h>
void setup()
{
vw_set_ptt_inverted(true); // Required for DR3100
vw_set_rx_pin(12);
vw_setup(4000); // Bits per sec
pinMode(13, OUTPUT);

vw_rx_start(); // Start the receiver PLL running


}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

if (vw_get_message(buf, &buflen)) // Non-blocking


{
if(buf[0]=='1'){

digitalWrite(13,1);
}
if(buf[0]=='0'){
digitalWrite(13,0);
}

}
}

Receiver as Counter

//simple Tx on pin D12


//Written By : Mohannad Rawashdeh
// 3:00pm , 13/6/2013
//http://www.genotronex.com/
//..................................
#include <VirtualWire.h>
int Counter = 0;
void setup()
{
Serial.begin(9600);
vw_set_ptt_inverted(true); // Required for DR3100
vw_set_rx_pin(12);
vw_setup(4000); // Bits per sec
pinMode(13, OUTPUT);

vw_rx_start(); // Start the receiver PLL running


}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

if (vw_get_message(buf, &buflen)) // Non-blocking


{
if(buf[0]=='1'){

digitalWrite(13,1);
Counter++;
Serial.println(Counter);
}
if(buf[0]=='0'){
digitalWrite(13,0);
Serial.println("OFF");
}

}
}

---------------------------------------------------------------------------------------------------
Transmitter

#include <VirtualWire.h>

const int led_pin = 13;


const int transmit_pin = 12;
//const int receive_pin = 2;
//const int transmit_en_pin = 3;

void setup()
{
// Initialise the IO and ISR
vw_set_tx_pin(transmit_pin);
//vw_set_rx_pin(receive_pin);
//vw_set_ptt_pin(transmit_en_pin);
vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(2000); // Bits per sec
}

byte count = 1;

void loop()
{
char msg[7] = {'h','e','l','l','o',' ','#'};

msg[6] = count;
digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
vw_send((uint8_t *)msg, 7);
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(led_pin, LOW);
delay(1000);
count = count + 1;
}

Receiver

#include <VirtualWire.h>

const int led_pin = 13;


//const int transmit_pin = 12;
const int receive_pin = 12;
//const int transmit_en_pin = 3;

void setup()
{
delay(1000);
Serial.begin(9600); // Debugging only
Serial.println("setup");

// Initialise the IO and ISR


//vw_set_tx_pin(transmit_pin);
vw_set_rx_pin(receive_pin);
//vw_set_ptt_pin(transmit_en_pin);
vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(2000); // Bits per sec

vw_rx_start(); // Start the receiver PLL running


}

void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

if (vw_get_message(buf, &buflen)) // Non-blocking


{
int i;
digitalWrite(led_pin, HIGH); // Flash a light to show received good message
// Message with a good checksum received, print it.
Serial.print("Got: ");

for (i = 0; i < buflen; i++)


{
Serial.print(buf[i], HEX);
Serial.print(' ');
}
Serial.println();
digitalWrite(led_pin, LOW);
}
}
64. RF RC-SWITCH

Trasmitter

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
mySwitch.enableTransmit(12); // Using Pin #12
}

void loop() {
mySwitch.send("10000100011000000000010100");
delay(1000);
}

Receiver

/*
Simple example for receiving

http://code.google.com/p/rc-switch/

Need help? http://forum.ardumote.com


*/
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
Serial.begin(9600);
mySwitch.enableReceive(0); // Receiver on inerrupt 0 => that is pin #2
}

void loop() {
if (mySwitch.available()) {

int value = mySwitch.getReceivedValue();

if (value == 0) {
Serial.print("Unknown encoding");
} else {
Serial.print("Received ");
Serial.print( mySwitch.getReceivedValue() ); //decimal number
Serial.print(" / ");
Serial.print( mySwitch.getReceivedBitlength() );
Serial.print("bit ");
Serial.print("Protocol: ");
Serial.println( mySwitch.getReceivedProtocol() );
}

mySwitch.resetAvailable();
}
}

==============================================================
65. KONTROL RF DENGAN KEYBOARD

Ini adalah dasar sebagai panduan jika Anda akan mengontrol switch jarak jauh dengan bantuan RF
module by keyboard serial.

Receiver

//simple Tx on pin D12


//Written By : Mohannad Rawashdeh
//Modified by : Triantara
// 3:00pm , 13/6/2013
//http://www.genotronex.com/
//..................................
#include <VirtualWire.h>
void setup()
{
vw_set_ptt_inverted(true); // Required for DR3100
vw_set_rx_pin(12);
vw_setup(4000); // Bits per sec
pinMode(13, OUTPUT);

vw_rx_start(); // Start the receiver PLL running


}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
if(buf[0]=='1'){

digitalWrite(13,1);
}
if(buf[0]=='2'){
digitalWrite(13,0);
}
if(buf[0]=='3'){

digitalWrite(13,1);
}
if(buf[0]=='4'){
digitalWrite(13,0);
}
if(buf[0]=='5'){

digitalWrite(13,1);
}
if(buf[0]=='6'){
digitalWrite(13,0);
}

}
}

Transmitter

//simple Tx on pin D12


//Written By : Mohannad Rawashdeh
//Modified by : Triantara
// 3:00pm , 13/6/2013
//http://www.genotronex.com/
//..................................
#include <VirtualWire.h>
char *controller;
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
vw_set_ptt_inverted(true); //
vw_set_tx_pin(12);
vw_setup(4000);// speed of data transfer Kbps
}
/*
void loop(){
controller="1";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,1);
delay(2000);
controller="0";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,0);
delay(2000);

}
*/
//-------------------------------------------------

void loop() {

// Initialize the Serial interface:

if (Serial.available() > 0) {
int inByte = Serial.read();
int speed; // Local variable

switch (inByte) {

case '1':
controller="1";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,1);
//delay(2000);
break;

case '2':
controller="2";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,0);
//delay(2000);
break;

case '3':
controller="3";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,1);
//delay(2000);
break;

case '4':
controller="4";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,0);
//delay(2000);
break;

case '5':
controller="5";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,1);
//delay(2000);
break;

case '6':
controller="6";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,0);
//delay(2000);
break;

default:
// turn all the connections off if an unmapped key is pressed:
for (int thisPin = 2; thisPin < 11; thisPin++) {
digitalWrite(thisPin, LOW);
}
}
}
}

//-----------------------------------------------------------------

===============================================================
66. ACCELEROMETER MMA7455

Dengan akselerometer ini kita dapat mengukur sudut kemiringan dengan memanfaatkan percepatan
gravitasi sebagai acuan. Ada beberapa sket yang dapat kita pakai.

// MMA7455 Accelerometer
// ---------------------
//
// By arduino.cc user "Krodal".
// May 2012
// Open Source / Public Domain
//
// Fixes to union and type conversions by Arduino.cc user "Afroviking"
// August 2014
//
// Using Arduino 1.0.1
// It will not work with an older version, since Wire.endTransmission()
// uses a parameter to hold or release the I2C bus.
//
// Documentation:
// - The Freescale MMA7455L datasheet
// - The AN3468 Application Note (programming).
// - The AN3728 Application Note (calibrating offset).
//
// The MMA7455 can be used by writing and reading a single byte,
// but it is also capable to read and write multiple bytes.
//
// The accuracy is 10-bits.
//

#include <Wire.h>

// Register names according to the datasheet.


// Register 0x1C is sometimes called 'PW', and sometimes 'PD'.
// The two reserved registers can not be used.
#define MMA7455_XOUTL 0x00 // Read only, Output Value X LSB
#define MMA7455_XOUTH 0x01 // Read only, Output Value X MSB
#define MMA7455_YOUTL 0x02 // Read only, Output Value Y LSB
#define MMA7455_YOUTH 0x03 // Read only, Output Value Y MSB
#define MMA7455_ZOUTL 0x04 // Read only, Output Value Z LSB
#define MMA7455_ZOUTH 0x05 // Read only, Output Value Z MSB
#define MMA7455_XOUT8 0x06 // Read only, Output Value X 8 bits
#define MMA7455_YOUT8 0x07 // Read only, Output Value Y 8 bits
#define MMA7455_ZOUT8 0x08 // Read only, Output Value Z 8 bits
#define MMA7455_STATUS 0x09 // Read only, Status Register
#define MMA7455_DETSRC 0x0A // Read only, Detection Source Register
#define MMA7455_TOUT 0x0B // Temperature Output Value (Optional)
#define MMA7455_RESERVED1 0x0C // Reserved
#define MMA7455_I2CAD 0x0D // Read/Write, I2C Device Address
#define MMA7455_USRINF 0x0E // Read only, User Information (Optional)
#define MMA7455_WHOAMI 0x0F // Read only, "Who am I" value (Optional)
#define MMA7455_XOFFL 0x10 // Read/Write, Offset Drift X LSB
#define MMA7455_XOFFH 0x11 // Read/Write, Offset Drift X MSB
#define MMA7455_YOFFL 0x12 // Read/Write, Offset Drift Y LSB
#define MMA7455_YOFFH 0x13 // Read/Write, Offset Drift Y MSB
#define MMA7455_ZOFFL 0x14 // Read/Write, Offset Drift Z LSB
#define MMA7455_ZOFFH 0x15 // Read/Write, Offset Drift Z MSB
#define MMA7455_MCTL 0x16 // Read/Write, Mode Control Register
#define MMA7455_INTRST 0x17 // Read/Write, Interrupt Latch Reset
#define MMA7455_CTL1 0x18 // Read/Write, Control 1 Register
#define MMA7455_CTL2 0x19 // Read/Write, Control 2 Register
#define MMA7455_LDTH 0x1A // Read/Write, Level Detection Threshold Limit Value
#define MMA7455_PDTH 0x1B // Read/Write, Pulse Detection Threshold Limit Value
#define MMA7455_PD 0x1C // Read/Write, Pulse Duration Value
#define MMA7455_LT 0x1D // Read/Write, Latency Time Value (between pulses)
#define MMA7455_TW 0x1E // Read/Write, Time Window for Second Pulse Value
#define MMA7455_RESERVED2 0x1F // Reserved

// Defines for the bits, to be able to change


// between bit number and binary definition.
// By using the bit number, programming the MMA7455
// is like programming an AVR microcontroller.
// But instead of using "(1<<X)", or "_BV(X)",
// the Arduino "bit(X)" is used.
#define MMA7455_D0 0
#define MMA7455_D1 1
#define MMA7455_D2 2
#define MMA7455_D3 3
#define MMA7455_D4 4
#define MMA7455_D5 5
#define MMA7455_D6 6
#define MMA7455_D7 7

// Status Register
#define MMA7455_DRDY MMA7455_D0
#define MMA7455_DOVR MMA7455_D1
#define MMA7455_PERR MMA7455_D2

// Mode Control Register


#define MMA7455_MODE0 MMA7455_D0
#define MMA7455_MODE1 MMA7455_D1
#define MMA7455_GLVL0 MMA7455_D2
#define MMA7455_GLVL1 MMA7455_D3
#define MMA7455_STON MMA7455_D4
#define MMA7455_SPI3W MMA7455_D5
#define MMA7455_DRPD MMA7455_D6

// Control 1 Register
#define MMA7455_INTPIN MMA7455_D0
#define MMA7455_INTREG0 MMA7455_D1
#define MMA7455_INTREG1 MMA7455_D2
#define MMA7455_XDA MMA7455_D3
#define MMA7455_YDA MMA7455_D4
#define MMA7455_ZDA MMA7455_D5
#define MMA7455_THOPT MMA7455_D6
#define MMA7455_DFBW MMA7455_D7

// Control 2 Register
#define MMA7455_LDPL MMA7455_D0
#define MMA7455_PDPL MMA7455_D1
#define MMA7455_DRVO MMA7455_D2

// Interrupt Latch Reset Register


#define MMA7455_CLR_INT1 MMA7455_D0
#define MMA7455_CLR_INT2 MMA7455_D1

// Detection Source Register


#define MMA7455_INT1 MMA7455_D0
#define MMA7455_INT2 MMA7455_D1
#define MMA7455_PDZ MMA7455_D2
#define MMA7455_PDY MMA7455_D3
#define MMA7455_PDX MMA7455_D4
#define MMA7455_LDZ MMA7455_D5
#define MMA7455_LDY MMA7455_D6
#define MMA7455_LDX MMA7455_D7

// I2C Device Address Register


#define MMA7455_I2CDIS MMA7455_D7

// Default I2C address for the MMA7455


#define MMA7455_I2C_ADDRESS 0x1D

// When using an union for the registers and


// the axis values, the byte order of the accelerometer
// should match the byte order of the compiler and AVR chip.
// Both have the lower byte at the lower address,
// so they match.
// This union is only used by the low level functions.
typedef union xyz_union
{
struct
{
uint8_t x_lsb;
uint8_t x_msb;
uint8_t y_lsb;
uint8_t y_msb;
uint8_t z_lsb;
uint8_t z_msb;
} reg;
struct
{
uint16_t x;
uint16_t y;
uint16_t z;
} value;
};

int led = 13;

void setup()
{
int error;
uint8_t c;

Serial.begin(9600);
Serial.println("Freescale MMA7455 accelerometer");
Serial.println("May 2012");

// Initialize the 'Wire' class for I2C-bus communication.


Wire.begin();
// Initialize the MMA7455, and set the offset.
error = MMA7455_init();
if (error == 0)
Serial.println("The MMA7455 is okay");
else
Serial.println("Check your wiring !");

// Read the Status Register


MMA7455_read(MMA7455_STATUS, &c, 1);
Serial.print("STATUS : ");
Serial.println(c,HEX);

// Read the "Who am I" value


MMA7455_read(MMA7455_WHOAMI, &c, 1);
Serial.print("WHOAMI : ");
Serial.println(c,HEX);

// Read the optional temperature output value (I always read zero)


MMA7455_read(MMA7455_TOUT, &c, 1);
Serial.print("TOUT : ");
Serial.println(c,DEC);
pinMode(led, OUTPUT);
}

void loop()
{
uint16_t x,y,z, error;
double dX,dY,dZ;

// The function MMA7455_xyz returns the 'g'-force


// as an integer in 64 per 'g'.

// set x,y,z to zero (they are not written in case of an error).


x = y = z = 0;
error = MMA7455_xyz(&x, &y, &z); // get the accelerometer values.

dX = (int16_t) x / 64.0; // calculate the 'g' values.


dY = (int16_t) y / 64.0;
dZ = (int16_t) z / 64.0;

Serial.print("error = ");
Serial.print(error, DEC);
Serial.print(", xyz g-forces = ");
Serial.print(dX, 3);
Serial.print(", ");
Serial.print(dY, 3);
Serial.print(", ");
Serial.print(dZ, 3);
Serial.println("");

if (dZ < 0.8)


{
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
}
else
{
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
}

delay(100);
}

// --------------------------------------------------------
// MMA7455_init
//
// Initialize the MMA7455.
// Set also the offset, assuming that the accelerometer is
// in flat horizontal position.
//
// Important notes about the offset:
// The sensor has internal registers to set an offset.
// But the offset could also be calculated by software.
// This function uses the internal offset registers
// of the sensor.
// That turned out to be bad idea, since setting the
// offset alters the actual offset of the sensor.
// A second offset calculation had to be implemented
// to fine tune the offset.
// Using software variables for the offset would be
// much better.
//
// The offset is influenced by the slightest vibration
// (like a computer on the table).
//
int MMA7455_init(void)
{
uint16_t x, y, z;
int error;
xyz_union xyz;
uint8_t c1, c2;

// Initialize the sensor


//
// Sensitivity:
// 2g : GLVL0
// 4g : GLVL1
// 8g : GLVL1 | GLVL0
// Mode:
// Standby :0
// Measurement : MODE0
// Level Detection : MODE1
// Pulse Detection : MODE1 | MODE0
// There was no need to add functions to write and read
// a single byte. So only the two functions to write
// and read multiple bytes are used.

// Set mode for "2g sensitivity" and "Measurement Mode".


c1 = bit(MMA7455_GLVL0) | bit(MMA7455_MODE0);
error = MMA7455_write(MMA7455_MCTL, &c1, 1);
if (error != 0)
return (error);

// Read it back, to test the sensor and communication.


error = MMA7455_read(MMA7455_MCTL, &c2, 1);
if (error != 0)
return (error);

if (c1 != c2)
return (-99);

// Clear the offset registers.


// If the Arduino was reset or with a warm-boot,
// there still could be offset written in the sensor.
// Only with power-up the offset values of the sensor
// are zero.
xyz.value.x = xyz.value.y = xyz.value.z = 0;
error = MMA7455_write(MMA7455_XOFFL, (uint8_t *) &xyz, 6);
if (error != 0)
return (error);

// The mode has just been set, and the sensor is activated.
// To get a valid reading, wait some time.
delay(100);

#define USE_INTERNAL_OFFSET_REGISTERS
#ifdef USE_INTERNAL_OFFSET_REGISTERS

// Calcuate the offset.


//
// The values are 16-bits signed integers, but the sensor
// uses offsets of 11-bits signed integers.
// However that is not a problem,
// as long as the value is within the range.

// Assuming that the sensor is flat horizontal,


// the 'z'-axis should be 1 'g'. And 1 'g' is
// a value of 64 (if the 2g most sensitive setting
// is used).
// Note that the actual written value should be doubled
// for this sensor.
error = MMA7455_xyz (&x, &y, &z); // get the x,y,z values
if (error != 0)
return (error);

xyz.value.x = 2 * -x; // The sensor wants double values.


xyz.value.y = 2 * -y;
xyz.value.z = 2 * -(z-64); // 64 is for 1 'g' for z-axis.

error = MMA7455_write(MMA7455_XOFFL, (uint8_t *) &xyz, 6);


if (error != 0)
return (error);

// The offset has been set, and everything should be okay.


// But by setting the offset, the offset of the sensor
// changes.
// A second offset calculation has to be done after
// a short delay, to compensate for that.
delay(200);

error = MMA7455_xyz (&x, &y, &z); // get te x,y,z values again


if (error != 0)
return (error);

xyz.value.x += 2 * -x; // add to previous value


xyz.value.y += 2 * -y;
xyz.value.z += 2 * -(z-64); // 64 is for 1 'g' for z-axis.

// Write the offset for a second time.


// This time the offset is fine tuned.
error = MMA7455_write(MMA7455_XOFFL, (uint8_t *) &xyz, 6);
if (error != 0)
return (error);

#endif

return (0); // return : no error


}

// --------------------------------------------------------
// MMA7455_xyz
//
// Get the 'g' forces.
// The values are with integers as 64 per 'g'.
//
int MMA7455_xyz( uint16_t *pX, uint16_t *pY, uint16_t *pZ)
{
xyz_union xyz;
int error;
uint8_t c;
// Wait for status bit DRDY to indicate that
// all 3 axis are valid.
do
{
error = MMA7455_read (MMA7455_STATUS, &c, 1);
} while ( !bitRead(c, MMA7455_DRDY) && error == 0);
if (error != 0)
return (error);

// Read 6 bytes, containing the X,Y,Z information


// as 10-bit signed integers.
error = MMA7455_read (MMA7455_XOUTL, (uint8_t *) &xyz, 6);
if (error != 0)
return (error);

// The output is 10-bits and could be negative.


// To use the output as a 16-bit signed integer,
// the sign bit (bit 9) is extended for the 16 bits.
if (xyz.reg.x_msb & 0x02) // Bit 9 is sign bit.
xyz.reg.x_msb |= 0xFC; // Stretch bit 9 over other bits.
else
xyz.reg.x_msb &= 0x3;

if (xyz.reg.y_msb & 0x02)


xyz.reg.y_msb |= 0xFC;
else
xyz.reg.y_msb &= 0x3;

if (xyz.reg.z_msb & 0x02)


xyz.reg.z_msb |= 0xFC;
else
xyz.reg.z_msb &= 0x3;

// The result is the g-force in units of 64 per 'g'.


*pX = xyz.value.x;
*pY = xyz.value.y;
*pZ = xyz.value.z;

return (0); // return : no error


}

// --------------------------------------------------------
// MMA7455_read
//
// This is a common function to read multiple bytes
// from an I2C device.
//
// It uses the boolean parameter for Wire.endTransMission()
// to be able to hold or release the I2C-bus.
// This is implemented in Arduino 1.0.1.
//
// Only this function is used to read.
// There is no function for a single byte.
//
int MMA7455_read(int start, uint8_t *buffer, int size)
{
int i, n, error;

Wire.beginTransmission(MMA7455_I2C_ADDRESS);
n = Wire.write(start);
if (n != 1)
return (-10);

n = Wire.endTransmission(false); // hold the I2C-bus


if (n != 0)
return (n);

// Third parameter is true: relase I2C-bus after data is read.


Wire.requestFrom(MMA7455_I2C_ADDRESS, size, true);
i = 0;
while(Wire.available() && i<size)
{
buffer[i++]=Wire.read();
}
if ( i != size)
return (-11);

return (0); // return : no error


}

// --------------------------------------------------------
// MMA7455_write
//
// This is a common function to write multiple bytes
// to an I2C device.
//
// Only this function is used to write.
// There is no function for a single byte.
//
int MMA7455_write(int start, const uint8_t *pData, int size)
{
int n, error;

Wire.beginTransmission(MMA7455_I2C_ADDRESS);
n = Wire.write(start); // write the start address
if (n != 1)
return (-20);

n = Wire.write(pData, size); // write data bytes


if (n != size)
return (-21);
error = Wire.endTransmission(true); // release the I2C-bus
if (error != 0)
return (error);

return (0); // return : no error


}

===========================================================

// MMA7455 Accelerometer
// ---------------------
//
// By arduino.cc user "Krodal".
// May 2012
// Open Source / Public Domain
//
// Fixes to union and type conversions by Arduino.cc user "Afroviking"
// August 2014
//
// Using Arduino 1.0.1
// It will not work with an older version, since Wire.endTransmission()
// uses a parameter to hold or release the I2C bus.
//
// Documentation:
// - The Freescale MMA7455L datasheet
// - The AN3468 Application Note (programming).
// - The AN3728 Application Note (calibrating offset).
//
// The MMA7455 can be used by writing and reading a single byte,
// but it is also capable to read and write multiple bytes.
//
// The accuracy is 10-bits.
//

#include <Wire.h>

// Register names according to the datasheet.


// Register 0x1C is sometimes called 'PW', and sometimes 'PD'.
// The two reserved registers can not be used.
#define MMA7455_XOUTL 0x00 // Read only, Output Value X LSB
#define MMA7455_XOUTH 0x01 // Read only, Output Value X MSB
#define MMA7455_YOUTL 0x02 // Read only, Output Value Y LSB
#define MMA7455_YOUTH 0x03 // Read only, Output Value Y MSB
#define MMA7455_ZOUTL 0x04 // Read only, Output Value Z LSB
#define MMA7455_ZOUTH 0x05 // Read only, Output Value Z MSB
#define MMA7455_XOUT8 0x06 // Read only, Output Value X 8 bits
#define MMA7455_YOUT8 0x07 // Read only, Output Value Y 8 bits
#define MMA7455_ZOUT8 0x08 // Read only, Output Value Z 8 bits
#define MMA7455_STATUS 0x09 // Read only, Status Register
#define MMA7455_DETSRC 0x0A // Read only, Detection Source Register
#define MMA7455_TOUT 0x0B // Temperature Output Value (Optional)
#define MMA7455_RESERVED1 0x0C // Reserved
#define MMA7455_I2CAD 0x0D // Read/Write, I2C Device Address
#define MMA7455_USRINF 0x0E // Read only, User Information (Optional)
#define MMA7455_WHOAMI 0x0F // Read only, "Who am I" value (Optional)
#define MMA7455_XOFFL 0x10 // Read/Write, Offset Drift X LSB
#define MMA7455_XOFFH 0x11 // Read/Write, Offset Drift X MSB
#define MMA7455_YOFFL 0x12 // Read/Write, Offset Drift Y LSB
#define MMA7455_YOFFH 0x13 // Read/Write, Offset Drift Y MSB
#define MMA7455_ZOFFL 0x14 // Read/Write, Offset Drift Z LSB
#define MMA7455_ZOFFH 0x15 // Read/Write, Offset Drift Z MSB
#define MMA7455_MCTL 0x16 // Read/Write, Mode Control Register
#define MMA7455_INTRST 0x17 // Read/Write, Interrupt Latch Reset
#define MMA7455_CTL1 0x18 // Read/Write, Control 1 Register
#define MMA7455_CTL2 0x19 // Read/Write, Control 2 Register
#define MMA7455_LDTH 0x1A // Read/Write, Level Detection Threshold Limit Value
#define MMA7455_PDTH 0x1B // Read/Write, Pulse Detection Threshold Limit Value
#define MMA7455_PD 0x1C // Read/Write, Pulse Duration Value
#define MMA7455_LT 0x1D // Read/Write, Latency Time Value (between pulses)
#define MMA7455_TW 0x1E // Read/Write, Time Window for Second Pulse Value
#define MMA7455_RESERVED2 0x1F // Reserved

// Defines for the bits, to be able to change


// between bit number and binary definition.
// By using the bit number, programming the MMA7455
// is like programming an AVR microcontroller.
// But instead of using "(1<<X)", or "_BV(X)",
// the Arduino "bit(X)" is used.
#define MMA7455_D0 0
#define MMA7455_D1 1
#define MMA7455_D2 2
#define MMA7455_D3 3
#define MMA7455_D4 4
#define MMA7455_D5 5
#define MMA7455_D6 6
#define MMA7455_D7 7

// Status Register
#define MMA7455_DRDY MMA7455_D0
#define MMA7455_DOVR MMA7455_D1
#define MMA7455_PERR MMA7455_D2

// Mode Control Register


#define MMA7455_MODE0 MMA7455_D0
#define MMA7455_MODE1 MMA7455_D1
#define MMA7455_GLVL0 MMA7455_D2
#define MMA7455_GLVL1 MMA7455_D3
#define MMA7455_STON MMA7455_D4
#define MMA7455_SPI3W MMA7455_D5
#define MMA7455_DRPD MMA7455_D6
// Control 1 Register
#define MMA7455_INTPIN MMA7455_D0
#define MMA7455_INTREG0 MMA7455_D1
#define MMA7455_INTREG1 MMA7455_D2
#define MMA7455_XDA MMA7455_D3
#define MMA7455_YDA MMA7455_D4
#define MMA7455_ZDA MMA7455_D5
#define MMA7455_THOPT MMA7455_D6
#define MMA7455_DFBW MMA7455_D7

// Control 2 Register
#define MMA7455_LDPL MMA7455_D0
#define MMA7455_PDPL MMA7455_D1
#define MMA7455_DRVO MMA7455_D2

// Interrupt Latch Reset Register


#define MMA7455_CLR_INT1 MMA7455_D0
#define MMA7455_CLR_INT2 MMA7455_D1

// Detection Source Register


#define MMA7455_INT1 MMA7455_D0
#define MMA7455_INT2 MMA7455_D1
#define MMA7455_PDZ MMA7455_D2
#define MMA7455_PDY MMA7455_D3
#define MMA7455_PDX MMA7455_D4
#define MMA7455_LDZ MMA7455_D5
#define MMA7455_LDY MMA7455_D6
#define MMA7455_LDX MMA7455_D7

// I2C Device Address Register


#define MMA7455_I2CDIS MMA7455_D7

// Default I2C address for the MMA7455


#define MMA7455_I2C_ADDRESS 0x1D

// When using an union for the registers and


// the axis values, the byte order of the accelerometer
// should match the byte order of the compiler and AVR chip.
// Both have the lower byte at the lower address,
// so they match.
// This union is only used by the low level functions.
typedef union xyz_union
{
struct
{
uint8_t x_lsb;
uint8_t x_msb;
uint8_t y_lsb;
uint8_t y_msb;
uint8_t z_lsb;
uint8_t z_msb;
} reg;
struct
{
uint16_t x;
uint16_t y;
uint16_t z;
} value;
};

int led = 13;

void setup()
{
int error;
uint8_t c;

Serial.begin(9600);
Serial.println("Freescale MMA7455 accelerometer");
Serial.println("May 2012");

// Initialize the 'Wire' class for I2C-bus communication.


Wire.begin();

// Initialize the MMA7455, and set the offset.


error = MMA7455_init();
if (error == 0)
Serial.println("The MMA7455 is okay");
else
Serial.println("Check your wiring !");

// Read the Status Register


MMA7455_read(MMA7455_STATUS, &c, 1);
Serial.print("STATUS : ");
Serial.println(c,HEX);

// Read the "Who am I" value


MMA7455_read(MMA7455_WHOAMI, &c, 1);
Serial.print("WHOAMI : ");
Serial.println(c,HEX);

// Read the optional temperature output value (I always read zero)


MMA7455_read(MMA7455_TOUT, &c, 1);
Serial.print("TOUT : ");
Serial.println(c,DEC);
pinMode(led, OUTPUT);
}
void loop()
{
uint16_t x,y,z, error;
double dX,dY,dZ;

// The function MMA7455_xyz returns the 'g'-force


// as an integer in 64 per 'g'.

// set x,y,z to zero (they are not written in case of an error).


x = y = z = 0;
error = MMA7455_xyz(&x, &y, &z); // get the accelerometer values.

dX = (int16_t) x / 64.0; // calculate the 'g' values.


dY = (int16_t) y / 64.0;
dZ = (int16_t) z / 64.0;
float s=atan(dZ/dY)*57.3;
//float sm = map(s, 0, -1, 0, 179);

//Serial.print("error = ");
//Serial.print(error, DEC);
Serial.print("xyz g-forces = ");
Serial.print(dX, 3);
Serial.print(", ");
Serial.print(dY, 3);
Serial.print(", ");
Serial.print(dZ, 3);
Serial.print(" ");
Serial.print(s);
Serial.println("");

if (dZ < 0.8)


{
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
}
else
{
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
}

delay(100);
}

// --------------------------------------------------------
// MMA7455_init
//
// Initialize the MMA7455.
// Set also the offset, assuming that the accelerometer is
// in flat horizontal position.
//
// Important notes about the offset:
// The sensor has internal registers to set an offset.
// But the offset could also be calculated by software.
// This function uses the internal offset registers
// of the sensor.
// That turned out to be bad idea, since setting the
// offset alters the actual offset of the sensor.
// A second offset calculation had to be implemented
// to fine tune the offset.
// Using software variables for the offset would be
// much better.
//
// The offset is influenced by the slightest vibration
// (like a computer on the table).
//
int MMA7455_init(void)
{
uint16_t x, y, z;
int error;
xyz_union xyz;
uint8_t c1, c2;

// Initialize the sensor


//
// Sensitivity:
// 2g : GLVL0
// 4g : GLVL1
// 8g : GLVL1 | GLVL0
// Mode:
// Standby :0
// Measurement : MODE0
// Level Detection : MODE1
// Pulse Detection : MODE1 | MODE0
// There was no need to add functions to write and read
// a single byte. So only the two functions to write
// and read multiple bytes are used.

// Set mode for "2g sensitivity" and "Measurement Mode".


c1 = bit(MMA7455_GLVL0) | bit(MMA7455_MODE0);
error = MMA7455_write(MMA7455_MCTL, &c1, 1);
if (error != 0)
return (error);

// Read it back, to test the sensor and communication.


error = MMA7455_read(MMA7455_MCTL, &c2, 1);
if (error != 0)
return (error);

if (c1 != c2)
return (-99);

// Clear the offset registers.


// If the Arduino was reset or with a warm-boot,
// there still could be offset written in the sensor.
// Only with power-up the offset values of the sensor
// are zero.
xyz.value.x = xyz.value.y = xyz.value.z = 0;
error = MMA7455_write(MMA7455_XOFFL, (uint8_t *) &xyz, 6);
if (error != 0)
return (error);

// The mode has just been set, and the sensor is activated.
// To get a valid reading, wait some time.
delay(100);

#define USE_INTERNAL_OFFSET_REGISTERS
#ifdef USE_INTERNAL_OFFSET_REGISTERS

// Calcuate the offset.


//
// The values are 16-bits signed integers, but the sensor
// uses offsets of 11-bits signed integers.
// However that is not a problem,
// as long as the value is within the range.

// Assuming that the sensor is flat horizontal,


// the 'z'-axis should be 1 'g'. And 1 'g' is
// a value of 64 (if the 2g most sensitive setting
// is used).
// Note that the actual written value should be doubled
// for this sensor.

error = MMA7455_xyz (&x, &y, &z); // get the x,y,z values


if (error != 0)
return (error);

xyz.value.x = 2 * -x; // The sensor wants double values.


xyz.value.y = 2 * -y;
xyz.value.z = 2 * -(z-64); // 64 is for 1 'g' for z-axis.

error = MMA7455_write(MMA7455_XOFFL, (uint8_t *) &xyz, 6);


if (error != 0)
return (error);

// The offset has been set, and everything should be okay.


// But by setting the offset, the offset of the sensor
// changes.
// A second offset calculation has to be done after
// a short delay, to compensate for that.
delay(200);

error = MMA7455_xyz (&x, &y, &z); // get te x,y,z values again


if (error != 0)
return (error);
xyz.value.x += 2 * -x; // add to previous value
xyz.value.y += 2 * -y;
xyz.value.z += 2 * -(z-64); // 64 is for 1 'g' for z-axis.

// Write the offset for a second time.


// This time the offset is fine tuned.
error = MMA7455_write(MMA7455_XOFFL, (uint8_t *) &xyz, 6);
if (error != 0)
return (error);

#endif

return (0); // return : no error


}

// --------------------------------------------------------
// MMA7455_xyz
//
// Get the 'g' forces.
// The values are with integers as 64 per 'g'.
//
int MMA7455_xyz( uint16_t *pX, uint16_t *pY, uint16_t *pZ)
{
xyz_union xyz;
int error;
uint8_t c;

// Wait for status bit DRDY to indicate that


// all 3 axis are valid.
do
{
error = MMA7455_read (MMA7455_STATUS, &c, 1);
} while ( !bitRead(c, MMA7455_DRDY) && error == 0);
if (error != 0)
return (error);

// Read 6 bytes, containing the X,Y,Z information


// as 10-bit signed integers.
error = MMA7455_read (MMA7455_XOUTL, (uint8_t *) &xyz, 6);
if (error != 0)
return (error);

// The output is 10-bits and could be negative.


// To use the output as a 16-bit signed integer,
// the sign bit (bit 9) is extended for the 16 bits.
if (xyz.reg.x_msb & 0x02) // Bit 9 is sign bit.
xyz.reg.x_msb |= 0xFC; // Stretch bit 9 over other bits.
else
xyz.reg.x_msb &= 0x3;

if (xyz.reg.y_msb & 0x02)


xyz.reg.y_msb |= 0xFC;
else
xyz.reg.y_msb &= 0x3;

if (xyz.reg.z_msb & 0x02)


xyz.reg.z_msb |= 0xFC;
else
xyz.reg.z_msb &= 0x3;

// The result is the g-force in units of 64 per 'g'.


*pX = xyz.value.x;
*pY = xyz.value.y;
*pZ = xyz.value.z;

return (0); // return : no error


}

// --------------------------------------------------------
// MMA7455_read
//
// This is a common function to read multiple bytes
// from an I2C device.
//
// It uses the boolean parameter for Wire.endTransMission()
// to be able to hold or release the I2C-bus.
// This is implemented in Arduino 1.0.1.
//
// Only this function is used to read.
// There is no function for a single byte.
//
int MMA7455_read(int start, uint8_t *buffer, int size)
{
int i, n, error;

Wire.beginTransmission(MMA7455_I2C_ADDRESS);
n = Wire.write(start);
if (n != 1)
return (-10);

n = Wire.endTransmission(false); // hold the I2C-bus


if (n != 0)
return (n);

// Third parameter is true: relase I2C-bus after data is read.


Wire.requestFrom(MMA7455_I2C_ADDRESS, size, true);
i = 0;
while(Wire.available() && i<size)
{
buffer[i++]=Wire.read();
}
if ( i != size)
return (-11);

return (0); // return : no error


}

// --------------------------------------------------------
// MMA7455_write
//
// This is a common function to write multiple bytes
// to an I2C device.
//
// Only this function is used to write.
// There is no function for a single byte.
//
int MMA7455_write(int start, const uint8_t *pData, int size)
{
int n, error;

Wire.beginTransmission(MMA7455_I2C_ADDRESS);
n = Wire.write(start); // write the start address
if (n != 1)
return (-20);

n = Wire.write(pData, size); // write data bytes


if (n != size)
return (-21);

error = Wire.endTransmission(true); // release the I2C-bus


if (error != 0)
return (error);

return (0); // return : no error


}

================================================================

/* YourDuinoStarter Example: MMA7455 Accelerometer Test


This example uses the MMA_7455 library by Moritz Kemper [email protected]
Released under Creative Commons Licence
For use with this module or equivalent:
http://yourduino.com/sunshop2/index.php?l=product_detail&p=391
CONNECTIONS:
+5V and GND to Arduino/Yourduino (Module has 3.3V regulator)
SCL - To Arduino / YourDuino A5 (Or Mega SCL pin)
SDA - To Arduino / YourDuino A4 (Or Mega SDA pin)
- V1.03 11/18/2013
Questions?: [email protected]

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


#include <Wire.h> //Include the Wire library
#include <MMA_7455.h> //Include the MMA_7455 library

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

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


MMA_7455 mySensor = MMA_7455(); //Make an instance of MMA_7455

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


char xVal, yVal, zVal; //Variables for the values from the sensor

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


{
Serial.begin(9600);
delay(500);
Serial.println("MMA7455 Accelerometer Test. [email protected]");
// Set the sensitivity you want to use
// 2 = 2g, 4 = 4g, 8 = 8g
mySensor.initSensitivity(2); // Good for "Tilt" measurements
/* Calibrate the Offset. Calibrate, in Flat position, try to
get: xVal = 0, yVal = 0, zVal = +63 (1 G)
!!!Activate this after having the first values read out!!!
Suggestion: Run this with offsets = 0,0,0 and see needed correction
*/
//mySensor.calibrateOffset(0,0,0); //Uncomment for first try: find offsets
mySensor.calibrateOffset(3.0, 19.0, -12.0); //Then Uncomment and use this

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

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


{
xVal = mySensor.readAxis('x'); //Read out the 'x' Axis
yVal = mySensor.readAxis('y'); //Read out the 'y' Axis
zVal = mySensor.readAxis('z'); //Read out the 'z' Axis
Serial.print("X = ");
Serial.print(xVal, DEC);
Serial.print(" Y = ");
Serial.print(yVal, DEC);
Serial.print(" Z = ");
Serial.println(zVal, DEC);
delay(100);
/*--( Show tilt [Assumes unit has been calibrated ] )----*/
if (xVal < -20) Serial.println("Tilted LEFT");
if (xVal > 20) Serial.println("Tilted RIGHT");
if (yVal < -20) Serial.println("Tilted TOWARDS");
if (yVal > 20 ) Serial.println("Tilted AWAY");
if (zVal < -45 ) Serial.println("UPSIDE DOWN!");
}//--(end main loop )---

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


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

=================================================================
67. MP3 SHIELD

#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

SdFat sd;
SFEMP3Shield MP3player;

void setup() {

Serial.begin(9600);

//start the shield


sd.begin(SD_SEL, SPI_HALF_SPEED);
MP3player.begin();

//start playing track 1


//MP3player.playTrack(1);
//All mp3 files should be in format : track001.mp3, track002.mp3, ....
/* Free pins :
The hardware UART pins – RX and TX – on pins 0 and 1
D5 and D10 (PWM pins!)
All analog pins (A0 through A5).
*/
}

//do something else now


void loop() {
MP3player.playTrack(1);
delay(2000);
MP3player.playTrack(2);
delay(2000);
MP3player.playTrack(3);
delay(2000);
MP3player.playTrack(4);
delay(2000);
MP3player.playTrack(5);
delay(2000);
MP3player.playTrack(6);
delay(2000);
MP3player.playTrack(7);
delay(2000);
MP3player.playTrack(8);
delay(2000);
MP3player.playTrack(9);
delay(2000);
MP3player.playTrack(10);
delay(2000);
MP3player.playTrack(11);
delay(2000);
MP3player.playTrack(12);
delay(2000);
MP3player.playTrack(13);
delay(2000);
MP3player.playTrack(14);
delay(2000);
MP3player.playTrack(15);
delay(2000);

==============================================================
68. THERMOCOUPLE
#include "max6675.h"

int ktcSO = 8;
int ktcCS = 9;
int ktcCLK = 10;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

void setup() {
Serial.begin(9600);
// give the MAX a little time to settle
delay(500);
}

void loop() {
// basic readout test

Serial.print("Deg C = ");
Serial.print(ktc.readCelsius());
Serial.print("\t Deg F = ");
Serial.println(ktc.readFahrenheit());

delay(500);
}
69. MENGUKUR SUDUT MEMUTAR DENGAN MPU6050

#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
MPU6050 mpu;
#define OUTPUT_READABLE_EULER
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
int pinSetting = 4;

int addr = 1;
float sudut = 0;
int sudutawal = 0;

// MPU control/status vars


bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector

// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}

// ================================================================
// === INITIAL SETUP ===
// ================================================================

void setup() {
pinMode(pinSetting, INPUT);
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif

// initialize serial communication


// (115200 chosen because it is required for Teapot Demo output, but it's
// really up to you depending on your project)
Serial.begin(9600);
while (!Serial); // wait for Leonardo enumeration, others continue immediately

mpu.initialize();

devStatus = mpu.dmpInitialize();

// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(38);
mpu.setYGyroOffset(-91);
mpu.setZGyroOffset(46);
mpu.setZAccelOffset(1682); // 1688 factory default for my test chip
// make sure it worked (returns 0 if so)
if (devStatus == 0) {

mpu.setDMPEnabled(true);

attachInterrupt(0, dmpDataReady, RISING);


mpuIntStatus = mpu.getIntStatus();

// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;

// get expected DMP packet size for later comparison


packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}

// configure LED for output


pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// === MAIN PROGRAM LOOP ===
// ================================================================

void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;

// wait for MPU interrupt or extra packet(s) available


while (!mpuInterrupt && fifoCount < packetSize) {
// other program behavior stuff here
// .
// .
// .
// if you are really paranoid you can frequently test in between other
// stuff to see if mpuInterrupt is true, and if so, "break;" from the
// while() loop to immediately process the MPU data
// .
// .
// .
}

// reset interrupt flag and get INT_STATUS byte


mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();

// get current FIFO count


fifoCount = mpu.getFIFOCount();

if(digitalRead(pinSetting) == HIGH){

//------------------------------------------------------------------------
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
//Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

// read a packet from FIFO


mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available


// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;

// display Euler angles in degrees


mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
//Serial.print("euler\t");
sudut = euler[0] * 180/M_PI;
//Serial.print(sudut);
//Serial.print(" ");
// Serial.print("\t");
// Serial.print(euler[1] * 180/M_PI);
// Serial.print("\t");
// Serial.println(euler[2] * 180/M_PI);

// blink LED to indicate activity


//blinkState = !blinkState;
//digitalWrite(LED_PIN, blinkState);
}
//--------------------------------------------------------------------------------------
while (!eeprom_is_ready());
cli();
if(eeprom_read_word((uint16_t*)addr) != sudut) {
eeprom_update_word((uint16_t*)addr, sudut);
}
sei();

while (!eeprom_is_ready());
cli();
sudutawal = eeprom_read_word((uint16_t*)addr); // => sensorValue
sei();
Serial.print(sudut);
Serial.print(" ");
Serial.print(sudutawal);
Serial.print(" ");
hitung();
delay(100);

}else if(digitalRead(pinSetting) == LOW){

//------------------------------------------------------------------------
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
//Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

// read a packet from FIFO


mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available


// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;

// display Euler angles in degrees


mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
//Serial.print("euler\t");
sudut = euler[0] * 180/M_PI;
//Serial.print(sudut);
//Serial.print(" ");
// Serial.print("\t");
// Serial.print(euler[1] * 180/M_PI);
// Serial.print("\t");
// Serial.println(euler[2] * 180/M_PI);

// blink LED to indicate activity


//blinkState = !blinkState;
//digitalWrite(LED_PIN, blinkState);
}
//--------------------------------------------------------------------------------------
//while (!eeprom_is_ready());
//cli();

/*if(eeprom_read_word((uint16_t*)addr) != sudut) {
eeprom_write_word((uint16_t*)addr, sudut);
}

sei();
*/
while (!eeprom_is_ready());
cli();
sudutawal = eeprom_read_word((uint16_t*)addr); // => sensorValue
sei();
Serial.print(sudut);
Serial.print(" ");
Serial.print(sudutawal);
Serial.print(" ");
hitung();
delay(100);
}

void hitung(){

if(((sudutawal >= -90) && (sudutawal <= 90)) || ((sudutawal >= -180) && (sudutawal < -90))){
int delta = abs(sudut-sudutawal);
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= -180) && (sudut < 0)){
int delta = (360 + sudut-sudutawal);
Serial.println(delta);
}
else if((sudutawal >= -180) && (sudutawal < -90) && (sudut >= 0) && (sudut <= 180)){
int delta = (360 - sudut+sudutawal);
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= 0) && (sudut <= 180)){
int delta = abs(sudut-sudutawal);
Serial.println(delta);
}
else{
Serial.println(" ");
}

=================================================================
70. MENGUKUR SUDUT MEMUTAR DENGAN MPU6050 (IR RESET)

#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
MPU6050 mpu;
#define OUTPUT_READABLE_EULER
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
int pinSetting = 4;
#include <IRremote.h>
int RECV_PIN = 5;
IRrecv irrecv(RECV_PIN);
decode_results results;

int addr = 1;
float sudut = 0;
int sudutawal = 0;

// MPU control/status vars


bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector

// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}

// ================================================================
// === INITIAL SETUP ===
// ================================================================

void setup() {
irrecv.enableIRIn();
pinMode(pinSetting, INPUT);
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif

// initialize serial communication


// (115200 chosen because it is required for Teapot Demo output, but it's
// really up to you depending on your project)
Serial.begin(9600);
while (!Serial); // wait for Leonardo enumeration, others continue immediately

mpu.initialize();

devStatus = mpu.dmpInitialize();
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(38);
mpu.setYGyroOffset(-91);
mpu.setZGyroOffset(46);
mpu.setZAccelOffset(1682); // 1688 factory default for my test chip

// make sure it worked (returns 0 if so)


if (devStatus == 0) {

mpu.setDMPEnabled(true);

attachInterrupt(0, dmpDataReady, RISING);


mpuIntStatus = mpu.getIntStatus();

// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;

// get expected DMP packet size for later comparison


packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}

// configure LED for output


pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// === MAIN PROGRAM LOOP ===
// ================================================================

void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;

// wait for MPU interrupt or extra packet(s) available


while (!mpuInterrupt && fifoCount < packetSize) {
// other program behavior stuff here
// .
// .
// .
// if you are really paranoid you can frequently test in between other
// stuff to see if mpuInterrupt is true, and if so, "break;" from the
// while() loop to immediately process the MPU data
// .
// .
// .
}

// reset interrupt flag and get INT_STATUS byte


mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();

// get current FIFO count


fifoCount = mpu.getFIFOCount();

if(irrecv.decode(&results)){

//------------------------------------------------------------------------
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
//Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

// read a packet from FIFO


mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available


// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;

// display Euler angles in degrees


mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
//Serial.print("euler\t");
sudut = euler[0] * 180/M_PI;
//Serial.print(sudut);
//Serial.print(" ");
// Serial.print("\t");
// Serial.print(euler[1] * 180/M_PI);
// Serial.print("\t");
// Serial.println(euler[2] * 180/M_PI);

// blink LED to indicate activity


//blinkState = !blinkState;
//digitalWrite(LED_PIN, blinkState);
}
//--------------------------------------------------------------------------------------
while (!eeprom_is_ready());
cli();
if(eeprom_read_word((uint16_t*)addr) != sudut) {
eeprom_update_word((uint16_t*)addr, sudut);
}
sei();

while (!eeprom_is_ready());
cli();
sudutawal = eeprom_read_word((uint16_t*)addr); // => sensorValue
sei();
Serial.print(sudut);
Serial.print(" ");
Serial.print(sudutawal);
Serial.print(" ");
hitung();
irrecv.resume();
delay(100);

}else{

//------------------------------------------------------------------------
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
//Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

// read a packet from FIFO


mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available


// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;

// display Euler angles in degrees


mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
//Serial.print("euler\t");
sudut = euler[0] * 180/M_PI;
//Serial.print(sudut);
//Serial.print(" ");
// Serial.print("\t");
// Serial.print(euler[1] * 180/M_PI);
// Serial.print("\t");
// Serial.println(euler[2] * 180/M_PI);

// blink LED to indicate activity


//blinkState = !blinkState;
//digitalWrite(LED_PIN, blinkState);
}
//--------------------------------------------------------------------------------------
//while (!eeprom_is_ready());
//cli();

/*if(eeprom_read_word((uint16_t*)addr) != sudut) {
eeprom_write_word((uint16_t*)addr, sudut);
}

sei();
*/
while (!eeprom_is_ready());
cli();
sudutawal = eeprom_read_word((uint16_t*)addr); // => sensorValue
sei();
Serial.print(sudut);
Serial.print(" ");
Serial.print(sudutawal);
Serial.print(" ");
hitung();
delay(100);
}

void hitung(){

if(((sudutawal >= -90) && (sudutawal <= 90)) || ((sudutawal >= -180) && (sudutawal < -90))){
int delta = abs(sudut-sudutawal);
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= -180) && (sudut < 0)){
int delta = (360 + sudut-sudutawal);
Serial.println(delta);
}
else if((sudutawal >= -180) && (sudutawal < -90) && (sudut >= 0) && (sudut <= 180)){
int delta = (360 - sudut+sudutawal);
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= 0) && (sudut <= 180)){
int delta = abs(sudut-sudutawal);
Serial.println(delta);
}
else{
Serial.println(" ");
}

}
71. MENGENDALIKAN CONTINOUS MOTOR SERVO DENGAN IR REMOTE

#include <IRremote.h>
#include <Servo.h>
Servo myservo1; // create servo object to control a servo
Servo myservo2;
int RECV_PIN = 5;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
myservo1.attach(10);
myservo2.attach(11);
irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();
void loop() {
if (irrecv.decode(&results)) {
if (results.value == 0xEF10E01F) {
kanan();
}
else if (results.value == 0xEF10609F) {
kiri();
}
else if (results.value == 0xEF1054AB) {
henti();
}
else if (results.value == 0xEF1020DF) {
maju();
}
else if (results.value == 0xEF10A05F) {
mundur();
}
irrecv.resume(); // Receive the next value
}
}

void kanan(){
myservo1.write(80);
myservo2.write(80);
delay(1000);
henti();
irrecv.resume();

}
void kiri(){
myservo1.write(100);
myservo2.write(100);
delay(1000);
henti();
irrecv.resume();

}
void henti(){
myservo1.write(90);
myservo2.write(90);
irrecv.resume();

}
void maju(){
myservo1.write(110);
myservo2.write(70);
irrecv.resume();

}
void mundur(){
myservo1.write(70);
myservo2.write(110);
irrecv.resume();

atau

/*
source: www.electroschematics.com
You'll need to change the led pins and the codes
accordingly to your configuration and IR remote
552656927
552600317
552624287
*/

#include <IRremote.h>
#include <Servo.h>
Servo myservo1; // create servo object to control a servo
Servo myservo2;

int RECV_PIN = 5; // the pin where you connect the output pin of TSOP4838

/* the initial state of LEDs is OFF (zero)


the first zero must remain zero but you can
change the others to 1's if you want a certain
led to light when the board is powered */
#define code1 4010860575 // code received from button A
#define code2 4010827935 // code received from button B
#define code3 4010824875 // code received from button C
#define code4 4010811615
#define code5 4010844255

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
myservo1.attach(10);
myservo2.attach(11);
Serial.begin(9600); // you can comment this line
irrecv.enableIRIn(); // Start the receiver

void loop() {
if (irrecv.decode(&results)) {
unsigned int value = results.value;
switch(value) {
case code1:
kanan();
break;
case code2:
kiri();
break;
case code3:
henti();
break;
case code4:
maju();
break;
case code5:
mundur();
break;
}
Serial.println(value); // you can comment this line
irrecv.resume(); // Receive the next value
}
}

void kanan(){
myservo1.write(80);
myservo2.write(80);
delay(1000);
henti();
irrecv.resume();

}
void kiri(){
myservo1.write(100);
myservo2.write(100);
delay(1000);
henti();
irrecv.resume();

}
void henti(){
myservo1.write(90);
myservo2.write(90);
irrecv.resume();

}
void maju(){
myservo1.write(110);
myservo2.write(70);
irrecv.resume();

}
void mundur(){
myservo1.write(70);
myservo2.write(110);
irrecv.resume();

}
72. MENGENDALIKAN CONTINOUS MOTOR SERVO DENGAN MPU DAN IR REMOTE

#include <IRremote.h>
#include <Servo.h>
Servo myservo1; // create servo object to control a servo
Servo myservo2;
#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include <EEPROM.h>
int value;
int addr0 = 1;
int addr1 = 2;
int a;
byte b;

int RECV_PIN = 5;

#define code1 4010860575 // code received from button A


#define code2 4010827935 // code received from button B
#define code3 4010824875 // code received from button C
#define code4 4010811615
#define code5 4010844255

IRrecv irrecv(RECV_PIN);

decode_results results;
//#include <avr/interrupt.h>
//#include <avr/eeprom.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
MPU6050 mpu;
#define OUTPUT_READABLE_EULER
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

float sudut = 0;
int sudutawal = 0;

// MPU control/status vars


bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector

// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}

void setup()
{
myservo1.attach(10);
myservo2.attach(11);
Serial.begin(9600); // you can comment this line
irrecv.enableIRIn(); // Start the receiver

// join I2C bus (I2Cdev library doesn't do this automatically)


#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif

// initialize serial communication


// (115200 chosen because it is required for Teapot Demo output, but it's
// really up to you depending on your project)
//Serial.begin(9600);
while (!Serial); // wait for Leonardo enumeration, others continue immediately

mpu.initialize();

devStatus = mpu.dmpInitialize();

// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(38);
mpu.setYGyroOffset(-91);
mpu.setZGyroOffset(46);
mpu.setZAccelOffset(1682); // 1688 factory default for my test chip

// make sure it worked (returns 0 if so)


if (devStatus == 0) {

mpu.setDMPEnabled(true);

attachInterrupt(0, dmpDataReady, RISING);


mpuIntStatus = mpu.getIntStatus();

// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;

// get expected DMP packet size for later comparison


packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}

// configure LED for output


pinMode(LED_PIN, OUTPUT);
}

void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;

// wait for MPU interrupt or extra packet(s) available


while (!mpuInterrupt && fifoCount < packetSize) {
// other program behavior stuff here
// .
// .
// .
// if you are really paranoid you can frequently test in between other
// stuff to see if mpuInterrupt is true, and if so, "break;" from the
// while() loop to immediately process the MPU data
// .
// .
// .
}

// reset interrupt flag and get INT_STATUS byte


mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();

// get current FIFO count


fifoCount = mpu.getFIFOCount();

if (irrecv.decode(&results)) {
//------------------------------------------------------------------------
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
//Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

// read a packet from FIFO


mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available


// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
//Serial.print("euler\t");
sudut = euler[0] * 180/M_PI;
//Serial.print(sudut);
//Serial.print(" ");
// Serial.print("\t");
// Serial.print(euler[1] * 180/M_PI);
// Serial.print("\t");
// Serial.println(euler[2] * 180/M_PI);

// blink LED to indicate activity


//blinkState = !blinkState;
//digitalWrite(LED_PIN, blinkState);
}
//--------------------------------------------------------------------------------------

//unsigned int value = results.value;


switch(results.value) {
case code1:
a=1;
EEPROM.write(addr0, a);
while (!eeprom_is_ready());
cli();

if(eeprom_read_word((uint16_t*)addr1) != sudut) {
eeprom_update_word((uint16_t*)addr1, sudut);
}
sei();
//kanan();
break;
case code2:
a=2;
EEPROM.write(addr0, a);;
while (!eeprom_is_ready());
cli();

if(eeprom_read_word((uint16_t*)addr1) != sudut) {
eeprom_update_word((uint16_t*)addr1, sudut);
}
sei();
//kiri();
break;
case code3:
a=3;
EEPROM.write(addr0, a);
while (!eeprom_is_ready());
cli();

if(eeprom_read_word((uint16_t*)addr1) != sudut) {
eeprom_update_word((uint16_t*)addr1, sudut);
}
sei();
henti();
break;
case code4:
a=4;
EEPROM.write(addr0, a);
while (!eeprom_is_ready());
cli();

if(eeprom_read_word((uint16_t*)addr1) != sudut) {
eeprom_update_word((uint16_t*)addr1, sudut);
}
sei();
maju();
break;
case code5:
a=5;
EEPROM.write(addr0, a);
while (!eeprom_is_ready());
cli();

if(eeprom_read_word((uint16_t*)addr1) != sudut) {
eeprom_update_word((uint16_t*)addr1, sudut);
}
sei();
mundur();
break;
}
//Serial.println(value); // you can comment this line
irrecv.resume(); // Receive the next value
}
else{
//------------------------------------------------------------------------
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
//Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

// read a packet from FIFO


mpu.getFIFOBytes(fifoBuffer, packetSize);

// track FIFO count here in case there is > 1 packet available


// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
//Serial.print("euler\t");
sudut = euler[0] * 180/M_PI;
//Serial.print(sudut);
//Serial.print(" ");
// Serial.print("\t");
// Serial.print(euler[1] * 180/M_PI);
// Serial.print("\t");
// Serial.println(euler[2] * 180/M_PI);

// blink LED to indicate activity


//blinkState = !blinkState;
//digitalWrite(LED_PIN, blinkState);
}
//--------------------------------------------------------------------------------------
//while (!eeprom_is_ready());
//cli();
b = EEPROM.read(addr0); // => sensorValue
//sei();
//while (!eeprom_is_ready());
//cli();
sudutawal = eeprom_read_word((uint16_t*)addr1); // => sensorValue
//sei();
Serial.print(b);
Serial.print(" ");
Serial.print(sudut);
Serial.print(" ");
Serial.print(sudutawal);
Serial.println(" ");
if (b==1){

if(((sudutawal >= -90) && (sudutawal <= 90)) || ((sudutawal >= -180) && (sudutawal < -90))){
int delta = abs(sudut-sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= -180) && (sudut < 0)){
int delta = (360 + sudut-sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else if((sudutawal >= -180) && (sudutawal < -90) && (sudut >= 0) && (sudut <= 180)){
int delta = (360 - sudut+sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= 0) && (sudut <= 180)){
int delta = abs(sudut-sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else{
Serial.print(" ");
//irrecv.resume();
}

}
else if(b==2){

if(((sudutawal >= -90) && (sudutawal <= 90)) || ((sudutawal >= -180) && (sudutawal < -90))){
int delta = abs(sudut-sudutawal);

if (delta <=90){
myservo1.write(100);
myservo2.write(100);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= -180) && (sudut < 0)){
int delta = (360 + sudut-sudutawal);
if (delta <=90){
myservo1.write(100);
myservo2.write(100);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else if((sudutawal >= -180) && (sudutawal < -90) && (sudut >= 0) && (sudut <= 180)){
int delta = (360 - sudut+sudutawal);
if (delta <=90){
myservo1.write(100);
myservo2.write(100);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= 0) && (sudut <= 180)){
int delta = abs(sudut-sudutawal);
if (delta <=90){
myservo1.write(100);
myservo2.write(100);

}
else if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.print(delta);
}
else{
Serial.print(" ");
//irrecv.resume();
}

}
}

void kanan(){

if(((sudutawal >= -90) && (sudutawal <= 90)) || ((sudutawal >= -180) && (sudutawal < -90))){
int delta = abs(sudut-sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= -180) && (sudut < 0)){
int delta = (360 + sudut-sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.println(delta);
}
else if((sudutawal >= -180) && (sudutawal < -90) && (sudut >= 0) && (sudut <= 180)){
int delta = (360 - sudut+sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= 0) && (sudut <= 180)){
int delta = abs(sudut-sudutawal);
if (delta <=90){
myservo1.write(80);
myservo2.write(80);

}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);

}
Serial.println(delta);
}
else{
Serial.println(" ");

}
void kiri(){

if(((sudutawal >= -90) && (sudutawal <= 90)) || ((sudutawal >= -180) && (sudutawal < -90))){
int delta = abs(sudut-sudutawal);
if (delta <=90){
myservo1.write(100);
myservo2.write(100);
}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);
}
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= -180) && (sudut < 0)){
int delta = (360 + sudut-sudutawal);
if (delta <=90){
myservo1.write(100);
myservo2.write(100);
}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);
}
Serial.println(delta);
}
else if((sudutawal >= -180) && (sudutawal < -90) && (sudut >= 0) && (sudut <= 180)){
int delta = (360 - sudut+sudutawal);
if (delta <=90){
myservo1.write(100);
myservo2.write(100);
}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);
}
Serial.println(delta);
}
else if((sudutawal > 90) && (sudutawal <= 180) && (sudut >= 0) && (sudut <= 180)){
int delta = abs(sudut-sudutawal);
if (delta <=90){
myservo1.write(100);
myservo2.write(100);
}
if (delta > 90){
myservo1.write(90);
myservo2.write(90);
}
Serial.println(delta);
}
else{
Serial.println(" ");
}

}
void henti(){
myservo1.write(90);
myservo2.write(90);
irrecv.resume();

}
void maju(){
myservo1.write(110);
myservo2.write(70);
irrecv.resume();

}
void mundur(){
myservo1.write(71);
myservo2.write(110);
irrecv.resume();

}
73. WATERING PLANT

#define trigger 11

void setup() {

Serial.begin(9600);
pinMode(trigger, OUTPUT);
}
void loop() {
int sensorValue0 = analogRead(A0);

if (sensorValue0 <= 500) {


analogWrite(trigger, 25); // for adjust pump speed

}
if (sensorValue0 >= 500) {
analogWrite(trigger, 0);
}
Serial.println(sensorValue0);

}
74. RAIN DETECTOR

//Rain Sensor Detection of Rain


//www.circuits4you.com

int nRainDigitalIn = 2;
int nRainVal;
boolean bIsRaining = false;
String strRaining;

void setup() {
Serial.begin(9600);
pinMode(2,INPUT);
}
void loop() {
nRainVal = analogRead(A0);
bIsRaining = !(digitalRead(nRainDigitalIn)); //Cheks Digital Pin 2, Output D0

if(bIsRaining){ //Cheks Digital Pin 2, Output D0


strRaining = "YES";
}
else{
strRaining = "NO";
}

Serial.print("Raining: ");
Serial.print(strRaining);
Serial.print(" Moisture Level: ");
Serial.println(nRainVal);
delay(100);
}

=======================================================================
/*
* Arduino Rain Sensor Alarm
* Realized using a pre-wired rain sensor module
* Author: T.K.Hareendran
* Prototyped &Tested at Technode Protolabz /1:04 AM 7/26/2015
* Source: http://www.electroschematics.com
*/
int rainSensePin= 0; // analog pin 0 - sensor i/p
int alertPin= 8; // digital pin 8 - alert o/p
int curCounter= 0; // current counter - goes up by 1 every second while sensing

void setup(){
Serial.begin(9600);
pinMode(alertPin, OUTPUT);
pinMode(rainSensePin, INPUT);
}
void loop(){
int rainSenseReading = analogRead(rainSensePin);
Serial.println(rainSenseReading); // use this for serial monitoring if available
delay(100); // relax
// check to see how long it is raining at the threshold level
// rain strength value from 0 - 1023
// heavy rain -to- no rain.
if (curCounter >= 30){ // end of the time delay
digitalWrite(alertPin, HIGH); //raise an alert after x time
}

// If raining is continuing for x amount of time raise an alert


// When raining is no longer detected, reset the counter
if (rainSenseReading <500){ // while raining at threshold level - see text
curCounter++; // increment sensing counter
}
else if (rainSenseReading >300) { // if not raining at threshold level
digitalWrite(alertPin, LOW); // don't raise an alert
curCounter = 0; // reset the counter to 0
}
delay(100);
}

================================================================

/*Arduino Rain Sensor sketch*/

int rainsense= 0; // analog sensor input pin 0


int buzzerout= 11; // buzzer output
int countval= 0; // counter value starting from 0

void setup(){
Serial.begin(9600);
pinMode(buzzerout, OUTPUT);
pinMode(rainsense, INPUT);
}
void loop(){
int rainSenseReading = analogRead(rainsense);
Serial.println(rainSenseReading); // serial monitoring message
delay(50);// this variable fo adjust counter interval
// from heavy rain - no rain.
if (countval >= 35){
Serial.print("Heavy rain");
analogWrite(buzzerout, 150); //raise an alert after x time
}
//raining for long duration rise buzzer sound
// there is no rain then reset the counter value
if (rainSenseReading <350){
countval++; // increment count value
}
else if (rainSenseReading >350) { // if not raining
digitalWrite(buzzerout, LOW); // turn off buzzer
countval = 0; // reset count to 0
}
delay(50); //this variable fo adjust counter interval
}

-----------------------------------------------------------------------------------------------------------------

/*Arduino Rain Sensor sketch*/

int rainsense= 0; // analog sensor input pin 0


const int pinSpeaker = 11; // buzzer output
int countval= 0; // counter value starting from 0
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
void setup(){
Serial.begin(9600);
pinMode(pinSpeaker, OUTPUT);
pinMode(rainsense, INPUT);
}
void loop(){
int rainSenseReading = analogRead(rainsense);
Serial.println(rainSenseReading); // serial monitoring message
delay(50);// this variable fo adjust counter interval
// from heavy rain - no rain.
if (countval >= 35){
Serial.print("Heavy rain");
alarm(); //raise an alert after x time
}
//raining for long duration rise buzzer sound
// there is no rain then reset the counter value
if (rainSenseReading <350){
countval++; // increment count value
}
else if (rainSenseReading >350) { // if not raining
noTone(pinSpeaker); // turn off buzzer
countval = 0; // reset count to 0
}
delay(50); //this variable fo adjust counter interval
}
void alarm(){
tone(pinSpeaker,NOTE_C4, 500);
delay(500);
tone(pinSpeaker,NOTE_D4, 500);
delay(500);
}
75. PIR SENSOR

/* PIR sensor tester*/

int ledPin = 13; // choose the pin for the LED


int inputPin = 7; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status

void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input

Serial.begin(9600);
}

void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH){
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}

-------------------------------------------------------------------------------------------------------------

/*
* //////////////////////////////////////////////////
* //making sense of the Parallax PIR sensor's output
* //////////////////////////////////////////////////
*
* Switches a LED according to the state of the sensors output pin.
* Determines the beginning and end of continuous motion sequences.
*
* @author: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at
* @date: 3. September 2006
*
* kr1 (cleft) 2006
* released under a creative commons "Attribution-NonCommercial-ShareAlike 2.0" license
* http://creativecommons.org/licenses/by-nc-sa/2.0/de/
*
*
* The Parallax PIR Sensor is an easy to use digital infrared motion sensor module.
* (http://www.parallax.com/detail.asp?product_id=555-28027)
*
* The sensor's output pin goes to HIGH if motion is present.
* However, even if motion is present it goes to LOW from time to time,
* which might give the impression no motion is present.
* This program deals with this issue by ignoring LOW-phases shorter than a given time,
* assuming continuous motion is present during these phases.
*
*/

/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

//the time when the sensor outputs a low impulse


long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low


//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;


boolean takeLowTime;

int pirPin = 7; //the digital pin connected to the PIR sensor's output
int ledPin = 13;
/////////////////////////////
//SETUP
void setup(){
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(pirPin, LOW);

//give the sensor some time to calibrate


Serial.print("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++){
Serial.print(".");
delay(1000);
}
Serial.println(" done");
Serial.println("SENSOR ACTIVE");
delay(50);
}

////////////////////////////
//LOOP
void loop(){

if(digitalRead(pirPin) == HIGH){
digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state
if(lockLow){
//makes sure we wait for a transition to LOW before any further output is made:
lockLow = false;
Serial.println("---");
Serial.print("motion detected at ");
Serial.print(millis()/1000);
Serial.println(" sec");
delay(50);
}
takeLowTime = true;
}

if(digitalRead(pirPin) == LOW){
digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state

if(takeLowTime){
lowIn = millis(); //save the time of the transition from high to LOW
takeLowTime = false; //make sure this is only done at the start of a LOW phase
}
//if the sensor is low for more than the given pause,
//we assume that no more motion is going to happen
if(!lockLow && millis() - lowIn > pause){
//makes sure this block of code is only executed again after
//a new motion sequence has been detected
lockLow = true;
Serial.print("motion ended at "); //output
Serial.print((millis() - pause)/1000);
Serial.println(" sec");
delay(50);
}
}
}

=================================================================
//int rainsense= 0; // analog sensor input pin 0
const int pinSpeaker = 11; // buzzer output
//int countval= 0; // counter value starting from 0
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

//the time when the sensor outputs a low impulse


long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low


//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;


boolean takeLowTime;

int pirPin = 7; //the digital pin connected to the PIR sensor's output
int ledPin = 13;

/////////////////////////////
//SETUP
void setup(){
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(pirPin, LOW);
pinMode(pinSpeaker, OUTPUT);

//give the sensor some time to calibrate


Serial.print("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++){
Serial.print(".");
delay(1000);
}
Serial.println(" done");
Serial.println("SENSOR ACTIVE");
delay(50);
}

////////////////////////////
//LOOP
void loop(){

if(digitalRead(pirPin) == HIGH){
digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state
alarm();
if(lockLow){
//makes sure we wait for a transition to LOW before any further output is made:
lockLow = false;
Serial.println("---");
Serial.print("motion detected at ");
Serial.print(millis()/1000);
Serial.println(" sec");
delay(50);
}
takeLowTime = true;
}

if(digitalRead(pirPin) == LOW){
digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state
noTone(pinSpeaker);
if(takeLowTime){
lowIn = millis(); //save the time of the transition from high to LOW
takeLowTime = false; //make sure this is only done at the start of a LOW phase
}
//if the sensor is low for more than the given pause,
//we assume that no more motion is going to happen
if(!lockLow && millis() - lowIn > pause){
//makes sure this block of code is only executed again after
//a new motion sequence has been detected
lockLow = true;
Serial.print("motion ended at "); //output
Serial.print((millis() - pause)/1000);
Serial.println(" sec");
delay(50);
}
}
}
void alarm(){
tone(pinSpeaker,NOTE_C4, 500);
delay(500);
tone(pinSpeaker,NOTE_D4, 500);
delay(500);
}

---------------------------------------------------------------------------------------------------------

// Uses a PIR sensor to detect movement, buzzes a buzzer


// more info here: http://blog.makezine.com/projects/pir-sensor-arduino-alarm/
// email me, John Park, at [email protected]
// based upon:
// PIR sensor tester by Limor Fried of Adafruit
// tone code by [email protected]

int ledPin = 13; // choose the pin for the LED


int inputPin = 7; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
int pinSpeaker = 11; //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(pinSpeaker, OUTPUT);
Serial.begin(9600);
}

void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
playTone(300, 160);
delay(150);

if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
playTone(0, 0);
delay(300);
if (pirState == HIGH){
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}

===================================================================
76. SAKLAR SENTUH

#include <CapacitiveSensor.h>
int OUTPUT_PIN = 11; //PWM pin
CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2); // 10M resistor between pins 4 & 2, pin 2 is
sensor pin, add a wire and or foil if desired
void setup() {
cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate on channel 1 - just as an
example
Serial.begin(9600);
pinMode(OUTPUT_PIN, OUTPUT);
}
int on = 0;
unsigned long last = millis();
void loop() {
long start = millis();
long total1 = cs_4_2.capacitiveSensor(30);

if (total1 >= 1000) {//this value can be adjusted for get desired sensitivity
//==============================
if (millis() - last > 250) {
on = !on;
analogWrite(OUTPUT_PIN, on ? 255 : 0);
//digitalWrite(OUTPUT_PIN, on ? HIGH : LOW); if do not want adjustable speed
}
last = millis();
//===================================================
}
Serial.println(total1);
delay(100);
}
77. SENSOR INFRAMERAH

// IR Obstacle Collision Detection Module


// Henry's Bench

int LED = 13; // Use the onboard Uno LED


int isObstaclePin = 7; // This is our input pin
int isObstacle = HIGH; // HIGH MEANS NO OBSTACLE

void setup() {
pinMode(LED, OUTPUT);
pinMode(isObstaclePin, INPUT);
Serial.begin(9600);

void loop() {
isObstacle = digitalRead(isObstaclePin);
if (isObstacle == LOW)
{
Serial.println("OBSTACLE!!, OBSTACLE!!");
digitalWrite(LED, HIGH);
}
else
{
Serial.println("clear");
digitalWrite(LED, LOW);
}
delay(200);
}
78. PENGUKURAN TEGANGAN DC, KUAT ARUS, DAYA

#include <Wire.h>
#include <Adafruit_INA219.h> // You will need to download this library

Adafruit_INA219 sensor219; // Declare and instance of INA219

void setup(void)
{
Serial.begin(9600);
sensor219.begin();
}
void loop(void)
{
float busVoltage = 0;
float current = 0; // Measure in milli amps
float power = 0;
busVoltage = sensor219.getBusVoltage_V();
current = sensor219.getCurrent_mA();
power = busVoltage * (current); // Calculate the Power
Serial.print("Bus Voltage: ");
Serial.print(busVoltage);
Serial.print(" V ");

Serial.print("Current: ");
Serial.print(current);
Serial.print(" mA ");

Serial.print("Power: ");
Serial.print(power);
Serial.println(" mW");
//Serial.println("");
delay(1000);
}

----------------------------------------------------------------------------------------------------------

#include <Wire.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;
void setup()
{
uint32_t currentFrequency;
Serial.begin(9600);
Serial.println("Hello!");
Serial.println("Measuring voltage and current with INA219 ...");
ina219.begin();
pinMode(2,OUTPUT);
}
void loop()
{
digitalWrite(2,HIGH);
float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float loadvoltage = 0;
float power = 0;
shuntvoltage = ina219.getShuntVoltage_mV();
busvoltage = ina219.getBusVoltage_V();
current_mA = ina219.getCurrent_mA();
loadvoltage = busvoltage + (shuntvoltage / 1000);
power = current_mA * loadvoltage;
Serial.print("Bus Voltage: ");
Serial.print(busvoltage);
Serial.print(" V ");
Serial.print("Shunt Voltage: ");
Serial.print(shuntvoltage);
Serial.print(" mV ");
Serial.print("Load Voltage: ");
Serial.print(loadvoltage);
Serial.print(" V ");
Serial.print("Current: ");
Serial.print(current_mA);
Serial.print(" mA ");
Serial.print("Power: ");
Serial.print(power);
Serial.print(" mW");
Serial.println("");
delay(1000);
}
79. ETHERNET SHIELD

Untuk dapat menggunakan ethernet shield kita harus mendapatkan IP address dahulu. Sambungkan
kabel LAN ke shield dan upload sket di bawah, IP dapat kita baca pada serial monitor. Pin yang
dipakai ethernet adalah pin 10, 11, 12, 13, jadi pin-pin tersebut tidak dapat digunakan lagi.

/*
DHCP-based IP printer

This sketch uses the DHCP extensions to the Ethernet library


to get an IP address via DHCP and print the address obtained.
using an Arduino Wiznet Ethernet shield.

Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13

created 12 April 2011


modified 9 Apr 2012
by Tom Igoe

*/

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.


// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };

// Initialize the Ethernet client library


// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// this check is only needed on the Leonardo:
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}

// start the Ethernet connection:


if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for(;;)
;
}
// print your local IP address:
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}

void loop() {

===============================================================
80. MENYALAKAN LED VIA BROWSER

Sket di bawah ini adalah menyalakan dan mematikan lampu LED melalui jaringan LAN lokal

/*
Web Server Demo
thrown together by Randy Sarafan

Allows you to turn on and off an LED by entering different urls.

To turn it on:
http://your-IP-address/$1

To turn it off:
http://your-IP-address/$2

Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Connect an LED to pin D2 and put it in series with a 220 ohm resistor to ground

Based almost entirely upon Web Server by Tom Igoe and David Mellis

Edit history:
created 18 Dec 2009
by David A. Mellis
modified 4 Sep 2010
by Tom Igoe

*/

#include <SPI.h>
#include <Ethernet.h>

boolean incoming = 0;

// Enter a MAC address and IP address for your controller below.


// The IP address will be dependent on your local network:
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDA, 0x02 };
IPAddress ip(192,168,1,126); //<<< ENTER YOUR IP ADDRESS HERE!!!

// Initialize the Ethernet server library


// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

// start the Ethernet connection and the server:


Ethernet.begin(mac, ip);
server.begin();
Serial.begin(9600);
}

void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply

//reads URL string from $ to first blank space


if(incoming && c == ' '){
incoming = 0;
}
if(c == '$'){
incoming = 1;
}

//Checks for the URL string $1 or $2


if(incoming == 1){
Serial.println(c);

if(c == '1'){
Serial.println("ON");
digitalWrite(2, HIGH);
}
if(c == '2'){
Serial.println("OFF");
digitalWrite(2, LOW);
}

if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}

================================================================
81. SWITCH LED DAN SERVO MOTOR VIA HTML

Pada sket di bawah adalah mendemonstrasikan pengontrolan LED dan servo motor via halaman
HTML. Untuk membuka halaman web, ketikkan http://192.168.1.126 , atau sesuai IP address yang
digunakan.

/*
Created by Rui Santos
Visit: http://randomnerdtutorials.com for more arduino projects

Arduino with Ethernet Shield


*/

#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>
int led = 2;
Servo microservo;
int pos = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 126 }; // ip in lan (that's what you need to use in your
browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port
String readString;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(led, OUTPUT);
microservo.attach(7);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}

void loop() {
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();

//read char by char HTTP request


if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}

//if HTTP request has ended


if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging

client.println("HTTP/1.1 200 OK"); //send new page


client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-
translucent' />");
client.println("<link rel='stylesheet' type='text/css'
href='http://randomnerdtutorials.com/ethernetcss.css' />");
client.println("<TITLE>Random Nerd Tutorials Project</TITLE>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<H1>Random Nerd Tutorials Project</H1>");
client.println("<hr />");
client.println("<br />");
client.println("<H2>Arduino with Ethernet Shield</H2>");
client.println("<br />");
client.println("<a href=\"/?button1on\"\">Turn On LED</a>");
client.println("<a href=\"/?button1off\"\">Turn Off LED</a><br />");
client.println("<br />");
client.println("<br />");
client.println("<a href=\"/?button2on\"\">Rotate Left</a>");
client.println("<a href=\"/?button2off\"\">Rotate Right</a><br />");
client.println("<p>Created by Rui Santos. Visit http://randomnerdtutorials.com for more
projects!</p>");
client.println("<br />");
client.println("</BODY>");
client.println("</HTML>");

delay(1);
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf("?button1on") >0){
digitalWrite(led, HIGH);
}
if (readString.indexOf("?button1off") >0){
digitalWrite(led, LOW);
}
if (readString.indexOf("?button2on") >0){
for(pos = 0; pos < 180; pos += 3) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if (readString.indexOf("?button2off") >0){
for(pos = 180; pos>=1; pos-=3) // goes from 180 degrees to 0 degrees
{
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//clearing string for next read
readString="";

}
}
}
}
}
82. MEMBACA INPUT ANALOG VIA BROWSER

Pada sket di bawah adalah pembacaan signal analog melalui web browser. Untuk membuka
halaman web, ketikkan http://192.168.1.126 , atau sesuai IP address yang digunakan.

/*
Web Server

A simple web server that shows the value of the analog input pins.
using an Arduino Wiznet Ethernet shield.

Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* Analog inputs attached to pins A0 through A5 (optional)

created 18 Dec 2009


by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

*/

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.


// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,126);

// Initialize the Ethernet server library


// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}

// start the Ethernet connection and the server:


Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}

void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the
response
client.println("Refresh: 1"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
83. ETHERNET SHIELD MULTI SWITCH

Pada sket ini didemonstrasikan penggunaan ethernet shield untuk menyalahan atau mematikan
beberapa LED. Untuk penerapan yang lebih lanjut LED ini dapat diganti dengan relay, yang
selanjutnya dari relay ini kita dapat mengendalikan alat-alat listrik dengan tegangan lebih tinggi.

/*
Created by Rui Santos
Visit: http://randomnerdtutorials.com for more arduino projects

Arduino with Ethernet Shield


*/

#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 8;
int led7 = 9;
int led8 = 7;
Servo microservo;
int pos = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 126 }; // ip in lan (that's what you need to use in your
browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port
String readString;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
pinMode(led6, OUTPUT);
pinMode(led7, OUTPUT);
pinMode(led8, OUTPUT);

microservo.attach(14);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}

void loop() {
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();

//read char by char HTTP request


if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}

//if HTTP request has ended


if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging

client.println("HTTP/1.1 200 OK"); //send new page


client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");

client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");


client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-
translucent' />");
client.println("<link rel='stylesheet' type='text/css'
href='http://randomnerdtutorials.com/ethernetcss.css' />");

client.println("<TITLE>WEB SWITCH</TITLE>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<H1>WEB SWITCH</H1>");
client.println("<hr />");
client.println("<br />");
//client.println("<H2>Arduino with Ethernet Shield</H2>");
client.println("<br />");
client.println("<a href=\"/?button1on\"\">LAMPU 1 ON</a>");
//client.println("<a>|</a>");
client.println("<a href=\"/?button2on\"\">LAMPU 2 ON</a>");
client.println("<a href=\"/?button3on\"\">LAMPU 3 ON</a>");
client.println("<a href=\"/?button4on\"\">LAMPU 4 ON</a>");
client.println("<a href=\"/?button5on\"\">LAMPU 5 ON</a>");
client.println("<a href=\"/?button6on\"\">LAMPU 6 ON</a>");
client.println("<a href=\"/?button7on\"\">LAMPU 7 ON</a>");
client.println("<a href=\"/?button8on\"\">LAMPU 8 ON</a>");
client.println("<br />");
client.println("<br />");
client.println("<a href=\"/?button1off\"\">LAMPU 1 OFF</a>");
client.println("<a href=\"/?button2off\"\">LAMPU 2 OFF</a>");
client.println("<a href=\"/?button3off\"\">LAMPU 3 OFF</a>");
client.println("<a href=\"/?button4off\"\">LAMPU 4 OFF</a>");
client.println("<a href=\"/?button5off\"\">LAMPU 5 OFF</a>");
client.println("<a href=\"/?button6off\"\">LAMPU 6 OFF</a>");
client.println("<a href=\"/?button7off\"\">LAMPU 7 OFF</a>");
client.println("<a href=\"/?button8off\"\">LAMPU 8 OFF</a>");
client.println("<br />");
client.println("<br />");
client.println("<a href=\"/?button9on\"\">Rotate Left</a>");
client.println("<a href=\"/?button9off\"\">Rotate Right</a><br />");
client.println("<br />");
client.println("<hr />");
//client.println("<p>Created by Rui Santos. Visit http://randomnerdtutorials.com for more
projects!</p>");
client.println("<br />");
client.println("</BODY>");
client.println("</HTML>");

delay(1);
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf("?button1on") >0){
digitalWrite(led1, HIGH);
}
if (readString.indexOf("?button1off") >0){
digitalWrite(led1, LOW);
}
if (readString.indexOf("?button2on") >0){
digitalWrite(led2, HIGH);
}
if (readString.indexOf("?button2off") >0){
digitalWrite(led2, LOW);
}
if (readString.indexOf("?button3on") >0){
digitalWrite(led3, HIGH);
}
if (readString.indexOf("?button3off") >0){
digitalWrite(led3, LOW);
}
if (readString.indexOf("?button4on") >0){
digitalWrite(led4, HIGH);
}
if (readString.indexOf("?button4off") >0){
digitalWrite(led4, LOW);
}
if (readString.indexOf("?button5on") >0){
digitalWrite(led5, HIGH);
}
if (readString.indexOf("?button5off") >0){
digitalWrite(led5, LOW);
}
if (readString.indexOf("?button6on") >0){
digitalWrite(led6, HIGH);
}
if (readString.indexOf("?button6off") >0){
digitalWrite(led6, LOW);
}
if (readString.indexOf("?button7on") >0){
digitalWrite(led7, HIGH);
}
if (readString.indexOf("?button7off") >0){
digitalWrite(led7, LOW);
}
if (readString.indexOf("?button8on") >0){
digitalWrite(led8, HIGH);
}
if (readString.indexOf("?button8off") >0){
digitalWrite(led8, LOW);
}
if (readString.indexOf("?button9on") >0){
for(pos = 0; pos < 180; pos += 3) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if (readString.indexOf("?button9off") >0){
for(pos = 180; pos>=1; pos-=3) // goes from 180 degrees to 0 degrees
{
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//clearing string for next read
readString="";

}
}
}
}
}

===================================================================
Sket lain :

/*
Created by Rui Santos
Visit: http://randomnerdtutorials.com for more arduino projects

Arduino with Ethernet Shield


*/

#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 8;
int led7 = 9;
int led8 = 7;
Servo microservo;
int pos = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 126 }; // ip in lan (that's what you need to use in your
browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port
String readString;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
pinMode(led6, OUTPUT);
pinMode(led7, OUTPUT);
pinMode(led8, OUTPUT);

microservo.attach(14);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}

void loop() {
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();

//read char by char HTTP request


if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}

//if HTTP request has ended


if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging

client.println("HTTP/1.1 200 OK"); //send new page


client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");
/*
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-
translucent' />");
*/
client.println("<link rel='stylesheet' type='text/css'
href='http://randomnerdtutorials.com/ethernetcss.css' />");

client.println("<TITLE>WEB SWITCH</TITLE>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<H1>WEB SWITCH</H1>");
client.println("<hr />");
client.println("<br />");
//client.println("<H2>Arduino with Ethernet Shield</H2>");
client.println("<br />");
client.println("<a href=\"/?button1on\"\">LAMPU 1 ON</a>");
//client.println("<a>|</a>");
client.println("<a href=\"/?button2on\"\">LAMPU 2 ON</a>");
client.println("<a href=\"/?button3on\"\">LAMPU 3 ON</a>");
client.println("<a href=\"/?button4on\"\">LAMPU 4 ON</a>");
client.println("<a href=\"/?button5on\"\">LAMPU 5 ON</a>");
client.println("<a href=\"/?button6on\"\">LAMPU 6 ON</a>");
client.println("<a href=\"/?button7on\"\">LAMPU 7 ON</a>");
client.println("<a href=\"/?button8on\"\">LAMPU 8 ON</a>");
client.println("<br />");
client.println("<br />");
client.println("<a href=\"/?button1off\"\">LAMPU 1 OFF</a>");
client.println("<a href=\"/?button2off\"\">LAMPU 2 OFF</a>");
client.println("<a href=\"/?button3off\"\">LAMPU 3 OFF</a>");
client.println("<a href=\"/?button4off\"\">LAMPU 4 OFF</a>");
client.println("<a href=\"/?button5off\"\">LAMPU 5 OFF</a>");
client.println("<a href=\"/?button6off\"\">LAMPU 6 OFF</a>");
client.println("<a href=\"/?button7off\"\">LAMPU 7 OFF</a>");
client.println("<a href=\"/?button8off\"\">LAMPU 8 OFF</a>");
client.println("<br />");
client.println("<br />");
client.println("<a href=\"/?button9on\"\">Rotate Left</a>");
client.println("<a href=\"/?button9off\"\">Rotate Right</a><br />");
client.println("<br />");
client.println("<a href=\"/?allon\"\">ALL ON</a>");
client.println("<a href=\"/?alloff\"\">ALL OFF</a>");
client.println("<br />");
client.println("<br />");
client.println("<hr />");
//client.println("<p>Created by Rui Santos. Visit http://randomnerdtutorials.com for more
projects!</p>");
client.println("<br />");
client.println("</BODY>");
client.println("</HTML>");

delay(1);
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf("?button1on") >0){
digitalWrite(led1, HIGH);

}
if (readString.indexOf("?button1off") >0){
digitalWrite(led1, LOW);

}
if (readString.indexOf("?button2on") >0){
digitalWrite(led2, HIGH);
}
if (readString.indexOf("?button2off") >0){
digitalWrite(led2, LOW);
}
if (readString.indexOf("?button3on") >0){
digitalWrite(led3, HIGH);
}
if (readString.indexOf("?button3off") >0){
digitalWrite(led3, LOW);
}
if (readString.indexOf("?button4on") >0){
digitalWrite(led4, HIGH);
}
if (readString.indexOf("?button4off") >0){
digitalWrite(led4, LOW);
}
if (readString.indexOf("?button5on") >0){
digitalWrite(led5, HIGH);
}
if (readString.indexOf("?button5off") >0){
digitalWrite(led5, LOW);
}
if (readString.indexOf("?button6on") >0){
digitalWrite(led6, HIGH);
}
if (readString.indexOf("?button6off") >0){
digitalWrite(led6, LOW);
}
if (readString.indexOf("?button7on") >0){
digitalWrite(led7, HIGH);
}
if (readString.indexOf("?button7off") >0){
digitalWrite(led7, LOW);
}
if (readString.indexOf("?button8on") >0){
digitalWrite(led8, HIGH);
}
if (readString.indexOf("?button8off") >0){
digitalWrite(led8, LOW);
}

if (readString.indexOf("?allon") >0){
digitalWrite(led1, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led5, HIGH);
digitalWrite(led6, HIGH);
digitalWrite(led7, HIGH);
digitalWrite(led8, HIGH);

}
if (readString.indexOf("?alloff") >0){

digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
digitalWrite(led5, LOW);
digitalWrite(led6, LOW);
digitalWrite(led7, LOW);
digitalWrite(led8, LOW);

if (readString.indexOf("?button9on") >0){
for(pos = 0; pos < 180; pos += 3) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
if (readString.indexOf("?button9off") >0){
for(pos = 180; pos>=1; pos-=3) // goes from 180 degrees to 0 degrees
{
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//clearing string for next read
readString="";

}
}
}
}
}

====================================================================
84. ETHERNET SHIELD MULTI SWITCH DENGAN TELNET

#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>

// Enter a MAC address and IP address for your controller below.


// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,126);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255, 255, 255, 0);

EthernetServer server(23);// Telnet defaults to port 23


boolean alreadyConnected = false; // whether or not the client was connected previously

int ledPin1 = 2;
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 5;
int ledPin5 = 6;
int ledPin6 = 7;
int ledPin7 = 8;
int ledPin8 = 9;
Servo microservo;
int pos = 0;
String commandString;

void setup() {

pinMode(ledPin1, OUTPUT); // sets the digital pin as output


pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
pinMode(ledPin6, OUTPUT);
pinMode(ledPin7, OUTPUT);
pinMode(ledPin8, OUTPUT);
microservo.attach(14);
Ethernet.begin(mac, ip, gateway, subnet); // initialize the ethernet device
server.begin();// start listening for clients
Serial.begin(9600);// Open serial communications and wait for port to open:
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only

Serial.print("Chat server address:");


Serial.println(Ethernet.localIP());
}

void loop() {

// wait for a new client:


EthernetClient client = server.available();

// when the client sends the first byte, say hello:


if (client) {
if (!alreadyConnected) {
// clear out the input buffer:
client.flush();
commandString = ""; //clear the commandString variable

server.println("--> Please type your command and hit Return...");


alreadyConnected = true;
}

while (client.available()) {

char newChar = client.read(); // read the bytes incoming from the client:

if (newChar == 0x0D) //If a 0x0D is received, a Carriage Return, then evaluate the command
{
server.print("Received this command: ");
server.println(commandString);
processCommand(commandString);
} else
{
Serial.println(newChar);
commandString += newChar;
}

}
}
}

void processCommand(String command)


{
server.print("Processing command ");
server.println(command);

if (command.indexOf("turn1") > -1){


Serial.println("Servo command received");
server.print("Turn to 180 " );
for(pos = 180; pos>=1; pos-=3) // goes from 180 degrees to 0 degrees
{
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
} //Print the integer returned by analogRead to the server object
commandString = "";
return;
}
if (command.indexOf("turn2") > -1){
Serial.println("Servo command received");
server.print("Turn to 0 " );
for(pos = 0; pos < 180; pos += 3) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
microservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
} //Print the integer returned by analogRead to the server object
commandString = "";
return;
}

if (command.indexOf("led1on") > -1){


server.println("LED1 On command received");
digitalWrite(ledPin1, HIGH); // sets the LED on
server.println("LED1 was turned on");
commandString = "";
return;
}

if (command.indexOf("led1off") > -1){


Serial.println("LED1 Off command received");
digitalWrite(ledPin1, LOW); // sets the LED off
server.println("LED1 was turned off");
commandString = "";
return;
}
if (command.indexOf("led2on") > -1){
server.println("LED2 On command received");
digitalWrite(ledPin2, HIGH); // sets the LED on
server.println("LED2 was turned on");
commandString = "";
return;
}

if (command.indexOf("led2off") > -1){


Serial.println("LED2 Off command received");
digitalWrite(ledPin2, LOW); // sets the LED off
server.println("LED2 was turned off");
commandString = "";
return;
}
if (command.indexOf("led3on") > -1){
server.println("LED3 On command received");
digitalWrite(ledPin3, HIGH); // sets the LED on
server.println("LED3 was turned on");
commandString = "";
return;
}

if (command.indexOf("led3off") > -1){


Serial.println("LED3 Off command received");
digitalWrite(ledPin3, LOW); // sets the LED off
server.println("LED3 was turned off");
commandString = "";
return;
}

if (command.indexOf("led4on") > -1){


server.println("LED4 On command received");
digitalWrite(ledPin4, HIGH); // sets the LED on
server.println("LED4 was turned on");
commandString = "";
return;
}

if (command.indexOf("led4off") > -1){


Serial.println("LED4 Off command received");
digitalWrite(ledPin4, LOW); // sets the LED off
server.println("LED4 was turned off");
commandString = "";
return;
}
if (command.indexOf("led5on") > -1){
server.println("LED5 On command received");
digitalWrite(ledPin5, HIGH); // sets the LED on
server.println("LED5 was turned on");
commandString = "";
return;
}

if (command.indexOf("led5off") > -1){


Serial.println("LED5 Off command received");
digitalWrite(ledPin5, LOW); // sets the LED off
server.println("LED5 was turned off");
commandString = "";
return;
}
if (command.indexOf("led6on") > -1){
server.println("LED6 On command received");
digitalWrite(ledPin6, HIGH); // sets the LED on
server.println("LED6 was turned on");
commandString = "";
return;
}

if (command.indexOf("led6off") > -1){


Serial.println("LED6 Off command received");
digitalWrite(ledPin6, LOW); // sets the LED off
server.println("LED6 was turned off");
commandString = "";
return;
}
if (command.indexOf("led7on") > -1){
server.println("LED7 On command received");
digitalWrite(ledPin7, HIGH); // sets the LED on
server.println("LED7 was turned on");
commandString = "";
return;
}

if (command.indexOf("led7off") > -1){


Serial.println("LED7 Off command received");
digitalWrite(ledPin7, LOW); // sets the LED off
server.println("LED7 was turned off");
commandString = "";
return;
}
if (command.indexOf("led8on") > -1){
server.println("LED8 On command received");
digitalWrite(ledPin8, HIGH); // sets the LED on
server.println("LED8 was turned on");
commandString = "";
return;
}

if (command.indexOf("led8off") > -1){


Serial.println("LED8 Off command received");
digitalWrite(ledPin8, LOW); // sets the LED off
server.println("LED8 was turned off");
commandString = "";
return;
}
if (command.indexOf("Allon") > -1){
server.println("All LED On command received");
digitalWrite(ledPin1, HIGH); // sets the LED on
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, HIGH);
digitalWrite(ledPin5, HIGH);
digitalWrite(ledPin6, HIGH);
digitalWrite(ledPin7, HIGH);
digitalWrite(ledPin8, HIGH);
server.println("All LEDs were turned on");
commandString = "";
return;
}
if (command.indexOf("Alloff") > -1){
Serial.println("All LED Off command received");
digitalWrite(ledPin1, LOW); // sets the LED off
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, LOW);
digitalWrite(ledPin6, LOW);
digitalWrite(ledPin7, LOW);
digitalWrite(ledPin8, LOW);
server.println("All LEDs were turned off");
commandString = "";
return;
}

commandString = "";
instructions();
}

void instructions()
{
/*
server.println("I don't understand");
server.println("Please use one of these commands:");
server.println("* pot, to get a reading from the potentiomet");
server.println("* ledon, to turn on the LED");
server.println("* ledoff, to turn off the LED");
*/
server.println("I don't understand");
/*
server.println("Please use one of these commands:");
server.println("* turn1, to servo turn to 180");
server.println("* turn2, to servo turn to 0");
server.println("* led1on, to turn on the LED1");
server.println("* led1off, to turn off the LED1");
server.println("* led2on, to turn on the LED1");
server.println("* led2off, to turn off the LED1");
server.println("* led3on, to turn on the LED1");
server.println("* led3off, to turn off the LED1");
server.println("* led4on, to turn on the LED1");
server.println("* led4off, to turn off the LED1");
server.println("* led5on, to turn on the LED1");
server.println("* led5off, to turn off the LED1");
server.println("* led6on, to turn on the LED1");
server.println("* led6off, to turn off the LED1");
server.println("* led7on, to turn on the LED1");
server.println("* led7off, to turn off the LED1");
server.println("* led8on, to turn on the LED1");
server.println("* led8off, to turn off the LED1");
*/
}

Hasil sket ini dapat dibuka dengan telnet, ketikkan “telnet 192.168.1.126” atau sesuai dengan IP
address yang dipakai, lalu untuk menjalankan perintah ketikkan comand : led1on untuk menyalakan
LED 1, led1off untuk mematikan LED1, Allon untuk menyalan secara bersama-sama, dan
seterusnya sesuai comand pada bagian “if”.

===========================================================
85. MAGNETOMETER HMC5883L

#include <Wire.h>
#include <HMC5883L.h>

HMC5883L compass;

void setup()
{
Wire.begin();
Serial.begin(9600);
compass = HMC5883L();

Serial.println("Setting scale to +/- 1.3Ga");


int error = compass.SetScale(1.3);
if(error != 0)
Serial.println(compass.GetErrorText(error));

Serial.println("Setting measurement mode to continuous");


error = compass.SetMeasurementMode(Measurement_Continuous);
if(error != 0)
Serial.println(compass.GetErrorText(error));
}

void loop()
{
MagnetometerRaw raw = compass.ReadRawAxis();
float heading = atan2(raw.YAxis, raw.XAxis);
if(heading < 0)
heading += 2*PI;
float headingDegrees = heading * 180/M_PI;
Serial.println(headingDegrees);
delay(100);
}

-----------------------------------------------------------------------------------------------------------

#include <Wire.h>
#include <HMC5883L.h>

HMC5883L compass;
int i;
float X_tot, Y_tot, Z_tot;
float X,Y,Z;
void setup()
{
Wire.begin();
Serial.begin(9600);
compass = HMC5883L();

Serial.println("Setting scale to +/- 1.3Ga");


int error = compass.SetScale(1.3);
if(error != 0)
Serial.println(compass.GetErrorText(error));

Serial.println("Setting measurement mode to continuous");


error = compass.SetMeasurementMode(Measurement_Continuous);
if(error != 0)
Serial.println(compass.GetErrorText(error));

i = 0;
X_tot = 0;
Y_tot = 0;
Z_tot = 0;
X = 0; Y = 0; Z = 0;
}

void loop()
{
MagnetometerRaw raw = compass.ReadRawAxis();
if(i<499){
X_tot += raw.XAxis;
Y_tot += raw.YAxis;
Z_tot += raw.ZAxis;
}else{
X = X_tot/500;
Y = Y_tot/500;
Z = Z_tot/500;
X_tot = 0; Y_tot = 0; Z_tot = 0;
i = 0;
Serial.print(i+":\t");
Serial.print(X);
Serial.print(" ");
Serial.print(Y);
Serial.print(" ");
Serial.print(Z);
Serial.println(" ");
delay(10);
}
i++;
}

------------------------------------------------------------------------------------------------------------

/* Arduino Compass
*
* by Dejan Nedelkovski,
* www.HowToMechatronics.com
*
*/
#include <Wire.h> //I2C Arduino Library
#define Magnetometer_mX0 0x03
#define Magnetometer_mX1 0x04
#define Magnetometer_mZ0 0x05
#define Magnetometer_mZ1 0x06
#define Magnetometer_mY0 0x07
#define Magnetometer_mY1 0x08
int mX0, mX1, mX_out;
int mY0, mY1, mY_out;
int mZ0, mZ1, mZ_out;
float heading, headingDegrees, headingFiltered, declination;
float Xm,Ym,Zm;
#define Magnetometer 0x1E //I2C 7bit address of HMC5883
void setup(){
//Initialize Serial and I2C communications
Serial.begin(9600);
Wire.begin();
delay(100);

Wire.beginTransmission(Magnetometer);
Wire.write(0x02); // Select mode register
Wire.write(0x00); // Continuous measurement mode
Wire.endTransmission();
}
void loop(){

//---- X-Axis
Wire.beginTransmission(Magnetometer); // transmit to device
Wire.write(Magnetometer_mX1);
Wire.endTransmission();
Wire.requestFrom(Magnetometer,1);
if(Wire.available()<=1)
{
mX0 = Wire.read();
}
Wire.beginTransmission(Magnetometer); // transmit to device
Wire.write(Magnetometer_mX0);
Wire.endTransmission();
Wire.requestFrom(Magnetometer,1);
if(Wire.available()<=1)
{
mX1 = Wire.read();
}
//---- Y-Axis
Wire.beginTransmission(Magnetometer); // transmit to device
Wire.write(Magnetometer_mY1);
Wire.endTransmission();
Wire.requestFrom(Magnetometer,1);
if(Wire.available()<=1)
{
mY0 = Wire.read();
}
Wire.beginTransmission(Magnetometer); // transmit to device
Wire.write(Magnetometer_mY0);
Wire.endTransmission();
Wire.requestFrom(Magnetometer,1);
if(Wire.available()<=1)
{
mY1 = Wire.read();
}

//---- Z-Axis
Wire.beginTransmission(Magnetometer); // transmit to device
Wire.write(Magnetometer_mZ1);
Wire.endTransmission();
Wire.requestFrom(Magnetometer,1);
if(Wire.available()<=1)
{
mZ0 = Wire.read();
}
Wire.beginTransmission(Magnetometer); // transmit to device
Wire.write(Magnetometer_mZ0);
Wire.endTransmission();
Wire.requestFrom(Magnetometer,1);
if(Wire.available()<=1)
{
mZ1 = Wire.read();
}

//---- X-Axis
mX1=mX1<<8;
mX_out =mX0+mX1; // Raw data
// From the datasheet: 0.92 mG/digit
Xm = mX_out*0.00092; // Gauss unit
//* Earth magnetic field ranges from 0.25 to 0.65 Gauss, so these are the values that we need to get
approximately.
//---- Y-Axis
mY1=mY1<<8;
mY_out =mY0+mY1;
Ym = mY_out*0.00092;
//---- Z-Axis
mZ1=mZ1<<8;
mZ_out =mZ0+mZ1;
Zm = mZ_out*0.00092;
// ==============================
//Calculating Heading
heading = atan2(Ym, Xm);

// Correcting the heading with the declination angle depending on your location
// You can find your declination angle at: http://www.ngdc.noaa.gov/geomag-web/
// At my location it's 4.2 degrees => 0.073 rad
declination = 0.073;
heading += declination;

// Correcting when signs are reveresed


if(heading <0) heading += 2*PI;
// Correcting due to the addition of the declination angle
if(heading > 2*PI)heading -= 2*PI;
headingDegrees = heading * 180/PI; // The heading in Degrees unit
// Smoothing the output angle / Low pass filter
headingFiltered = headingFiltered*0.85 + headingDegrees*0.15;
//Sending the heading value through the Serial Port to Processing IDE
Serial.println(headingFiltered);

delay(50);
}

-----------------------------------------------------------------------------------------------------------

/*
HMC5883L_Example.ino - Example sketch for integration with an HMC5883L triple axis
magnetometer.
Copyright (C) 2013 BluLemonLabs (bluelemonlabs.blogspot.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,


but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

*/

// Reference the I2C Library


#include <Wire.h>
// Reference the HMC5883L Compass Library
#include <HMC5883L.h>

// Store our compass as an object.


HMC5883L compass;

// Record any errors that may occur in the compass.


int error = 0;

// Out setup routine, here we will configure the microcontroller and compass.
void setup()
{
// Initialize the serial port.
Serial.begin(9600);

Serial.println("Starting the I2C interface.");


Wire.begin(); // Start the I2C interface.

Serial.println("Constructing new HMC5883L");


compass = HMC5883L(); // Construct a new HMC5883 compass.
//The implementation of the class is provided in the library

// Now we have an istance of the class!


//Let's initializate it...

Serial.println("Setting scale to +/- 1.3 Ga");


error = compass.SetScale(1.3); // Set the scale of the compass to 1.3Ga
if(error != 0){ // If there is an error, print it out.
Serial.println(compass.GetErrorText(error));
error =0;
}

Serial.println("Setting measurement mode to continous.");


error = compass.SetMeasurementMode(Measurement_Continuous); // Set the measurement mode
to Continuous
if(error != 0) {// If there is an error, print it out.
Serial.println(compass.GetErrorText(error)); //Todo: Error handling for this method in .h and .cpp
error=0;
}
}

// Our main program loop.


void loop()
{
// Retrieve the raw values from the magnetometer (not scaled).
MagnetometerRaw raw = compass.ReadRawAxis();
// Retrieve the scaled values from the magnetometer (scaled to the configured scale).
MagnetometerScaled scaled = compass.ReadScaledAxis();

// Values are accessed like so:


int MilliGauss_OnThe_XAxis = scaled.XAxis;// (or YAxis, or ZAxis)

// Calculate heading when the magnetometer is level, then correct for signs of axis.
// Atan2() automatically check the correct formula taking care of the quadrant you are in
float heading = atan2(scaled.YAxis, scaled.XAxis);

// Once you have your heading, you must then add your 'Declination Angle',
// which is the 'Error' of the magnetic field in your location. Mine is 0.0404
// Find yours here: http://www.magnetic-declination.com/

// If you cannot find your Declination, comment out these two lines, your compass will be slightly
off.
float declinationAngle = 0.0404;
heading += declinationAngle;

// Correct for when signs are reversed.


if(heading < 0)
heading += 2*PI;

// Check for wrap due to addition of declination.


if(heading > 2*PI)
heading -= 2*PI;

// Convert radians to degrees for readability.


float headingDegrees = heading * 180/M_PI;

// Output the data via the serial port.


Output(raw, scaled, heading, headingDegrees);

// By default the HMC5883L reads the data 15 time per second (15Hz)
// However since we have a long serial out (104ms at 9600) we will let
// it run at its natural speed.
// delay(66);
}

// Output the data down the serial port.


void Output(MagnetometerRaw raw, MagnetometerScaled scaled, float heading, float
headingDegrees)
{
Serial.print("Raw:\t");
Serial.print(raw.XAxis);
Serial.print(" ");
Serial.print(raw.YAxis);
Serial.print(" ");
Serial.print(raw.ZAxis);
Serial.print(" \tScaled:\t");

Serial.print(scaled.XAxis);
Serial.print(" ");
Serial.print(scaled.YAxis);
Serial.print(" ");
Serial.print(scaled.ZAxis);

Serial.print(" \tHeading:\t");
Serial.print(heading);
Serial.print(" Radians \t");
Serial.print(headingDegrees);
Serial.println(" Degrees \t");
}

=========================================================
86. ACCELEROMETER GY-61

/*
ADXL335
note:vcc-->5v ,but ADXL335 Vs is 3.3V
The circuit:
5V: VCC
analog 1: x-axis
analog 2: y-axis
analog 3: z-axis
*/
const int xpin = 1; // x-axis of the accelerometer
const int ypin = 2; // y-axis
const int zpin = 3; // z-axis (only on 3-axis models)
void setup()
{
// initialize the serial communications:
Serial.begin(9600);
}
void loop()
{
int x = analogRead(xpin); //read from xpin

int y = analogRead(ypin); //read from ypin

int z = analogRead(zpin); //read from zpin

float zero_G = 512.0; //ADC is 0~1023 the zero g output equal to Vs/2
//ADXL335 power supply by Vs 3.3V
float scale = 102.3; //ADXL335330 Sensitivity is 330mv/g
//330 * 1024/3.3/1000

Serial.print(x);
Serial.print(" ");
Serial.print(y);
Serial.print(" ");
Serial.print(z);
Serial.print(" ");
Serial.print(((float)x - 395)/65*9.8); //print x value on serial monitor
Serial.print(" ");
Serial.print(((float)y - 350)/68.5*9.8); //print y value on serial monitor
Serial.print(" ");
Serial.print(((float)z - 372)/68*9.8); //print z value on serial monitor
Serial.println(" ");
delay(100);
}

===================================================================
87. SEND DATA VIA BLUETOOTH

Module bluetooth ini pada dasarnya berguna untuk mengirim data yang tertampil pada monitor
serial ke klien atau pair. Data dari arduino dikirim melalui pin RX dan TX. Sebagai contoh kita
akan mengirim data pada pin A0,

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}

Pertama-tama kita lepas dahulu kabel pin TX dan RX dari arduino, kemudian kita upload kode di
atas, lalu kita sambungkan lagi kabel ke pin RX dan TX arduino, maka data telah dipancarkan lewat
bluetooth.

Untuk membaca data via bluetooth maka kita memerlukan komputer yang dapat mengakses signal
bluetooth. Jika kita menggunakan Windows 10, aktifkan bluetooth dengan cara klik ikon bluetooth
pada task bar ---> Show Bluetooth Devises, maka pada tampilan Manage Bluetooth devices akan
tertampil HC-05, klik lalu lakukan pair, akan diminta password, isikan 1234 sebagai password,
maka bluetooth siap diakses. Cara mengakses data yang terkirim via bluetooth dapat kita lakukan
dengan membuka Arduino IDE versi 1.6.xx. Arahkan port ke port yang digunakan oleh bluetooth,
kemudian buka serial monitor, maka data yang terkirim via bluetooth akan tertampil.
Cara lain untuk mengakses data via bluetooth ini adalah dengan sofware Tera Term, kita bisa
download secara gratis. Setelah kita install kita open maka akan tampil menu koneksi, pilih serial
serta pilih port yang dipakai bluetooth, maka data akan tertampil. Kelebihan Tera Term ini kita bisa
simpan data yang tertampil dengan cara data log ke suatu file notepad.

===================================================================
88. SERVO MOTOR

#include <Servo.h>

Servo head;
void setup()
{
head.attach(9);
head.write(80);

}
void loop(){
head.write(180);
delay(1000);
head.write(160);
delay(1000);
head.write(140);
delay(1000);
head.write(120);
delay(1000);
head.write(100);
delay(1000);
head.write(80);
delay(1000);
head.write(60);
delay(1000);
head.write(40);
delay(1000);
head.write(20);
delay(1000);
head.write(0);
delay(1000);

head.write(20);
delay(1000);
head.write(40);
delay(1000);
head.write(60);
delay(1000);
head.write(80);
delay(1000);
head.write(100);
delay(1000);
head.write(120);
delay(1000);
head.write(140);
delay(1000);
head.write(160);
delay(1000);

==================================================================

#include <Servo.h>

Servo leftRightServo; // set a variable to map the servo


int leftRightPos = 0; // set a variable to store the servo position
const int numReadings = 3; // set a variable for the number of readings to take
int index = 0; // the index of the current reading
int total = 0; // the total of all readings

/* setup the pins, servo and serial port */


void setup() {
leftRightServo.attach(9);

Serial.begin(9600);
}

/* begin rotating the servo and getting sensor values */


void loop() {
for(leftRightPos = 0; leftRightPos < 180; leftRightPos++) { // going left to right.
leftRightServo.write(leftRightPos);
for (index = 0; index<=numReadings;index++) { // take x number of readings from the
sensor and average them
delay(3);
}

Serial.print("X"); // print leading X to mark the following value as


degrees
Serial.println(leftRightPos); // current servo position

for(leftRightPos = 180; leftRightPos > 0; leftRightPos--) { // going right to left


leftRightServo.write(leftRightPos);
for (index = 0; index<=numReadings;index++) {

delay(3);
}

Serial.print("X");
Serial.println(leftRightPos);

}
}

=======================================================================

#include <Servo.h>
Servo leftRightServo; // set a variable to map the servo
int leftRightPos = 0; // set a variable to store the servo position
void setup() {
leftRightServo.attach(9);
Serial.begin(9600);
}
void loop() {
for(leftRightPos = 0; leftRightPos < 180; leftRightPos++) { // going left to right.
leftRightServo.write(leftRightPos);
Serial.print("X"); // print leading X to mark the following value as
degrees
Serial.println(leftRightPos); // current servo position
delay(50);
}
for(leftRightPos = 180; leftRightPos > 0; leftRightPos--) { // going right to left
leftRightServo.write(leftRightPos);
Serial.print("X");
Serial.println(leftRightPos);
delay(50);
}
}
89. SONAR ARDUINO

//Arduino Code
#include <Servo.h>
/*
code for arduino bord ultrasonic radar system.
*/
Servo leftRightServo; // set a variable to map the servo
int leftRightPos = 0; // set a variable to store the servo position
const int numReadings = 1; // set a variable for the number of readings to take
int index = 0; // the index of the current reading
int total = 0; // the total of all readings
int average = 0; // the average
int echoPin = 6; // the SRF05's echo pin
int initPin = 7; // the SRF05's init pin
unsigned long pulseTime = 0; // variable for reading the pulse
unsigned long distance = 0; // variable for storing distance
/* setup the pins, servo and serial port */
void setup() {
leftRightServo.attach(9);
// make the init pin an output:
pinMode(initPin, OUTPUT);
// make the echo pin an input:
pinMode(echoPin, INPUT);
// initialize the serial port:
Serial.begin(9600);
}
/* begin rotating the servo and getting sensor values */
void loop() {
for(leftRightPos = 0; leftRightPos < 180; leftRightPos++) { // going left to right.
leftRightServo.write(leftRightPos);
for (index = 0; index<=numReadings;index++) { // take x number of readings from the
sensor and average them
digitalWrite(initPin, LOW);
delayMicroseconds(50);
digitalWrite(initPin, HIGH); // send signal
delayMicroseconds(50); // wait 50 microseconds for it to return
digitalWrite(initPin, LOW); // close signal
pulseTime = pulseIn(echoPin, HIGH); // calculate time for signal to return
distance = pulseTime/58; // convert to centimetres
total = total + distance; // update total
delay(1);
}
average = total/numReadings; // create average reading

if (index >= numReadings) { // reset the counts when at the last item of the
array
index = 0;
total = 0;
}
Serial.print("X"); // print leading X to mark the following value as
degrees
Serial.print(leftRightPos); // current servo position
Serial.print("V"); // preceeding character to separate values
Serial.println(average); // average of sensor readings
}
/*
start going right to left after we got to 180 degrees
same code as above
*/
for(leftRightPos = 180; leftRightPos > 0; leftRightPos--) { // going right to left
leftRightServo.write(leftRightPos);
for (index = 0; index<=numReadings;index++) {
digitalWrite(initPin, LOW);
delayMicroseconds(50);
digitalWrite(initPin, HIGH);
delayMicroseconds(50);
digitalWrite(initPin, LOW);
pulseTime = pulseIn(echoPin, HIGH);
distance = pulseTime/58;
total = total + distance;
delay(1);
}
average = total/numReadings;
if (index >= numReadings) {
index = 0;
total = 0;
}
Serial.print("X");
Serial.print(leftRightPos);
Serial.print("V");
Serial.println(average);
}
}

----------------------------------------------------

kode Processing

/*
Radar Screen Visualisation for HC-SR04
Maps out an area of what the HC-SR04 sees from a top down view.
Takes and displays 2 readings, one left to right and one right to left.
Displays an average of the 2 readings
Displays motion alert if there is a large difference between the 2 values.
*/
import processing.serial.*; // import serial library
Serial arduinoport; // declare a serial port
float x, y; // variable to store x and y co-ordinates for vertices
int radius = 350; // set the radius of objects
int w = 300; // set an arbitary width value
int degree = 0; // servo position in degrees
int value = 0; // value from sensor
int motion = 0; // value to store which way the servo is panning
int[] newValue = new int[181]; // create an array to store each new sensor value for each servo
position
int[] oldValue = new int[181]; // create an array to store the previous values.
PFont myFont; // setup fonts in Processing
int radarDist = 0; // set value to configure Radar distance labels
int firstRun = 0; // value to ignore triggering motion on the first 2 servo sweeps
/* create background and serial buffer */
void setup(){
// setup the background size, colour and font.
size(750, 450);
background (0); // 0 = black
myFont = createFont("verdana", 12);
textFont(myFont);
// setup the serial port and buffer
arduinoport = new Serial(this, Serial.list()[0], 9600);
}
/* draw the screen */
void draw(){
fill(0); // set the following shapes to be black
noStroke(); // set the following shapes to have no outline
ellipse(radius, radius, 750, 750); // draw a circle with a width/ height = 750 with its center position
(x and y) set by the radius
rectMode(CENTER); // set the following rectangle to be drawn around its center
rect(350,402,800,100); // draw rectangle (x, y, width, height)
if (degree >= 179) { // if at the far right then set motion = 1/ true we're about to go right
to left
motion = 1; // this changes the animation to run right to left
}
if (degree <= 1) { // if servo at 0 degrees then we're about to go left to right
motion = 0; // this sets the animation to run left to right
}
/* setup the radar sweep */
/*
We use trigonmetry to create points around a circle.
So the radius plus the cosine of the servo position converted to radians
Since radians 0 start at 90 degrees we add 180 to make it start from the left
Adding +1 (i) each time through the loops to move 1 degree matching the one degree of servo
movement
cos is for the x left to right value and sin calculates the y value
since its a circle we plot our lines and vertices around the start point for everything will always be
the center.
*/
strokeWeight(7); // set the thickness of the lines
if (motion == 0) { // if going left to right
for (int i = 0; i <= 20; i++) { // draw 20 lines with fading colour each 1 degree further round than
the last
stroke(0, (10*i), 0); // set the stroke colour (Red, Green, Blue) base it on the the value of i
line(radius, radius, radius + cos(radians(degree+(180+i)))*w, radius +
sin(radians(degree+(180+i)))*w); // line(start x, start y, end x, end y)
}
} else { // if going right to left
for (int i = 20; i >= 0; i--) { // draw 20 lines with fading colour
stroke(0,200-(10*i), 0); // using standard RGB values, each between 0 and 255
line(radius, radius, radius + cos(radians(degree+(180+i)))*w, radius +
sin(radians(degree+(180+i)))*w);
}
}
/* Setup the shapes made from the sensor values */
noStroke(); // no outline
/* first sweep */
fill(0,50,0); // set the fill colour of the shape (Red, Green, Blue)
beginShape(); // start drawing shape
for (int i = 0; i < 180; i++) { // for each degree in the array
x = radius + cos(radians((180+i)))*((oldValue[i])); // create x coordinate
y = radius + sin(radians((180+i)))*((oldValue[i])); // create y coordinate
vertex(x, y); // plot vertices
}
endShape(); // end shape
/* second sweep */
fill(0,110,0);
beginShape();
for (int i = 0; i < 180; i++) {
x = radius + cos(radians((180+i)))*(newValue[i]);
y = radius + sin(radians((180+i)))*(newValue[i]);
vertex(x, y);
}
endShape();
/* average */
fill(0,170,0);
beginShape();
for (int i = 0; i < 180; i++) {
x = radius + cos(radians((180+i)))*((newValue[i]+oldValue[i])/2); // create average
y = radius + sin(radians((180+i)))*((newValue[i]+oldValue[i])/2);
vertex(x, y);
}
endShape();
/* if after first 2 sweeps, highlight motion with red circle*/
if (firstRun >= 360) {
stroke(150,0,0);
strokeWeight(1);
noFill();
for (int i = 0; i < 180; i++) {
if (oldValue[i] - newValue[i] > 35 || newValue[i] - oldValue[i] > 35) {
x = radius + cos(radians((180+i)))*(newValue[i]);
y = radius + sin(radians((180+i)))*(newValue[i]);
ellipse(x, y, 10, 10);
}
}
}
/* set the radar distance rings and out put their values, 50, 100, 150 etc.. */
for (int i = 0; i <=6; i++){
noFill();
strokeWeight(1);
stroke(0, 255-(30*i), 0);
ellipse(radius, radius, (100*i), (100*i));
fill(0, 100, 0);
noStroke();
text(Integer.toString(radarDist+50), 380, (305-radarDist), 50, 50);
radarDist+=50;
}
radarDist = 0;
/* draw the grid lines on the radar every 30 degrees and write their values 180, 210, 240 etc.. */
for (int i = 0; i <= 6; i++) {
strokeWeight(1);
stroke(0, 55, 0);
line(radius, radius, radius + cos(radians(180+(30*i)))*w, radius + sin(radians(180+(30*i)))*w);
fill(0, 55, 0);
noStroke();
if (180+(30*i) >= 300) {
text(Integer.toString(180+(30*i)), (radius+10) + cos(radians(180+(30*i)))*(w+10), (radius+10) +
sin(radians(180+(30*i)))*(w+10), 25,50);
} else {
text(Integer.toString(180+(30*i)), radius + cos(radians(180+(30*i)))*w, radius +
sin(radians(180+(30*i)))*w, 60,40);
}
}
/* Write information text and values. */
noStroke();
fill(0);
rect(350,402,800,100);
fill(0, 100, 0);
text("Degrees: "+Integer.toString(degree), 100, 380, 100, 50); // use Integet.toString to convert
numeric to string as text() only outputs strings
text("Distance: "+Integer.toString(value), 100, 400, 100, 50); // text(string, x, y, width, height)
text("Radar screen code ", 540, 380, 250, 50);
fill(0);
rect(70,60,150,100);
fill(0, 100, 0);
text("Screen Key:", 100, 50, 150, 50);
fill(0,50,0);
rect(30,53,10,10);
text("First sweep", 115, 70, 150, 50);
fill(0,110,0);
rect(30,73,10,10);
text("Second sweep", 115, 90, 150, 50);
fill(0,170,0);
rect(30,93,10,10);
text("Average", 115, 110, 150, 50);
noFill();
stroke(150,0,0);
strokeWeight(1);
ellipse(29, 113, 10, 10);
fill(150,0,0);
text("Motion", 115, 130, 150, 50);
}
/* get values from serial port */
void serialEvent (Serial arduinoport) {
String xString = arduinoport.readStringUntil('\n'); // read the serial port until a new line
if (xString != null) { // if theres data in between the new lines
xString = trim(xString); // get rid of any whitespace just in case
String getX = xString.substring(1, xString.indexOf("V")); // get the value of the servo position
String getV = xString.substring(xString.indexOf("V")+1, xString.length()); // get the value of the
sensor reading
degree = Integer.parseInt(getX); // set the values to variables
value = Integer.parseInt(getV);
oldValue[degree] = newValue[degree]; // store the values in the arrays.
newValue[degree] = value;
/* sets a counter to allow for the first 2 sweeps of the servo */
firstRun++;
if (firstRun > 360) {
firstRun = 360; // keep the value at 360
}
}
}
=============================================================
90. WATERBATH
Pada diagram di atas kita sajikan draft waterbath. Garis besar cara kerjanya adalah sebagai berikut.
Temperatur dari air dalam wadah diukur dengan PT100, signal dari PT100 ini diperkuat dengan
penguat LM324, output dari LM324 ini diumpankan ke ADS1115, di mana modul ADS1115 ini
akan meningkatkan resolusi pembacaan signal analog dari output LM324. Signal analog yang
dibaca kemudian dikalibrasi terhadap rentang suhu. Pembacaan suhu ini akan digunakan untuk
mengendalikan sebuah pemanas listrik melalui relay. Relay tidak terhubung secara langsung
terhadap sirkuit kontroler, karena jika relay ini tergabung pada sirkuit kontroler maka akan
menimbulkan ketidakstabilan pembacaan suhu, sebagai gantinya maka kita gunakan gabungan LED
dan LDR untuk mengaktifkan relay ini. Sumber tegangan yang dipakai kontroler dan relay juga
terpisah. Hal yang tak kalah penting adalah pisahkan ground untuk ADS1115 terhadap ground yang
digunakan module lain agar stabilitas pembacaan suhu terjaga.

#include <EEPROM.h>
#include <LiquidCrystal.h>
int pinIncrease = 2; //pin increase button
int pinDecrease = 3; //pin decrease button
int pinHeater = 11; // go to relay input
int pinIND = 13; // LED heating indicator
int pinSetting = 10; // setting temperature button key
int SettingSuhu = 0;
byte BatasSuhu;
//---------------------------temp section
#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads(0x48);
int temp0;
//---------------------------temp section
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);//order number : RS,EN,D4,D5,D6,D7
void setup() {
Serial.begin(9600);
lcd.begin(16, 4);
//---------------------------temp section
ads.begin();
//---------------------------temp section
pinMode(pinIncrease, INPUT);
pinMode(pinDecrease, INPUT);
pinMode(pinSetting, INPUT);
pinMode(pinHeater, OUTPUT);
pinMode(pinIND, OUTPUT);
digitalWrite(pinIncrease, HIGH);
digitalWrite(pinDecrease, HIGH);
}

void loop() {
if(digitalRead(pinSetting) == HIGH){
int16_t adc0; // we read from the ADC, we have a sixteen bit integer as a result
adc0 = ads.readADC_SingleEnded(0);
temp0 = adc0;
float suhu = (temp0*0.030705394)-364.87967;//from calabration plot
SettingSuhu = constrain(SettingSuhu, 0, 255);
setting();
EEPROM.write(1, SettingSuhu);
BatasSuhu = EEPROM.read(1);
heater();
Serial.print(BatasSuhu);
Serial.print(" ");
Serial.print(suhu);
Serial.print(" ");
Serial.println(temp0);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("SETT :");
lcd.setCursor(7, 0);
lcd.print(BatasSuhu);
lcd.setCursor(0, 1);
lcd.print("TEMP :");
lcd.setCursor(7, 1);
lcd.print(suhu);
lcd.setCursor(0, 2);
lcd.print("READ :");
lcd.setCursor(7, 2);
lcd.print(temp0);
delay(100);
}
else if(digitalRead(pinSetting) == LOW){
int16_t adc0; // we read from the ADC, we have a sixteen bit integer as a result
adc0 = ads.readADC_SingleEnded(0);
temp0 = adc0;
float suhu = (temp0*0.030705394)-364.87967;//from calabration plot
BatasSuhu = EEPROM.read(1);
heater();
Serial.print(BatasSuhu);
Serial.print(" ");
Serial.print(suhu);
Serial.print(" ");
Serial.println(temp0);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("SETT :");
lcd.setCursor(7, 0);
lcd.print(BatasSuhu);
lcd.setCursor(0, 1);
lcd.print("TEMP :");
lcd.setCursor(7, 1);
lcd.print(suhu);
lcd.setCursor(0, 2);
lcd.print("READ :");
lcd.setCursor(7, 2);
lcd.print(temp0);
delay(100);
}
}
void setting(){
if(digitalRead(pinIncrease) == LOW){
SettingSuhu++;
}else if(digitalRead(pinDecrease) == LOW){
SettingSuhu--;
}
}
void heater(){
float suhu = (temp0*0.030705394)-364.87967;//from calabration plot
if(suhu < BatasSuhu){
digitalWrite(pinHeater, HIGH);
digitalWrite(pinIND, HIGH);
}else{
digitalWrite(pinHeater, LOW);
digitalWrite(pinIND, LOW);
}
}

==============================================================
91. WATERBATH REMOTE CONTROLLED

Sketsa di atas adalah waterbath yang setting suhunya dilakukan melalui remote control.
#include <EEPROM.h>
#include <LiquidCrystal.h>
int pinIncrease = 2; //pin increase button
int pinDecrease = 3; //pin decrease button
int pinHeater = 11; // go to relay input
int pinIND = 13; // LED heating indicator
int pinSetting = 10; // setting temperature button key
int SettingSuhu = 0;
byte BatasSuhu;
//---------------------------temp section
#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads(0x48);
int temp0;
//---------------------------temp section
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);//order number : RS,EN,D4,D5,D6,D7
#include <IRremote.h>
int RECV_PIN = 12;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
lcd.begin(16, 4);
//---------------------------temp section
ads.begin();
//---------------------------temp section
pinMode(pinIncrease, INPUT);
pinMode(pinDecrease, INPUT);
pinMode(pinSetting, INPUT);
pinMode(pinHeater, OUTPUT);
pinMode(pinIND, OUTPUT);
digitalWrite(pinIncrease, HIGH);
digitalWrite(pinDecrease, HIGH);
}
unsigned long last = millis();
void loop() {
SettingSuhu = constrain(SettingSuhu, 0, 255);
if (irrecv.decode(&results)) {
if (results.value == 0xEF1020DF) {
SettingSuhu++;
EEPROM.write(1, SettingSuhu);
}
else if (results.value == 0xEF10A05F) {
SettingSuhu--;
EEPROM.write(1, SettingSuhu);
}
irrecv.resume(); // Receive the next value
}
int16_t adc0; // we read from the ADC, we have a sixteen bit integer as a result
adc0 = ads.readADC_SingleEnded(0);
temp0 = adc0;
float suhu = (temp0*0.030705394)-364.87967;//from calabration plot
BatasSuhu = EEPROM.read(1);
heater();
Serial.print(BatasSuhu);
Serial.print(" ");
Serial.print(suhu);
Serial.print(" ");
Serial.println(temp0);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("SETT :");
lcd.setCursor(7, 0);
lcd.print(BatasSuhu);
lcd.setCursor(0, 1);
lcd.print("TEMP :");
lcd.setCursor(7, 1);
lcd.print(suhu);
lcd.setCursor(0, 2);
lcd.print("READ :");
lcd.setCursor(7, 2);
lcd.print(temp0);
delay(100);
}
void heater(){
float suhu = (temp0*0.030705394)-364.87967;//from calabration plot
if(suhu < BatasSuhu){
digitalWrite(pinHeater, HIGH);
digitalWrite(pinIND, HIGH);
}else{
digitalWrite(pinHeater, LOW);
digitalWrite(pinIND, LOW);
}
}

=======================================================================
92. SWITCH VIA BLUETOOTH

Melalui bluetooth kita dapat mengirimkan signal untuk mematikan atau menyalakan suatu lampu
atau peralatan.

// REMIXED BY: TECHBITAR (HAZIM BITAR)


// LICENSE: PUBLIC DOMAIN
// DATE: MAY 2, 2012
// CONTACT: techbitar at gmail dot com

char INBYTE;
int LED = 13; // LED on pin 13

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

void loop() {
Serial.println("Press 1 to turn Arduino pin 13 LED ON or 0 to turn it OFF:");
while (!Serial.available()); // stay here so long as COM port is empty
INBYTE = Serial.read(); // read next available byte
if( INBYTE == '0' ) digitalWrite(LED, LOW); // if it's a 0 (zero) tun LED off
if( INBYTE == '1' ) digitalWrite(LED, HIGH); // if it's a 1 (one) turn LED on
delay(50);
}

================================================================
93. GAS SENSOR MQ135

int sensorPin = A0;


int sensorValue = 0;
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(100);
}

==================================================================
94. KEYPAD 4x4

#include <Keypad.h>

const byte ROWS = 4; //four rows


const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );


void setup(){
Serial.begin(9600);
}

void loop(){
char key = keypad.getKey();

if (key){
Serial.println(key);
}
}

==============================================================
95. KEYPAD SWITCH

/* Keypadtest.pde
*
* Demonstrate the simplest use of the keypad library.
*
* The first step is to connect your keypad to the
* Arduino using the pin numbers listed below in
* rowPins[] and colPins[]. If you want to use different
* pins then you can change the numbers below to
* match your setup.
*
*/
#include <Keypad.h>

const byte ROWS = 4; // Four rows


const byte COLS = 4; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { 5, 4, 3, 2 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { 9, 8, 7, 6 };

// Create the Keypad


Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

#define ledpin 13

void setup()
{
pinMode(ledpin,OUTPUT);
//digitalWrite(ledpin, HIGH);
Serial.begin(9600);
}

void loop()
{
char key = kpd.getKey();
if(key) // Check for a valid key.
{
switch (key)
{
case 'A':
digitalWrite(ledpin, HIGH);
break;
case 'B':
digitalWrite(ledpin, LOW);
break;
default:
Serial.println(key);
}
}
}
96. RF REMOTE SWITCH

Pada proyek berikut adalah contoh sederhana bagaimana kita memanfaatkan RF module ini untuk
melakukan penyalaan lampu.

Kode transmitter

#include <VirtualWire.h>
char *controller;
void setup() {
pinMode(13,OUTPUT);
vw_set_ptt_inverted(true); //
vw_set_tx_pin(12);
vw_setup(4000);// speed of data transfer Kbps
}

void loop(){
int sensorValue = analogRead(A0);
if(sensorValue > 500){
controller="1";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,1);
//delay(2000);
}
else{
controller="0";
vw_send((uint8_t *)controller, strlen(controller));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13,0);
//delay(2000);
}
}

Kode receiver

#include <VirtualWire.h>
void setup()
{
vw_set_ptt_inverted(true); // Required for DR3100
vw_set_rx_pin(12);
vw_setup(4000); // Bits per sec
pinMode(13, OUTPUT);

vw_rx_start(); // Start the receiver PLL running


}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

if (vw_get_message(buf, &buflen)) // Non-blocking


{
if(buf[0]=='1'){

digitalWrite(13,1);
}
if(buf[0]=='0'){
digitalWrite(13,0);
}

}
}
97. CALCULATOR

/*
|| @version 1.0
|| @author Andrew Mascolo
|| @date May 15, 2013
||
|| @description
|| Simple use of keypad and LCD
*/
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <LCD.h>

//LiquidCrystal_I2C lcd(0x20,20,4);
#define I2C_ADDR 0x27
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

long first = 0;
long second = 0;
double total = 0;

char customKey;
const byte ROWS = 4;
const byte COLS = 4;

char keys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'C','0','=','/'}
};
byte rowPins[ROWS] = {5, 4, 3, 2 }; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6 }; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad


Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup()
{
//lcd.init(); // initialize the lcd
//lcd.backlight();
lcd.begin(16,2);lcd.clear();
lcd.setCursor(0,0);
lcd.print("LOADING");
for(int i=0; i<16; i++){
lcd.setCursor(i,1);
lcd.write(255);
delay(170);
}
lcd.clear();
}

void loop()
{
customKey = customKeypad.getKey();
switch(customKey)
{
case '0' ... '9': // This keeps collecting the first value until a operator is pressed "+-*/"
lcd.setCursor(0,0);
first = first * 10 + (customKey - '0');
lcd.print(first);
break;

case '+':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("+");
second = SecondNumber(); // get the collected the second number
total = first + second;
lcd.setCursor(0,3);
lcd.print(total);
first = 0, second = 0; // reset values back to zero for next use
break;

case '-':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("-");
second = SecondNumber();
total = first - second;
lcd.setCursor(0,3);
lcd.print(total);
first = 0, second = 0;
break;

case '*':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("*");
second = SecondNumber();
total = first * second;
lcd.setCursor(0,3);
lcd.print(total);
first = 0, second = 0;
break;

case '/':
first = (total != 0 ? total : first);
lcd.setCursor(0,1);
lcd.print("/");
second = SecondNumber();
lcd.setCursor(0,3);
second == 0 ? lcd.print("Invalid") : total = (float)first / (float)second;

lcd.print(total);
first = 0, second = 0;
break;

case 'C':
total = 0;
lcd.clear();
break;
}
}

long SecondNumber()
{
while( 1 )
{
customKey = customKeypad.getKey();
if(customKey >= '0' && customKey <= '9')
{
second = second * 10 + (customKey - '0');
lcd.setCursor(0,2);
lcd.print(second);
}

if(customKey == '=') break; //return second;


}
return second;
}

--------------------------------------------------------------------------------------------
atau dapat dicoba sket lain
--------------------------------------------------------------------------------------------------------

/*
Written by:
Gabe (http://rampantrobots.blogspot.com/)
and Kale (http://kalecloud.com/)
*/
#include <Keypad.h>
//#include <LiquidCrystal.h>
#include <stdlib.h>
#include <math.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

///////////////////////////////////////////////////////VARIABLES///////////////////////////////////////////
//VARIABLES TO PARSE FLOATING ANSWER INTO WHOLE NUMBER AND DECIMAL
PARTS///
char outresult[20];
String OutResult;
int decimal_location;
String whole_number;
String decimal_number;

//VARIABLES USED TO SCROLL TOP LINE//


long lasttime =0;
String totalarray = ""; //stores what was input
int length = 0; //length of what was input
int length2 = 0; //length after the first input is added
bool scroll1 = 0; //whether to scroll on line one or not
bool scroll2 = 0; //whether to scroll on line two or not
int scroll_index = 0;

int de=0;
//INPUT VARIABLES//
char input[9]; //buffer for input characters
float firstnumber = 0; //stores first number
float secondnumber = 0; //stores second number
float response = 0; //stores "answer"
bool positive = 1; //indicates positive number
int lcdcolumnindexrow1 = 1; // used to indicate location of input key

//FUNCTION VARIABLES//
int function = 9; //stores currently selected function
const int number_of_functions = 10;
int mode = 2; // select normal operation (1) or mystery function (0)
bool toggle = 1;
int level = 0; // stores level for the game
const int number_of_levels = 10;

///////////////////////////////////////////////////////KEYPAD SETUP///////////////////////////////////////
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
// Define the Keymap
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { 5, 4, 3, 2 };
// Connect keypad COL0, COL1, COL2, and COL3 to these Arduino pins.
byte colPins[COLS] = { 9, 8, 7, 6 };

// Create the Keypad


Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

///////////////////////////////////////////////////////LCD SETUP///////////////////////////////////////
//LiquidCrystal lcd(2, 3, 13, 8, 9, 10, 11, 4, 5, 6, 7);
#define I2C_ADDR 0x27
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;
void setup()
{
lcd.begin(16,2);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("LOADING");
for(int i=0; i<16; i++){
lcd.setCursor(i,1);
lcd.write(255);
delay(170);
}
lcd.clear();
for(int i = 0; i < 8; i++) { input[i] = '0'; } // initialize input as zero
}

void loop()
{

if(scroll1) // display the input number and function(s) on the top line if math has been done
{
scrollline(750, 0, length);
}
else if(scroll2) // display the input number and function(s) on the second line if awaiting a 2nd
number
{
scrollline(750, 1, length2);
}

char key = kpd.getKey(); // read keypad


if (key != NO_KEY)
{
if(de==1){
lcd.clear();
for(int i = 0; i < 8; i++) { input[i] = '0'; }
lcdcolumnindexrow1 = 1;
firstnumber = 0;
secondnumber = 0;
totalarray = "";
scroll1 = 0;
scroll2 = 0;
length = 0;
length2 = 0;
de=0;
if(!mode) {function = 10;} else {function = 9;}
positive = 1;
}
else if(key == 'A'){ //increment function in calculator mode
function = mod(++function, number_of_functions);
displayfunction(function);
}
else if(key == 'B'){ //decrement function in calculator mode
function = mod(--function, number_of_functions);
displayfunction(function);

}else if(key == 'C'){ //clear


lcd.clear();
for(int i = 0; i < 8; i++) { input[i] = '0'; }
lcdcolumnindexrow1 = 1;
firstnumber = 0;
secondnumber = 0;
totalarray = "";
scroll1 = 0;
scroll2 = 0;
length = 0;
length2 = 0;
de=0;
if(!mode) {function = 10;} else {function = 9;}
positive = 1;
}
else if(key == 'D') //enter
{
if(de==1){

}else{

if(function==5 || function==6 || function==7 || function==8){


firstnumber = atof(input); // convert input character array to a float
numintototalarray();
printoperation(function);
response = executefunction(function, firstnumber, 0); // do the math
numintototalarray();
scroll1 = 1; // display the input numbers and function on the top line

lcd.setCursor(0,1);
lcd.print(" ");
lcd.setCursor(0,1);
printresponse(response);

de=1;
}
else if(firstnumber == 0) // this is the first time that enter has been pressed and we have a valid
function
{
firstnumber = atof(input); // convert input character array to a float
numintototalarray();
printoperation(function);
lcd.setCursor(0,0);
lcd.print(" "); //clear first line to make space for the second number
lcd.setCursor(0,1);
lcd.print(" "); //clear line
length2 = length;
scroll2 = 1; //print what the user has entered so far on the second line
for(int i = 0; i < 8; i++) { input[i] = '0'; } // reinitialize the input buffer to make space for the
second number
lcdcolumnindexrow1 = 1;
positive = 1;
}else{
secondnumber = atof(input); // convert input character array to a float
response = executefunction(function, firstnumber, secondnumber); // do the math
numintototalarray();
totalarray = totalarray + "= ";
length = length + 2;
scroll1 = 1; // display the input numbers and function on the top line
if(function == 3 && secondnumber == 0){
lcd.setCursor(0,1);
lcd.print("ERROR");
de=1;
}else{
lcd.setCursor(0,1);
lcd.print(" "); //clear line
lcd.setCursor(0,1);
printresponse(response); //print answer
positive = 1;
de=1;
}

}
}
}
else if(key == '#' && positive ==1) //negative number read and number is currently positive
{
input[0] = '-';
lcd.setCursor(0,0);
lcd.print(input[0]); //print negative sign
positive = 0; //indicate number is now negative
++length;
}
else if(key == '#' && positive ==0)
{
positive = 1; //indicate number is now negative
input[0] = '0';
lcd.setCursor(0,0);
lcd.print(' '); //remove negative sign
--length;
}
else if(lcdcolumnindexrow1 < 8) //buffer overrun prevention
{
//read in a number or a decimal
{
for(int i =1; i < 7; i++) {input[i] = input[i+1]; } //shift all the values left
if(key == '*') { input[7] = '.'; } else { input[7] = key; } //* is decimal
lcd.setCursor(lcdcolumnindexrow1,0); //print on left of LCD moving right
lcd.print(input[7]);
++lcdcolumnindexrow1;
++length;
}
}
}
}

/////////////////////Function Returns Modulo Even for Negative Numbers//////////////////////////


int mod(int a, int b)
{
return (((a % b) + b) % b);
}

//////////////////////Function Displays Math Functions/////////////////////////////////////////


void displayfunction(int _function)
{
lcd.setCursor(0,1);
switch (_function)
{
case 0:
lcd.print("+ ");
break;
case 1:
lcd.print("- ");
break;
case 2:
lcd.print("x ");
break;
case 3:
lcd.print("/ ");
break;
case 4:
lcd.print("^ ");
break;
case 5:
lcd.print("^2 ");
break;
case 6:
lcd.print("sin ");
break;
case 7:
lcd.print("cos ");
break;
case 8:
lcd.print("tan ");
break;
case 9:
lcd.print(" ");
break;
}
}

//////////////////////Function Decides Whether Output Has 0, 1, 2, 3, or 4 Decimals AND Prints


Output/////////////////
void printresponse(float _response)
{
if(abs(_response) < 0.0001 && abs(_response) > 0) {lcd.print("TooSmall");}
else if(_response > 99999999) {lcd.print("Too Big ");}
else if(_response < -9999999) {lcd.print("-Too Big");}
else
{
dtostrf(_response,7,4,outresult); //Convert Float to Character Array
for(int i=0; i<19; i++) //Find the location of the decimal
{
if(outresult[i] == '.')
{
decimal_location = i;
}
}
OutResult = outresult; //Convert Character Array to String
whole_number = OutResult.substring(0,decimal_location); //Read up to the Decimal Location
decimal_number = OutResult.substring(decimal_location+1, decimal_location+5); //Read After
the Decimal Location
if(decimal_number[3] =='0' && decimal_number[2] =='0' && decimal_number[1] =='0' &&
decimal_number[0] =='0') //print only the whole number part
{
lcd.print(whole_number);
}
else if(decimal_number[3] =='0' && decimal_number[2] =='0' && decimal_number[1] =='0') //
print one decimal place
{
OutResult = whole_number + '.' + decimal_number[0];
lcd.print(OutResult);
}
else if(decimal_number[3] =='0' && decimal_number[2] =='0') // print two decimal places
{
OutResult = whole_number + '.' + decimal_number[0] + decimal_number[1];
lcd.print(OutResult);
}
else if(decimal_number[3] =='0') // print three decimal places
{
OutResult = whole_number + '.' + decimal_number[0] + decimal_number[1] +
decimal_number[2];
lcd.print(OutResult);
}
else {lcd.print(OutResult);} // print four decimal places
}
}

//////////////////////FUNCTION ADDS "+" "-" "/" TO STRING ARRAY/////////////////////////////////////////


void printoperation(int _function)
{
switch (_function)
{
case 0:
totalarray = totalarray + "+";
length = length + 1;
break;
case 1:
totalarray = totalarray + "-";
length = length + 1;
break;
case 2:
totalarray = totalarray + "x";
length = length + 1;
break;
case 3:
totalarray = totalarray + "/";
length = length + 1;
break;
case 4:
totalarray = totalarray + "^";
length = length + 1;
break;
case 5:
totalarray = totalarray + "^2= ";
length = length + 4;
break;
case 6:
totalarray = "sin(" + totalarray + ")= ";
length = length + 7;
break;
case 7:
totalarray = "cos(" + totalarray + ")= ";
length = length + 7;
break;
case 8:
totalarray = "tan(" + totalarray + ")= ";
length = length + 7;
break;
case 9:
break;
case 10:
totalarray = "f(" + totalarray + ")= ";
length = length + 5;
break;
}
}

//////////////////////FUNCTION DOES MATH/////////////////////////////////////////


float executefunction(int _function, float _firstnumber, float _secondnumber)
{
float _output;
switch (_function)
{
case 0:
_output = _firstnumber + _secondnumber;
break;
case 1:
_output = _firstnumber - _secondnumber;
break;
case 2:
_output = _firstnumber * _secondnumber;
break;
case 3:
if(_secondnumber != 0) {_output = _firstnumber / _secondnumber;}
break;
case 4:
_output = pow(_firstnumber, _secondnumber);
_output= round(_output);
break;
case 5:
_output = pow(_firstnumber, 2);
break;
case 6:
_output = sin(_firstnumber);
break;
case 7:
_output = cos(_firstnumber);
break;
case 8:
_output = tan(_firstnumber);
break;
case 9:
break;
}
return _output;
}

///////////////////Function Scrolls a Line////////////////////////////////


void scrollline(int delaytime, int line_number, int _length)
{
if(length > 8) // if the input is too long to fit on the screen, then scroll
{
if(millis() - lasttime > delaytime) // do this only every 750 milliseconds.
{
for(int i =0; i<8; i++)
{
lcd.setCursor(i,line_number);
if(scroll_index+i < _length) {lcd.print(totalarray.charAt(scroll_index+i));} else {lcd.print(" "); }
}
scroll_index = (scroll_index + 1)%(_length-6);
lasttime = millis();
}
}
else // if the input is shorter than 8 characters, no scroll is required
{
lcd.setCursor(0,line_number);
lcd.print(totalarray);
}
}

////////////////////////////////////////Function Scans Input Number into String Total Array/////////////////////////


void numintototalarray()
{
if(positive == 0) { totalarray = totalarray + '-'; }
for(int i = 1; i < 8; i++)
{
if(i > (8 - lcdcolumnindexrow1))
{
totalarray = totalarray + input[i];
}
}
}

=====================================================================
98. HALL PROXIMITY SENSOR

Pada penggunaan modul Hall ini, jika magnet didekatkan pada sensor Hall maka lampu LED akan
menyala. Pada diagram di atas A0 adalah kebalikan dari D0, artinya jika pin D3 kita sambungkan ke
pin modul D0 maka yang terjadi adalah jika magnet didekatkan ke sensor Hall maka LED akan
padam.

const int hallPin = 3; // the number of the hall effect sensor pin
const int ledPin = 2; // the number of the LED pin
// variables will change:
int hallState = 0; // variable for reading the hall sensor status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the hall effect sensor pin as an input:
pinMode(hallPin, INPUT);
}

void loop(){
// read the state of the hall effect sensor:
hallState = digitalRead(hallPin);

if (hallState == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
99. SERVO SERIAL CONTROLED

Kita bisa mengendalikan servo ini melalui serial monitor, ketikkan nilai sudut yang kita inginkan
(0-180) lalu tekan enter.

#include <Servo.h>

Servo servo1;
long num;

void setup()
{
servo1.attach(9);
Serial.begin(9600);
Serial.print("Enter Position = ");
}

void loop()
{
while(Serial.available()>0)
{
num= Serial.parseInt();
Serial.print(num);
Serial.println(" degree");
Serial.print("Enter Position = ");
}
servo1.write(num);
delay(15);
}

=======================================================================
100. SERVO CONTROL VIA BLUETOOTH

Kita juga dapat mengendalikan servo melalui bluetooth. Perlu diketahui ketika kita melakukan
upload sket lepaskan kabel TX dan RX pada arduino karena ketika RX dan TX ini terhubung maka
komunikasi usb arduino akan terputus. Operasikan servo via komputer lain yang terhubung
bluetooth dengan memakai Arduino IDE atau Tera Term.

#include <Servo.h>

Servo servo1;
long num;

void setup()
{
servo1.attach(9);
Serial.begin(9600);
Serial.print("Enter Position = ");
}

void loop()
{
while(Serial.available()>0)
{
num= Serial.parseInt();
Serial.print(num);
Serial.println(" degree");
Serial.print("Enter Position = ");
}
servo1.write(num);
delay(15);
}

===================================================================
101. LCD SERIAL MONITOR

Pada proyek ini kita demonstrasikan pengiriman karakter dari serial monitor ke LCD display.
/*
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
*/
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
/*
For details about the LCD display with I2C support see
http://www.fasttech.com/reviews/1380909/22072
and
http://dx.com/p/funduino-iic-i2c-1602-lcd-adapter-board-w-2-5-lcd-screen-black-green-red-173588
The reviewer comments by docpayce and particularly JackWP associated with the two product
pages above have been very useful.

Connect the LCD: VCC -> 5V, GND -> GND, SDA -> A4 (PortC4, ADC4), SCL -> A5 (PortC5,
SDA)

The LiquidCrystal_I2C library needs to be downloaded and installed from here:


https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home
*/

#define I2C_ADDR 0x27


#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// initialize the serial communications:
Serial.begin(9600);
}

void loop() {
// when characters arrive over the serial port...
if (Serial.available()) {
// 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());
}
}
}
102. LCD SERIAL MONITOR WITH SCHROLL

Kita juga dapat menggeser tulisan yang terkirim dari serial monitor ke LCD. Karakter yang dapat
kita tuliskan hanya 64 karakter, kelebihan karakter dari 64 tidak akan tertampil.

/*
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
*/
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
/*
For details about the LCD display with I2C support see
http://www.fasttech.com/reviews/1380909/22072
and
http://dx.com/p/funduino-iic-i2c-1602-lcd-adapter-board-w-2-5-lcd-screen-black-green-red-173588
The reviewer comments by docpayce and particularly JackWP associated with the two product
pages above have been very useful.

Connect the LCD: VCC -> 5V, GND -> GND, SDA -> A4 (PortC4, ADC4), SCL -> A5 (PortC5,
SDA)

The LiquidCrystal_I2C library needs to be downloaded and installed from here:


https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home
*/

#define I2C_ADDR 0x27


#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 1);
// initialize the serial communications:
Serial.begin(9600);
}

void loop() {
// when characters arrive over the serial port...
if (Serial.available()) {
// 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());
}
}
//int i;
//for (i = 0 ; i < 16; i ++) {
lcd.scrollDisplayLeft();
delay(400);
//}#
}
103. PESAN 63 HURUF

Pada proyek ini kita demostrasikan penggunaan LED matrix untuk menuliskan pesan singkat 63
huruf. Ketik pesan pada serial monitor. Huruf yang dapat dituliskan hanya 63 saja karena
keterbatasan kapasitas EEPROM.

#include <MaxMatrix.h>
#include <avr/pgmspace.h>
#include <EEPROM.h>
const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 5; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];
const int EEPROM_MIN_ADDR = 0;
const int EEPROM_MAX_ADDR = 511;

void eeprom_erase_all(byte b = 0xFF) {


int i;

for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {


EEPROM.write(i, b);
}
}

void eeprom_serial_dump_column() {
int i;
byte b;
char buf[10];
for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {
b = EEPROM.read(i);
sprintf(buf, "%03X: %02X", i, b);
Serial.println(buf);
}
}

void eeprom_serial_dump_table(int bytesPerRow = 16) {

int i;
int j;
byte b;
char buf[10];
j = 0;
for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {
if (j == 0) {
sprintf(buf, "%03X: ", i);
Serial.print(buf);
}
b = EEPROM.read(i);
sprintf(buf, "%02X ", b);
j++;
if (j == bytesPerRow) {
j = 0;
Serial.println(buf);
}
else {
Serial.print(buf);
}
}
}

boolean eeprom_is_addr_ok(int addr) {


return ((addr >= EEPROM_MIN_ADDR) && (addr <= EEPROM_MAX_ADDR));
}

boolean eeprom_write_bytes(int startAddr, const byte* array, int numBytes) {

int i;

if (!eeprom_is_addr_ok(startAddr) || !eeprom_is_addr_ok(startAddr + numBytes)) {


return false;
}

for (i = 0; i < numBytes; i++) {


EEPROM.write(startAddr + i, array[i]);
}

return true;
}
boolean eeprom_read_bytes(int startAddr, byte array[], int numBytes) {
int i;

if (!eeprom_is_addr_ok(startAddr) || !eeprom_is_addr_ok(startAddr + numBytes)) {


return false;
}

for (i = 0; i < numBytes; i++) {


array[i] = EEPROM.read(startAddr + i);
}

return true;
}

boolean eeprom_write_int(int addr, int value) {


byte *ptr;

ptr = (byte*)&value;
return eeprom_write_bytes(addr, ptr, sizeof(value));
}

boolean eeprom_read_int(int addr, int* value) {


return eeprom_read_bytes(addr, (byte*)value, sizeof(int));
}

boolean eeprom_write_string(int addr, const char* string) {


// actual number of bytes to be written
int numBytes;

numBytes = strlen(string) + 1;

return eeprom_write_bytes(addr, (const byte*)string, numBytes);


}

boolean eeprom_read_string(int addr, char* buffer, int bufSize) {


// byte read from eeprom
byte ch;

int bytesRead;

if (!eeprom_is_addr_ok(addr)) {
return false;
}

if (bufSize == 0) {
return false;
}

if (bufSize == 1) {
buffer[0] = 0;
return true;
}

bytesRead = 0;

ch = EEPROM.read(addr + bytesRead);

buffer[bytesRead] = ch;

bytesRead++;

while ( (ch != 0x00) && (bytesRead < bufSize) && ((addr + bytesRead) <=
EEPROM_MAX_ADDR) ) {
// if no stop condition is met, read the next byte from eeprom
ch = EEPROM.read(addr + bytesRead);

buffer[bytesRead] = ch;

bytesRead++;
}

if ((ch != 0x00) && (bytesRead >= 1)) {


buffer[bytesRead - 1] = 0;
}

return true;
}

int start_time;
int stop_time;

void start_timing() {
start_time = millis();
}
void print_elapsed() {
stop_time = millis();
Serial.print("Time elapsed (ms): ");
Serial.println(stop_time - start_time);
}
//======================================
bool write_StringEE(int Addr, String input)
{
char cbuff[input.length() + 1];
input.toCharArray(cbuff, input.length() + 1);
return eeprom_write_string(Addr, cbuff);
}

String read_StringEE(int Addr, int length)


{
char cbuff[length+1];
eeprom_read_string(Addr, cbuff, length+1);

String stemp(cbuff);
return stemp;
}

const int BUFSIZE = 50;


char buf[BUFSIZE];

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
String text;
if (Serial.available()) {
for (int i = 0 ; i < 512 ; i++) {
EEPROM.write(i, 0);
}
//eeprom_erase_all(byte b = 0xFF);
text = Serial.readString();
write_StringEE(0, text);//Write string starting at address 0

}
else{
int i;
for (i = 0; i <= 512; i++) {
byte c = EEPROM.read(i);
//printStringWithShift(" ", 100);
printCharWithShift(c, 100);
//printStringWithShift(" ", 100);
}
}
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}
void printStringWithShift(char* s, int shift_speed){
while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}
void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}

atau kita gunakan sket lain yang sedikit berbeda

#include <MaxMatrix.h>
#include <avr/pgmspace.h>
#include <EEPROM.h>
const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 5; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){

if (Serial.available()) {

byte b = Serial.read();
int i;

for (i = 0; i <= 511; i++) {


byte b = Serial.read();
EEPROM.write(i, b);

printCharWithShift(b, 100);

}
else{
int i;

for (i = 0; i <= 511; i++) {


byte c = EEPROM.read(i);
printCharWithShift(c, 100);
}
}
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}

================================================================
104. MATRIX-RTC-DHT22

Proyek ini adalah penggabungan beberapa proyek terdahulu : JAM-SUHU-KELEMBABAN-LED


MATRIX, DHT 22, PESAN 63 HURUF serta penambahan bluetooth untuk penulisan pesan, perlu
diingat jumper ke RX dan TX arduino ini harus dilepas saat upload sket.

#include <MaxMatrix.h>
#include <avr/pgmspace.h>
#include <EEPROM.h>

//===============================
const float fVerNum = 0.03;
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
#include <stdlib.h>
#include "DHT.h" //include the temp sensor library
#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 temp&humid sensor
DHT dht(DHTPIN, DHTTYPE);
//=====================================
const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B00100100, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};
int data = 12; // 8, DIN pin of MAX7219 module
int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 9; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];

const int EEPROM_MIN_ADDR = 0;


const int EEPROM_MAX_ADDR = 511;

void eeprom_erase_all(byte b = 0xFF) {


int i;

for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {


EEPROM.write(i, b);
}
}

void eeprom_serial_dump_column() {

int i;

byte b;

char buf[10];

for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {


b = EEPROM.read(i);
sprintf(buf, "%03X: %02X", i, b);
Serial.println(buf);
}
}

void eeprom_serial_dump_table(int bytesPerRow = 16) {

int i;
int j;
byte b;
char buf[10];

j = 0;

for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {

if (j == 0) {
sprintf(buf, "%03X: ", i);
Serial.print(buf);
}

b = EEPROM.read(i);

sprintf(buf, "%02X ", b);

j++;

if (j == bytesPerRow) {
j = 0;
Serial.println(buf);
}

else {
Serial.print(buf);
}
}
}

boolean eeprom_is_addr_ok(int addr) {


return ((addr >= EEPROM_MIN_ADDR) && (addr <= EEPROM_MAX_ADDR));
}

boolean eeprom_write_bytes(int startAddr, const byte* array, int numBytes) {

int i;

if (!eeprom_is_addr_ok(startAddr) || !eeprom_is_addr_ok(startAddr + numBytes)) {


return false;
}

for (i = 0; i < numBytes; i++) {


EEPROM.write(startAddr + i, array[i]);
}

return true;
}

boolean eeprom_read_bytes(int startAddr, byte array[], int numBytes) {


int i;

if (!eeprom_is_addr_ok(startAddr) || !eeprom_is_addr_ok(startAddr + numBytes)) {


return false;
}

for (i = 0; i < numBytes; i++) {


array[i] = EEPROM.read(startAddr + i);
}

return true;
}
boolean eeprom_write_int(int addr, int value) {
byte *ptr;

ptr = (byte*)&value;
return eeprom_write_bytes(addr, ptr, sizeof(value));
}

boolean eeprom_read_int(int addr, int* value) {


return eeprom_read_bytes(addr, (byte*)value, sizeof(int));
}

boolean eeprom_write_string(int addr, const char* string) {

int numBytes;

numBytes = strlen(string) + 1;

return eeprom_write_bytes(addr, (const byte*)string, numBytes);


}

boolean eeprom_read_string(int addr, char* buffer, int bufSize) {


byte ch;
int bytesRead;
if (!eeprom_is_addr_ok(addr)) {
return false;
}
if (bufSize == 0) {
return false;
}
if (bufSize == 1) {
buffer[0] = 0;
return true;
}
bytesRead = 0;
ch = EEPROM.read(addr + bytesRead);
buffer[bytesRead] = ch;
bytesRead++;
while ( (ch != 0x00) && (bytesRead < bufSize) && ((addr + bytesRead) <=
EEPROM_MAX_ADDR) ) {
ch = EEPROM.read(addr + bytesRead);
buffer[bytesRead] = ch;
bytesRead++;
}
if ((ch != 0x00) && (bytesRead >= 1)) {
buffer[bytesRead - 1] = 0;
}

return true;
}

int start_time;
int stop_time;
void start_timing() {
start_time = millis();
}

void print_elapsed() {
stop_time = millis();
Serial.print("Time elapsed (ms): ");
Serial.println(stop_time - start_time);
}
//======================================
bool write_StringEE(int Addr, String input)
{
char cbuff[input.length() + 1];
input.toCharArray(cbuff, input.length() + 1);
return eeprom_write_string(Addr, cbuff);
}

String read_StringEE(int Addr, int length)


{

char cbuff[length+1];
eeprom_read_string(Addr, cbuff, length+1);

String stemp(cbuff);
return stemp;

const int BUFSIZE = 50;


char buf[BUFSIZE];

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

void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
m.setIntensity(1); // dot matix intensity 0-15
dht.begin();
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
RTC.adjust(DateTime(__DATE__, __TIME__));
}

//====================================================
}
void loop(){
String text;
if (Serial.available()) {

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


EEPROM.write(i, 0);
}
text = Serial.readString();
write_StringEE(0, text);//Write string starting at address 0

}
else{

int i;

for (i = 0; i <= 1000; i++) {


byte c = EEPROM.read(i);
printCharWithShift(c, 100);
}
printStringWithShift("$$ ", 100);
printStringWithShift("TODAY : ", 100);
waktu();
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}

void waktu(){

float t = dht.readTemperature();
float h = dht.readHumidity();
char temp[4];
char hum[4];
itoa(t,temp,10); //convert int to char!!!!
itoa(h,hum,10); //convert int to char!!!!
DateTime now = RTC.now();

int mt = (now.month());
int dy = (now.day());
int y = (now.year());
int jm = (now.hour());
int men = (now.minute());
int dt = (now.second());
char tahun[5];
char bulan[4];
char tanggal[4];
char jam[4];
char menit[4];
char detik[4];

itoa(mt,bulan,10); //convert int to char!!!!


itoa(dy,tanggal,10); //convert int to char!!!!
itoa(y,tahun,10); //convert int to char!!!!
itoa(jm,jam,10); //convert int to char!!!!
itoa(men,menit,10); //convert int to char!!!!
itoa(dt,detik,10); //convert int to char!!!!

if(now.dayOfWeek()==1){
printStringWithShift("MONDAY", 100);
}
if(now.dayOfWeek()==2){
printStringWithShift("TUESDAY", 100);
}
if(now.dayOfWeek()==3){
printStringWithShift("WEDNESDAY", 100);
}
if(now.dayOfWeek()==4){
printStringWithShift("THURSDAY", 100);
}
if(now.dayOfWeek()==5){
printStringWithShift("FRIDAY", 100);
}
if(now.dayOfWeek()==6){
printStringWithShift("SATURDAY", 100);
}
if(now.dayOfWeek()==0){
printStringWithShift("SUNDAY", 100);
}
printStringWithShift(" ", 100);
printStringWithShift(tanggal, 100);
printStringWithShift("/", 100);
printStringWithShift(bulan, 100);
printStringWithShift("/", 100);
printStringWithShift(tahun, 100);
printStringWithShift(" ", 100);
printStringWithShift(jam, 100);
printStringWithShift(":", 100);
printStringWithShift(menit, 100);
printStringWithShift(":", 100);
printStringWithShift(detik, 100);
printStringWithShift(" ", 100);
printStringWithShift("temp: ", 100);
printStringWithShift(temp, 100);
printStringWithShift(" C ", 100);
printStringWithShift("humidity: ", 100);
printStringWithShift(hum, 100);
printStringWithShift(" % ", 100);
printStringWithShift(" ", 100);

m.shiftLeft(false, true);
}

============================================================
105. KEYPAD LOCK PASSWORD

/*
and press "#" than enter your password and press*. The LED will turn ON and will OFF.
*/
#include <Password.h> //http://playground.arduino.cc/uploads/Code/Password.zip //tells to use
password library
#include <Keypad.h> //http://www.arduino.cc/playground/uploads/Code/Keypad.zip //tells to use
keypad library

Password password = Password( "1234" ); //password to unlock, can be changed

const byte ROWS = 4; //four rows


const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

// Create the Keypad


Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
Serial.begin(9600);
delay(200);
pinMode(13, OUTPUT);
keypad.addEventListener(keypadEvent); //add an event listener for this keypad
}

void loop(){
keypad.getKey();
}
void keypadEvent(KeypadEvent eKey){
switch (keypad.getState()){
case PRESSED:

Serial.print("Enter:");
Serial.println(eKey);
delay(10);

switch (eKey){
case '*': checkPassword(); delay(1); break;
case '#': password.reset(); delay(1); break;
default: password.append(eKey); delay(1);
}
}
}
void checkPassword(){

if (password.evaluate()){ //if password is right open

Serial.println("Accepted");
digitalWrite(13, HIGH);//turn on
delay(5000); //wait 5 seconds
digitalWrite(13, LOW);// turn off

}else{
Serial.println("Denied"); //if passwords wrong keep locked
digitalWrite(13, LOW);//turn off

}
}

=================================================================
106. WIRELESS RF TEMPERATURE AND RH

Transmitter

// Include needed libraries


#include <VirtualWire.h>
#include <DHT.h>

// Defininition
#define dhtPin 4
#define dhtType DHT11
#define txPowerPin 8 // virtual pin, allways different with vw_set_tx_pin
// using the DHT library
DHT dht(dhtPin, dhtType);

// Variables
char msg0[3];
char msg1[3];

int tem = 0;
int hum = 0;

// Setup function - run one time


void setup() {
pinMode(txPowerPin, OUTPUT);
pinMode(txPowerPin, LOW);
vw_setup(4800); // VirtualWire communication speed
vw_set_tx_pin(12); // VirtualWire transmit pin
}

// Loop function - runs forever


void loop() {
digitalWrite(txPowerPin, HIGH);
hum = dht.readHumidity(); // Variable holding humidity
tem = dht.readTemperature(); // Variable holding temperature
itoa(hum, msg1, 10); // Converting humidity to an array of chars
itoa(tem, msg0, 10); // Converting the temperature to an array of chars
strcat(msg0, msg1); // Adding/joining the two arrays
vw_send((uint8_t *)msg0, strlen(msg0)); // Sending the msg
vw_wait_tx(); // Wait for tx to finish

digitalWrite(txPowerPin, LOW);

delay(3000); // Wait three seconds and it again

}
Receiver

// Include needed libraries


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

#define I2C_ADDR 0x27


#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

// "Drawing" the degree symbol


byte degreesymbol[8] = {
B01100,
B10010,
B10010,
B01100,
B00000,
B00000,
B00000,
B00000
};

// Variables
int tem = 0;
int i;
int led = 13;
// Setup function - run one time
void setup() {
lcd.begin(16,2); // Defining the LCD
lcd.createChar(1, degreesymbol); // Creating the degree symbol at place 1
Serial.begin(9600); // For debugging purpose
vw_setup(4800); // VirtualWire communication speed
vw_rx_start(); // Getting redy to receive
vw_set_rx_pin(2); // VirtualWiore receive pin
lcd.clear(); // Clear the LCD
}

// Loop function - runs forever


void loop() {
uint8_t buf[VW_MAX_MESSAGE_LEN]; // Variable to hold the received data
uint8_t buflen = VW_MAX_MESSAGE_LEN; // Variable to hold the length of the received data
lcd.setCursor(0,0);
lcd.print("Temp: ");
if (vw_get_message(buf, &buflen)) // If data is received
{
digitalWrite(led, HIGH);
Serial.print("Temp: ");
for (i=0;i<2;i++) // Get the two first bytes
{
Serial.write(buf[i]); // Debugging purpose
lcd.write(buf[i]); // Write the first bytes on the LCD
}
Serial.print(" degC");
Serial.print(" "); // Debugging purpose
lcd.write(1); // Write the degree symbol on the LCD
lcd.print(" C");
lcd.setCursor(0,1);
lcd.print("Hum: ");

Serial.print("Hum: ");
for (i=2;i<4;i++) // Get the two last bytes
{
Serial.write(buf[i]); // Debugging
lcd.write(buf[i]); // Write the last bytes on the LCD
}
Serial.print(" %");
lcd.print("% RH");
Serial.println();
}
else{
digitalWrite(led, LOW);
}
}
107. SEND ANALOG DATA VIA RF

Transmitter

/*

Sensor Transmitter
By Markus Ulfberg 2012-07-06
Takes a sensor reading 0-1023
converts it to a char array and sends
to RF receiver unit via VirtualWire

*/

#include <VirtualWire.h>
#define txPowerPin 8
// LED's
const int ledPin = 13;

// Sensors
const int Sensor1Pin = A2;
// const int Sensor2Pin = 3;

int Sensor1Data;
//int Sensor2Data;
char Sensor1CharMsg[4];

void setup() {
pinMode(txPowerPin, OUTPUT);
pinMode(txPowerPin, LOW);
// PinModes
// LED
pinMode(ledPin,OUTPUT);
// Sensor(s)
pinMode(Sensor1Pin,INPUT);

// for debugging
Serial.begin(9600);

// VirtualWire setup
vw_setup(2000); // Bits per sec
vw_set_tx_pin(12); // VirtualWire transmit pin

void loop() {
digitalWrite(txPowerPin, HIGH);
// Read and store Sensor 1 data
Sensor1Data = analogRead(Sensor1Pin);

// Convert integer data to Char array directly


itoa(Sensor1Data,Sensor1CharMsg,10);

// DEBUG
Serial.print("Sensor1 Integer: ");
Serial.print(Sensor1Data);
Serial.print(" Sensor1 CharMsg: ");
Serial.print(Sensor1CharMsg);
Serial.println(" ");
delay(1000);

// END DEBUG

digitalWrite(13, true); // Turn on a light to show transmitting


vw_send((uint8_t *)Sensor1CharMsg, strlen(Sensor1CharMsg));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13, false); // Turn off a light after transmission
digitalWrite(txPowerPin, LOW);
delay(2000);

} // END void loop...

Receiver
/*

Sensor Receiver
By Markus Ulfberg 2012-07-06

Gets a sensor reading 0-1023 in a char array


from RF Transmitter unit via VirtualWire
converts char array back to integer

*/

#include <VirtualWire.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
/*
For details about the LCD display with I2C support see
http://www.fasttech.com/reviews/1380909/22072
and
http://dx.com/p/funduino-iic-i2c-1602-lcd-adapter-board-w-2-5-lcd-screen-black-green-red-173588
The reviewer comments by docpayce and particularly JackWP associated with the two product
pages above have been very useful.

Connect the LCD: VCC -> 5V, GND -> GND, SDA -> A4 (PortC4, ADC4), SCL -> A5 (PortC5,
SDA)

The LiquidCrystal_I2C library needs to be downloaded and installed from here:


https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home
*/

#define I2C_ADDR 0x27


#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

// LED's
int ledPin = 13;

// Sensors
int Sensor1Data;

// RF Transmission container
char Sensor1CharMsg[4];

void setup() {
Serial.begin(9600);
lcd.begin(16,2); // initialize the lcd
lcd.home ();
// sets the digital pin as output
pinMode(ledPin, OUTPUT);

// VirtualWire
// Initialise the IO and ISR
// Required for DR3100
vw_set_ptt_inverted(true);
// Bits per sec
vw_setup(2000);

// Start the receiver PLL running


vw_rx_start();
vw_set_rx_pin(2);

} // END void setup

void loop(){
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

// Non-blocking
if (vw_get_message(buf, &buflen))
{
int i;
// Turn on a light to show received good message
digitalWrite(13, true);

// Message with a good checksum received, dump it.


for (i = 0; i < buflen; i++)
{
// Fill Sensor1CharMsg Char array with corresponding
// chars from buffer.
Sensor1CharMsg[i] = char(buf[i]);
}

// Null terminate the char array


// This needs to be done otherwise problems will occur
// when the incoming messages has less digits than the
// one before.
Sensor1CharMsg[buflen] = '\0';

// Convert Sensor1CharMsg Char array to integer


Sensor1Data = atoi(Sensor1CharMsg);

// DEBUG
Serial.print("Sensor 1: ");
Serial.println(Sensor1Data);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("SensorData = ");
lcd.setCursor(0, 1);
lcd.print(Sensor1Data);

// END DEBUG

// Turn off light to and await next message


digitalWrite(13, false);
}
}
=======================================================================
108. CONTROL LED BRIGHNESS VIA IR REMOTE

#include <IRremote.h>
int RECV_PIN = 3;
//int OUTPUT_PIN = 4;
IRrecv irrecv(RECV_PIN);
decode_results results;
int pinLED = 5; //don't use pin D11
int brighness = 0;
void setup()
{
Serial.begin(9600);
//pinMode(OUTPUT_PIN, OUTPUT);
pinMode(13, OUTPUT);
pinMode(pinLED, OUTPUT);
irrecv.enableIRIn(); // Start the receiver
}
int on = 0;
unsigned long last = millis();
void loop() {
brighness = constrain(brighness, 0, 255);
analogWrite(pinLED, brighness);
Serial.println(brighness);
delay(20);
if (irrecv.decode(&results)) {
if (results.value == 0xEF1020DF) { //enter you remote code
brighness++;
}
else if (results.value == 0xEF10A05F) { //enter you remote code
brighness--;
}
irrecv.resume(); // Receive the next value
}
}

atau setting brighness disimpan di EEPROM

#include <IRremote.h>
#include <EEPROM.h>
int RECV_PIN = 3;
IRrecv irrecv(RECV_PIN);
decode_results results;
int pinLED = 5; //don't use pin D11
int brighness = 0;
void setup()
{
Serial.begin(9600);
pinMode(pinLED, OUTPUT);
irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();
void loop() {
brighness = constrain(brighness, 0, 255);
if (irrecv.decode(&results)) {
if (results.value == 0xEF1020DF) {
brighness++;
EEPROM.write(1, brighness);
}
else if (results.value == 0xEF10A05F) {
brighness--;
EEPROM.write(1, brighness);
}
irrecv.resume(); // Receive the next value
}
brighness = EEPROM.read(1);
analogWrite(pinLED, brighness);
Serial.println(brighness);
}

Untuk IR sensor, gunakan ground pin yang terpisah.

========================================================
109. DC FAN SPEED CONTROL BY IR REMOTE

Pada proyek ini kita gunakan transistor mosfet RFP30N06LE sebagai switch fan.

#include <IRremote.h>
int RECV_PIN = 3;
//int OUTPUT_PIN = 4;
IRrecv irrecv(RECV_PIN);
decode_results results;
int pinLED = 5; //go to MOSFET input
int SpeedFan = 0;
void setup()
{
Serial.begin(9600);
//pinMode(OUTPUT_PIN, OUTPUT);
pinMode(13, OUTPUT);
pinMode(pinLED, OUTPUT);
irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();
void loop() {
SpeedFan = constrain(SpeedFan, 0, 255);
analogWrite(pinLED, SpeedFan);
Serial.println(SpeedFan);
delay(20);
if (irrecv.decode(&results)) {
if (results.value == 0xEF1020DF) {
SpeedFan++;
}
else if (results.value == 0xEF10A05F) {
SpeedFan--;
}
irrecv.resume(); // Receive the next value
}
}

atau setting speed disimpan pada EEPROM

#include <IRremote.h>
#include <EEPROM.h>
int RECV_PIN = 3;
IRrecv irrecv(RECV_PIN);
decode_results results;
int pinLED = 5; //go to MOSFET input
int SpeedFan = 0;
void setup()
{
Serial.begin(9600);
pinMode(pinLED, OUTPUT);
irrecv.enableIRIn(); // Start the receiver
}

int on = 0;
unsigned long last = millis();
void loop() {
SpeedFan = constrain(SpeedFan, 0, 255);
if (irrecv.decode(&results)) {
if (results.value == 0xEF1020DF) {
SpeedFan++;
EEPROM.write(1, SpeedFan);
}
else if (results.value == 0xEF10A05F) {
SpeedFan--;
EEPROM.write(1, SpeedFan);
}
irrecv.resume(); // Receive the next value
}
SpeedFan = EEPROM.read(1);
analogWrite(pinLED, SpeedFan);
Serial.println(SpeedFan);
}
110. CONTROL KECERAHAN LED BY LDR

int level = 0;
int encoder_pin = 5;
void setup()
{
Serial.begin(9600);
pinMode(encoder_pin, OUTPUT);

}
void loop() {
int sensorValue = analogRead(A0);
level = map(sensorValue, 0, 1023, 255, 0);
analogWrite(encoder_pin, level);
Serial.print(sensorValue);
Serial.print(" ");
Serial.println(level);
}

===============================================================
111. CONTROL LED BRIGHNESS BY SERIAL

#include <avr/interrupt.h>
#include <avr/eeprom.h>
int addr = 1;
int readValue = 0;
int a;
int encoder_pin = 5;
void setup()
{
Serial.begin(9600);
pinMode(encoder_pin, INPUT);
}

void loop() {
if (Serial.available() > 0) {
a = Serial.parseInt();
while (!eeprom_is_ready());
cli();
if(eeprom_read_word((uint16_t*)addr) != a) {
eeprom_write_word((uint16_t*)addr, a);
}
sei();

}
else{
readValue = eeprom_read_word((uint16_t*)addr);
Serial.print("Serial Input = ");
Serial.println(readValue);
readValue = constrain(readValue, 0, 255);
analogWrite(encoder_pin, readValue);
}

===================================================================
112. EEPROM BIG NUMBER AND PWM SETTING

#include <avr/interrupt.h>
#include <avr/eeprom.h>
int addr = 1;
int readValue;
int a;
int b;
int encoder_pin = 5;
void setup()
{
Serial.begin(9600);
pinMode(encoder_pin, INPUT);
}

void loop() {
if (Serial.available() > 0) {
a = Serial.parseFloat();
while (!eeprom_is_ready());
cli();
if(eeprom_read_word((uint16_t*)addr) != a) {
eeprom_write_word((uint16_t*)addr, a);
}
sei();

}
else{
readValue = eeprom_read_word((uint16_t*)addr);
b=readValue*10;
Serial.print("Serial Input = ");
Serial.print(readValue);
Serial.print(" ");
Serial.println(b);
readValue = constrain(readValue, 0, 255);
analogWrite(encoder_pin, readValue);
}

================================================================
113. MOTOR SPEED MEASUREMENT
int encoder_pin = 2; // pulse output from the module
int pulses;
unsigned long timeold;
int pinState = 0;
int lastpinState = 0;
int laju;
int turn;

void setup()
{
Serial.begin(9600);
pinMode(encoder_pin, INPUT);
attachInterrupt(0, counter, FALLING);
pulses = 0;
timeold = 0;
}
void loop()
{
if (millis() - timeold >= 500) {
detachInterrupt(0);
laju=(pulses)*(6.28/10000)*1000*60; //number pulses in 500ms with 20 hole disk
turn=(pulses)/10;
Serial.print(pulses);
Serial.print(" pulses/500ms ");
Serial.print(laju);
Serial.print(" rpm");
Serial.print(" ");
Serial.print(turn);
Serial.println(" turn/second");
timeold = millis();
pulses = 0;
attachInterrupt(0, counter, FALLING);

}
}
void counter()
{
pinState = digitalRead(encoder_pin);
if (pinState != lastpinState) {
if (pinState == HIGH) {
pulses++;
}
lastpinState = pinState;
}
}
===============================================================
114. SPEED CONTROL BY SERIAL

int dir1PinA = 7;
int dir2PinA = 8;
int speedPinA = 9;
#include <avr/interrupt.h>
#include <avr/eeprom.h>
int addr = 1;
int readValue = 0;
int a;

void setup()
{
Serial.begin(9600);
pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
}
void loop()
{
if (Serial.available() > 0) {
a = Serial.parseInt();
while (!eeprom_is_ready());
cli();
if(eeprom_read_word((uint16_t*)addr) != a) {
eeprom_write_word((uint16_t*)addr, a);
}
sei();
}
maju();
Serial.print(" Set point: ");
Serial.println(readValue);
}
void maju(){
readValue = eeprom_read_word((uint16_t*)addr);
readValue = constrain(readValue, 0, 255);
analogWrite(speedPinA, readValue);
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);

}
====================================================================
115. SPEED CONTROL DC MOTOR WITH SPEED SENSOR

int encoder_pin = 2; // pulse output from the module


int pulses;
unsigned long timeold;
int pinState = 0;
int lastpinState = 0;
int laju;
int turn;
int dir1PinA = 7;
int dir2PinA = 8;
int speedPinA = 9;
#include <avr/interrupt.h>
#include <avr/eeprom.h>
int addr = 1;
int readValue = 0;
int a;
int signalPWM = 0;

void setup()
{
Serial.begin(9600);
pinMode(encoder_pin, INPUT);
attachInterrupt(0, counter, FALLING);
pulses = 0;
timeold = 0;
pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
}
void loop()
{
if (Serial.available() > 0) {
a = Serial.parseInt();
while (!eeprom_is_ready());
cli();
if(eeprom_read_word((uint16_t*)addr) != a) {
eeprom_write_word((uint16_t*)addr, a);
}
sei();

}
signalPWM = constrain(signalPWM, 0, 255);
readValue = eeprom_read_word((uint16_t*)addr);
maju();
if (millis() - timeold >= 100) {
detachInterrupt(0);
laju=(pulses)*(6.28/2000)*1000*60; //number pulses in 100ms with 20 hole disk
turn=(pulses)/2;
if (laju <= readValue) {
signalPWM++;
}
else if (laju > readValue) {
signalPWM--;
}
Serial.print(pulses);
Serial.print(" pulses/100ms ");
Serial.print(" Speed: ");
Serial.print(laju);
Serial.print(" rpm ");
Serial.print(turn);
Serial.print(" turn/second ");
Serial.print(" PWM signal: ");
Serial.print(signalPWM);
Serial.print(" Set point: ");
Serial.println(readValue);
timeold = millis();
pulses = 0;
attachInterrupt(0, counter, FALLING);

}
}
void counter()
{
pinState = digitalRead(encoder_pin);
if (pinState != lastpinState) {
if (pinState == HIGH) {
pulses++;
}
lastpinState = pinState;
}
}
void maju(){
readValue = eeprom_read_word((uint16_t*)addr);
analogWrite(speedPinA, signalPWM);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);

====================================================================
116. PASSWORD KEYPAD WITH I2C LCD

#include <Password.h>
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <LCD.h>
#define I2C_ADDR 0x27
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

Password password = Password("12345678"); // password


int dlugosc = 8; // length of the password

int ledRed = 11;


int ledGreen = 12;
int buzzer = 13;

int ilosc; // number of clicks

const byte ROWS = 4; // rows


const byte COLS = 4; // cols

char keys[ROWS][COLS] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

byte rowPins[ROWS] = {5,4,3,2};


byte colPins[COLS] = {9,8,7,6};

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
Serial.begin(9600);
keypad.addEventListener(keypadEvent);
pinMode(ledRed, OUTPUT);
pinMode(ledGreen, OUTPUT);
pinMode(buzzer, OUTPUT);

digitalWrite(ledRed, HIGH);
digitalWrite(ledGreen, LOW);

lcd.begin(16, 2);

lcd.setCursor(1,0);
lcd.print(" :Welcome:");
lcd.setCursor(0,1);
lcd.print("PLEASE ENTER PIN");
}

void loop()
{
keypad.getKey();
}
void keypadEvent(KeypadEvent eKey)
{
switch (keypad.getState())
{
case PRESSED:

int i;
for( i = 1; i <= 1; i++ )
{
digitalWrite(buzzer, HIGH);
delay(50);
digitalWrite(buzzer, LOW);
delay(50);
}

Serial.print("Pressed: ");
Serial.println(eKey);

switch (eKey)
{
/*
case '#':
break;

case '*':
break;
*/

default:
ilosc=ilosc+1;
password.append(eKey);
}
//Serial.println(ilosc);

if(ilosc == 1)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("*_");
}
if(ilosc == 2)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("**_");
}
if(ilosc == 3)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("***_");
}
if(ilosc == 4)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("****_");
}
if(ilosc == 5)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("*****_");
}
if(ilosc == 6)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("******_");
}
if(ilosc == 7)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("*******_");
}
if(ilosc == 8)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("********");
}
if(ilosc == dlugosc)
{
delay(250);
checkPassword();
ilosc = 0;
}
}
}

void checkPassword()
{
if (password.evaluate())
{
int i;
for( i = 1; i <= 2; i++ )
{
digitalWrite(buzzer, HIGH);
delay(70);
digitalWrite(buzzer, LOW);
delay(70);
}
ilosc = 0;
//===============Event that want to do if pin right
Serial.println("Success");

digitalWrite(ledRed, LOW);
digitalWrite(ledGreen, HIGH);

lcd.clear();
lcd.setCursor(0,1);
lcd.print(" << SUCCESS >>");
//======================================================
}
else
{
int i;
for( i = 1; i <= 1; i++ )
{
digitalWrite(buzzer, HIGH);
delay(200);
digitalWrite(buzzer, LOW);
delay(200);
}
ilosc = 0;
password.reset();

Serial.println("Wrong");

digitalWrite(ledGreen, LOW);
digitalWrite(ledRed, HIGH);
lcd.clear();
lcd.setCursor(0,1);
lcd.print(" << WRONG >>");
delay(2000);

lcd.clear();
lcd.setCursor(1,0);
lcd.print(" :Welcome:");
lcd.setCursor(0,1);
lcd.print("PLEASE ENTER PIN");
}
}

other sket with little bit modification

#include <Password.h>
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <LCD.h>
#define I2C_ADDR 0x27
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

Password password = Password("12345678"); // password


int dlugosc = 8; // length of the password

int ledRed = 11;


int ledGreen = 12;
int buzzer = 13;

int ilosc; // number of clicks

const byte ROWS = 4; // rows


const byte COLS = 4; // cols

char keys[ROWS][COLS] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

byte rowPins[ROWS] = {5,4,3,2};


byte colPins[COLS] = {9,8,7,6};

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
Serial.begin(9600);
keypad.addEventListener(keypadEvent);
pinMode(ledRed, OUTPUT);
pinMode(ledGreen, OUTPUT);
pinMode(buzzer, OUTPUT);

digitalWrite(ledRed, HIGH);
digitalWrite(ledGreen, LOW);

lcd.begin(16, 2);

lcd.setCursor(1,0);
lcd.print(" :Welcome:");
lcd.setCursor(0,1);
lcd.print("PLEASE ENTER PIN");
}

void loop()
{
keypad.getKey();
}
void keypadEvent(KeypadEvent eKey)
{
switch (keypad.getState())
{
case PRESSED:

int i;
for( i = 1; i <= 1; i++ )
{
digitalWrite(buzzer, HIGH);
delay(50);
digitalWrite(buzzer, LOW);
delay(50);
}

Serial.print("Pressed: ");
Serial.println(eKey);
switch (eKey)
{
/*
case '#':
break;

case '*':
break;
*/

default:
ilosc=ilosc+1;
password.append(eKey);
}
//Serial.println(ilosc);

if(ilosc == 1)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("*_");
}
if(ilosc == 2)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("**_");
}
if(ilosc == 3)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("***_");
}
if(ilosc == 4)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("****_");
}
if(ilosc == 5)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("*****_");
}
if(ilosc == 6)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("******_");
}
if(ilosc == 7)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("*******_");
}
if(ilosc == 8)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" < PIN >");
lcd.setCursor(0,1);
lcd.print("********");
}

if(ilosc == dlugosc)
{
delay(250);
checkPassword();
ilosc = 0;
}
}
}

void checkPassword()
{
if (password.evaluate())
{
int i;
for( i = 1; i <= 2; i++ )
{
digitalWrite(buzzer, HIGH);
delay(70);
digitalWrite(buzzer, LOW);
delay(70);
}
ilosc = 0;
//===============Event that want to do if pin right
Serial.println("Success");

digitalWrite(ledRed, LOW);
digitalWrite(ledGreen, HIGH);

lcd.clear();
lcd.setCursor(0,1);
lcd.print(" << SUCCESS >>");
password.reset();
delay(3000);
digitalWrite(ledRed, LOW);
digitalWrite(ledGreen, LOW);
lcd.clear();
lcd.setCursor(1,0);
lcd.print(" :Welcome:");
lcd.setCursor(0,1);
lcd.print("PLEASE ENTER PIN");
//======================================================
}
else
{
int i;
for( i = 1; i <= 1; i++ )
{
digitalWrite(buzzer, HIGH);
delay(200);
digitalWrite(buzzer, LOW);
delay(200);
}
ilosc = 0;
password.reset();

Serial.println("Wrong");

digitalWrite(ledGreen, LOW);
digitalWrite(ledRed, HIGH);

lcd.clear();
lcd.setCursor(0,1);
lcd.print(" << WRONG >>");
delay(2000);

lcd.clear();
lcd.setCursor(1,0);
lcd.print(" :Welcome:");
lcd.setCursor(0,1);
lcd.print("PLEASE ENTER PIN");
}
}
117. SEND CHARACTER VIA RF

Transmitter

#include <VirtualWire.h>
char inData[10];
int newmessage = 0;
void setup() {
vw_setup(1000);
vw_set_tx_pin(12);
Serial.begin(9600);
}
void loop()
{
char inChar;
byte index = 0;
char mss[50];
while(Serial.available() > 1){
if(index < 49)
{
delay(10);
inChar = Serial.read();
inData[index] = inChar;
index++;
inData[index] = '\0';
}
newmessage = 1;
}
if(newmessage == 1){
inData[0] = '-';
sprintf(mss, "%s", inData);
vw_send((uint8_t *)mss, strlen(mss));
vw_wait_tx();
Serial.println(mss);
delay(100);
newmessage = 0; // Indicate that there is no new message to wait for the new one
}
}
Receiver

#include <VirtualWire.h>
void setup()
{
Serial.begin(9600);
Serial.println("Listening");
vw_setup(1000);
vw_rx_start();
vw_set_rx_pin(2);
}
void loop()
{
byte message[VW_MAX_MESSAGE_LEN];
byte messageLength = VW_MAX_MESSAGE_LEN;
if (vw_get_message(message, &messageLength))
{
for (int i = 0; i < messageLength; i++)
{
Serial.write(message[i]);
}
Serial.println();
}
}
====================================================================
118. SEVEN SEGMENT

Common Anode

int seg_a = 11; // declare the variables


int seg_b = 10;
int seg_c = 9;
int seg_d = 8;
int seg_e = 7;
int seg_f = 6;
int seg_g = 5;
int seg_dp = 4;
int com = 12;

void setup() {
pinMode(seg_a,OUTPUT); // configure all pins used to outputs
pinMode(seg_b,OUTPUT);
pinMode(seg_c,OUTPUT);
pinMode(seg_d,OUTPUT);
pinMode(seg_e,OUTPUT);
pinMode(seg_f,OUTPUT);
pinMode(seg_g,OUTPUT);
pinMode(seg_dp,OUTPUT);
pinMode(com,OUTPUT);
}

void loop() {
digitalWrite(com,HIGH); // set common anode HIGH (5V)
for (int i = 0; i < 10; i++) { // count 0 - 9
switch(i){ // switch statemet to select the number

case 0: // set relevent segments HIGH and others LOW


digitalWrite(seg_a,LOW);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,HIGH);
break;

case 1:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,HIGH);
break;

case 2:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,HIGH);
break;

case 3:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,HIGH);
break;
case 4:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,HIGH);
break;

case 5:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,HIGH);
break;

case 6:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,HIGH);
break;

case 7:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,HIGH);
break;

case 8:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,HIGH);
break;

case 9:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,HIGH);
break;

}
delay(1000); // Show each number for 1 second
}

Common Cathode

int seg_a = 11; // declare the variables


int seg_b = 10;
int seg_c = 9;
int seg_d = 8;
int seg_e = 7;
int seg_f = 6;
int seg_g = 5;
int seg_dp = 4;
int com = 12;

void setup() {
pinMode(seg_a,OUTPUT); // configure all pins used to outputs
pinMode(seg_b,OUTPUT);
pinMode(seg_c,OUTPUT);
pinMode(seg_d,OUTPUT);
pinMode(seg_e,OUTPUT);
pinMode(seg_f,OUTPUT);
pinMode(seg_g,OUTPUT);
pinMode(seg_dp,OUTPUT);
pinMode(com,OUTPUT);

void loop() {
digitalWrite(com,LOW); // set common anode HIGH (5V)
for (int i = 0; i < 10; i++) { // count 0 - 9
switch(i){ // switch statemet to select the number
case 0: // set relevent segments HIGH and others LOW
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,LOW);
break;

case 1:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,LOW);
break;

case 2:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,LOW);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,LOW);
break;

case 3:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,LOW);
break;

case 4:
digitalWrite(seg_a,LOW);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,LOW);
break;

case 5:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,LOW);
break;

case 6:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,LOW);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,LOW);
break;

case 7:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,LOW);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,LOW);
digitalWrite(seg_g,LOW);
digitalWrite(seg_dp,LOW);
break;

case 8:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,HIGH);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,LOW);
break;

case 9:
digitalWrite(seg_a,HIGH);
digitalWrite(seg_b,HIGH);
digitalWrite(seg_c,HIGH);
digitalWrite(seg_d,HIGH);
digitalWrite(seg_e,LOW);
digitalWrite(seg_f,HIGH);
digitalWrite(seg_g,HIGH);
digitalWrite(seg_dp,LOW);
break;

}
delay(1000); // Show each number for 1 second
}

other sket for common anode

void setup() {
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
writeDot(1); // start with the "dot" off
//writeDot(0); // start with the "dot" on
}

void writeDot(byte dot) {


digitalWrite(4, dot);
}

void loop() {
// write '9'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 0);
digitalWrite(9, 0);
digitalWrite(8, 0);
digitalWrite(7, 1);
digitalWrite(6, 0);
digitalWrite(5, 0);
delay(1000);
// write '8'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 0);
digitalWrite(9, 0);
digitalWrite(8, 0);
digitalWrite(7, 0);
digitalWrite(6, 0);
digitalWrite(5, 0);
delay(1000);
// write '7'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 0);
digitalWrite(9, 0);
digitalWrite(8, 1);
digitalWrite(7, 1);
digitalWrite(6, 1);
digitalWrite(5, 1);
delay(1000);
// write '6'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 1);
digitalWrite(9, 0);
digitalWrite(8, 0);
digitalWrite(7, 0);
digitalWrite(6, 0);
digitalWrite(5, 0);
delay(1000);
// write '5'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 1);
digitalWrite(9, 0);
digitalWrite(8, 0);
digitalWrite(7, 1);
digitalWrite(6, 0);
digitalWrite(5, 0);
delay(1000);
// write '4'
digitalWrite(12, 1);
digitalWrite(11, 1);
digitalWrite(10, 0);
digitalWrite(9, 0);
digitalWrite(8, 1);
digitalWrite(7, 1);
digitalWrite(6, 0);
digitalWrite(5, 0);
delay(1000);
// write '3'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 0);
digitalWrite(9, 0);
digitalWrite(8, 0);
digitalWrite(7, 1);
digitalWrite(6, 1);
digitalWrite(5, 0);
delay(1000);
// write '2'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 0);
digitalWrite(9, 1);
digitalWrite(8, 0);
digitalWrite(7, 0);
digitalWrite(6, 1);
digitalWrite(5, 0);
delay(1000);
// write '1'
digitalWrite(12, 1);
digitalWrite(11, 1);
digitalWrite(10, 0);
digitalWrite(9, 0);
digitalWrite(8, 1);
digitalWrite(7, 1);
digitalWrite(6, 1);
digitalWrite(5, 1);
delay(1000);
// write '0'
digitalWrite(12, 1);
digitalWrite(11, 0);
digitalWrite(10, 0);
digitalWrite(9, 0);
digitalWrite(8, 0);
digitalWrite(7, 0);
digitalWrite(6, 0);
digitalWrite(5, 1);
delay(1000);
}

other sket for common anode

byte seven_seg_digits[10][7] = { { 0,0,0,0,0,0,1 }, // = 0


{ 1,0,0,1,1,1,1 }, // = 1
{ 0,0,1,0,0,1,0 }, // = 2
{ 0,0,0,0,1,1,0 }, // = 3
{ 1,0,0,1,1,0,0 }, // = 4
{ 0,1,0,0,1,0,0 }, // = 5
{ 0,1,0,0,0,0,0 }, // = 6
{ 0,0,0,1,1,1,1 }, // = 7
{ 0,0,0,0,0,0,0 }, // = 8
{ 0,0,0,0,1,0,0 } // = 9
};

void setup() {
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
writeDot(1); // start with the "dot" off
}

void writeDot(byte dot) {


digitalWrite(4, dot);
}

void sevenSegWrite(byte digit) {


byte pin = 11;
for (byte segCount = 0; segCount < 7; ++segCount) {
digitalWrite(pin, seven_seg_digits[digit][segCount]);
--pin;
}
}

void loop() {
digitalWrite(12, HIGH);
for (byte count = 10; count > 0; --count) {
delay(1000);
sevenSegWrite(count - 1);
}
}

====================================================================
119. SEVEN SEGMENT DATA DISPLAY

//for common anode


const int digitPins[4] = {9,10,11,12}; //4 common anode pins of the display
const int clockPin = 6; //74HC595 Pin 6
const int latchPin = 5; //74HC595 Pin 5
const int dataPin = 4; //74HC595 Pin 4
const int tempPin = A0; //data sensor pin
const byte digit[10] = //seven segment digits in bits
{
B00111111, //0
B00000110, //1
B01011011, //2
B01001111, //3
B01100110, //4
B01101101, //5
B01111101, //6
B00000111, //7
B01111111, //8
B01101111 //9
};
int digitBuffer[4] = {
0};
int digitScan = 0, flag=0, soft_scaler = 0;
;
float data;

void setup(){
for(int i=0;i<4;i++)
{
pinMode(digitPins[i],OUTPUT);
}
pinMode(tempPin, INPUT);
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(tempPin, INPUT);
}

//writes the temperature on display


void updateDisp(){
for(byte j=0; j<4; j++)
digitalWrite(digitPins[j], LOW);

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
digitalWrite(latchPin, HIGH);

delayMicroseconds(100);
digitalWrite(digitPins[digitScan], HIGH);

digitalWrite(latchPin, LOW);

//-----------------------remove this part if decimal point not required----------------------------


if(digitScan==2) //where dot decimal placed
shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B10000000)); //print the
decimal point on the 3rd digit
else
//-------------------------------------------------------------------------

shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]);

digitalWrite(latchPin, HIGH);
digitScan++;
if(digitScan>3) digitScan=0;

void loop(){

data = analogRead(tempPin);
digitBuffer[3] = int(data)/1000;
digitBuffer[2] = (int(data)%1000)/100;
digitBuffer[1] = (int(data)%100)/10;
digitBuffer[0] = (int(data)%100)%10;
updateDisp();
delay(2);

}
120. SERIAL MONITOR TO SEVEN SEG DISPLAY

//---------Common Anode----------------------
#include "Timer.h" //include timer library
Timer t; // craete a timer object
long number = 0; //declear the variables
int first_digit = 0;
int second_digit = 0;
int third_digit = 0;
int fourth_digit = 0;
int timer_event = 0;
int CA_1 = 12;
int CA_2 = 11;
int CA_3 = 10;
int CA_4 = 9;
int clk = 6;
int latch = 5;
int data = 4;
int count = 0;
int digits[4] ;
int CAS[4] = {12, 11, 10, 9};
byte numbers[10] {B00000011, B10011111, B00100101, B00001101, B10011001, B01001001,
B01000001, B00011111, B00000001, B00001001};
//byte combinations for each number 0-9
void setup() {
Serial.begin(9600); //serial start and pin config
pinMode(CA_1, OUTPUT);
pinMode(CA_2, OUTPUT);
pinMode(CA_3, OUTPUT);
pinMode(CA_4, OUTPUT);
pinMode(clk, OUTPUT);
pinMode(latch, OUTPUT);
pinMode(data, OUTPUT);
digitalWrite(CA_1, LOW);
digitalWrite(CA_2, LOW);
digitalWrite(CA_3, LOW);
digitalWrite(CA_4, LOW);
Serial.println("please Enter a number from 0 to 9999");
}

void loop() {
t.update(); //timer update
if (Serial.available()) { // read from serial
t.stop(timer_event); //stop timer if anythign to read
cathode_high(); // blank the screen
String s = Serial.readString(); //read the serail value
number = (long)s.toInt(); //convert it to int
if (number > 9999) { //check the number is 0-9999
Serial.println("Please Enter Number Between 0 - 9999");
} else {
break_number(number);
timer_event = t.every(1, display_number); // start timer again
}

void break_number(long num) { // seperate the input number into 4 single digits

first_digit = num / 1000;


digits[0] = first_digit;

int first_left = num - (first_digit * 1000);


second_digit = first_left / 100;
digits[1] = second_digit;
int second_left = first_left - (second_digit * 100);
third_digit = second_left / 10;
digits[2] = third_digit;
fourth_digit = second_left - (third_digit * 10);
digits[3] = fourth_digit;

void display_number() { //scanning

cathode_high(); //black screen


digitalWrite(latch, LOW); //put the shift register to read
shiftOut(data, clk, LSBFIRST, numbers[digits[count]]); //send the data
digitalWrite(CAS[count], HIGH); //turn on the relevent digit
digitalWrite(latch, HIGH); //put the shift register to write mode
count++; //count up the digit
if (count == 4) { // keep the count between 0-3
count = 0;
}

void cathode_high() { //turn off all 4 digits

digitalWrite(CA_1, LOW);
digitalWrite(CA_2, LOW);
digitalWrite(CA_3, LOW);
digitalWrite(CA_4, LOW);
}

For Common Cathode

#include "Timer.h" //include timer library

Timer t; // craete a timer object


long number = 0; //declear the variables
int first_digit = 0;
int second_digit = 0;
int third_digit = 0;
int fourth_digit = 0;
int timer_event = 0;
int CA_1 = 12;
int CA_2 = 11;
int CA_3 = 10;
int CA_4 = 9;
int clk = 6;
int latch = 5;
int data = 4;
int count = 0;
int digits[4] ;
int CAS[4] = {12, 11, 10, 9};
byte numbers[10] {B11111100, B01100000, B11011010, B11110010, B01100110, B10110110,
B10111110, B11100000, B11111110, B11110110};
//byte combinations for each number 0-9
void setup() {
Serial.begin(9600); //serial start and pin config
pinMode(CA_1, OUTPUT);
pinMode(CA_2, OUTPUT);
pinMode(CA_3, OUTPUT);
pinMode(CA_4, OUTPUT);
pinMode(clk, OUTPUT);
pinMode(latch, OUTPUT);
pinMode(data, OUTPUT);
digitalWrite(CA_1, HIGH);
digitalWrite(CA_2, HIGH);
digitalWrite(CA_3, HIGH);
digitalWrite(CA_4, HIGH);
Serial.println("please Enter a number from 0 to 9999");
}

void loop() {
t.update(); //timer update
if (Serial.available()) { // read from serial
t.stop(timer_event); //stop timer if anythign to read
cathode_high(); // blank the screen
String s = Serial.readString(); //read the serail value
number = (long)s.toInt(); //convert it to int
if (number > 9999) { //check the number is 0-9999
Serial.println("Please Enter Number Between 0 - 9999");
} else {
break_number(number);
timer_event = t.every(1, display_number); // start timer again
}

void break_number(long num) { // seperate the input number into 4 single digits

first_digit = num / 1000;


digits[0] = first_digit;

int first_left = num - (first_digit * 1000);


second_digit = first_left / 100;
digits[1] = second_digit;
int second_left = first_left - (second_digit * 100);
third_digit = second_left / 10;
digits[2] = third_digit;
fourth_digit = second_left - (third_digit * 10);
digits[3] = fourth_digit;

void display_number() { //scanning

cathode_high(); //black screen


digitalWrite(latch, LOW); //put the shift register to read
shiftOut(data, clk, LSBFIRST, numbers[digits[count]]); //send the data
digitalWrite(CAS[count], LOW); //turn on the relevent digit
digitalWrite(latch, HIGH); //put the shift register to write mode
count++; //count up the digit
if (count == 4) { // keep the count between 0-3
count = 0;
}

void cathode_high() { //turn off all 4 digits

digitalWrite(CA_1, HIGH);
digitalWrite(CA_2, HIGH);
digitalWrite(CA_3, HIGH);
digitalWrite(CA_4, HIGH);
}

=========================================================
121. ANALOG DATA TO MATRIX DISPLAY

#include <MaxMatrix.h> //include matrix library


const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B00100100, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // DIN pin of MAX7219 module


int load = 10; // CS pin of MAX7219 module
int clock = 11; // CLK pin of MAX7219 module
int maxInUse = 3; //change this variable to set how many MAX7219's you'll use
MaxMatrix m(data, load, clock, maxInUse); // define module
byte buffer[10];

void setup(){
m.init(); // module initialize
m.setIntensity(1); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize

}
void loop(){
m.init();
m.setIntensity(1);
int sensorValue = analogRead(A0);
char sens[4];
itoa(sensorValue,sens,10); //convert int to char!!!!
printString(sens);
Serial.println(sensorValue);
delay(500);

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
122. ULTRASONIC SENSOR WITH LED MATRIX

#include <Wire.h>
#include <MaxMatrix.h> //include matrix library
#include <avr/pgmspace.h>
#include <stdlib.h>
#define trigPin1 2
#define echoPin1 4

long duration, distance, UltraSensor;


const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B00100100, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // DIN pin of MAX7219 module


int load = 10; // CS pin of MAX7219 module
int clock = 11; // CLK pin of MAX7219 module
int maxInUse = 2; //change this variable to set how many MAX7219's you'll use
MaxMatrix m(data, load, clock, maxInUse); // define module
byte buffer[10];

void setup(){
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
m.init(); // module initialize
m.setIntensity(1); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
m.init();
m.setIntensity(1);
SonarSensor(trigPin1, echoPin1);
UltraSensor = distance;
Serial.println(UltraSensor);
char jarak[4];
itoa(UltraSensor,jarak,10); //convert int to char!!!!
printString(jarak);
delay(1000);

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}

void SonarSensor(int trigPin,int echoPin)


{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
delay(100);
}
123. SEND ANALOG DATA TO MATRIX DISPL VIA RF

Receiver

#include <MaxMatrix.h> //include matrix library


#include <VirtualWire.h>
#include <Wire.h>
int ledPin = 13;
int Sensor1Data;
char Sensor1CharMsg[4];
const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B00100100, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // DIN pin of MAX7219 module


int load = 10; // CS pin of MAX7219 module
int clock = 11; // CLK pin of MAX7219 module
int maxInUse = 3; //change this variable to set how many MAX7219's you'll use
MaxMatrix m(data, load, clock, maxInUse); // define module
byte buffer[10];

void setup(){

m.init(); // module initialize


m.setIntensity(1); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
pinMode(ledPin, OUTPUT);
vw_set_ptt_inverted(true);
// Bits per sec
vw_setup(2000);

// Start the receiver PLL running


vw_rx_start();
vw_set_rx_pin(2);
}
void loop(){

uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

// Non-blocking
if (vw_get_message(buf, &buflen))
{
int i;
// Turn on a light to show received good message
digitalWrite(13, true);

// Message with a good checksum received, dump it.


for (i = 0; i < buflen; i++)
{

Sensor1CharMsg[i] = char(buf[i]);
}

Sensor1CharMsg[buflen] = '\0';

// Convert Sensor1CharMsg Char array to integer


Sensor1Data = atoi(Sensor1CharMsg);
m.init();
m.setIntensity(1);
int sensorValue = Sensor1Data;
char sens[4];
itoa(sensorValue,sens,10); //convert int to char!!!!
printString(sens);
Serial.println(sensorValue);

digitalWrite(13, false);
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}
void printStringWithShift(char* s, int shift_speed){
while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}

Transmitter
#include <VirtualWire.h>
#define txPowerPin 8
// LED's
const int ledPin = 13;

// Sensors
const int Sensor1Pin = A2;
// const int Sensor2Pin = 3;
int Sensor1Data;
//int Sensor2Data;
char Sensor1CharMsg[4];

void setup() {
pinMode(txPowerPin, OUTPUT);
pinMode(txPowerPin, LOW);
// PinModes
// LED
pinMode(ledPin,OUTPUT);
// Sensor(s)
pinMode(Sensor1Pin,INPUT);

// for debugging
Serial.begin(9600);

// VirtualWire setup
vw_setup(2000); // Bits per sec
vw_set_tx_pin(12); // VirtualWire transmit pin

void loop() {
digitalWrite(txPowerPin, HIGH);
// Read and store Sensor 1 data
Sensor1Data = analogRead(Sensor1Pin);

// Convert integer data to Char array directly


itoa(Sensor1Data,Sensor1CharMsg,10);

// DEBUG
Serial.print("Sensor1 Integer: ");
Serial.print(Sensor1Data);
Serial.print(" Sensor1 CharMsg: ");
Serial.print(Sensor1CharMsg);
Serial.println(" ");
//delay(1000);

// END DEBUG

digitalWrite(13, true); // Turn on a light to show transmitting


vw_send((uint8_t *)Sensor1CharMsg, strlen(Sensor1CharMsg));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13, false); // Turn off a light after transmission
digitalWrite(txPowerPin, LOW);
delay(1000);

} // END void loop...


124. BODY HEIGHT MEASUREMENT BY ULTRASONIC VIA RF

In this section we try to measure body heigh by ultrasonic distance sensor. Data that get from sensor
send to matrix display via RF. The zero can be adjusted by IR remote. The transmitter must be fixed
above of floor not more than 250 cm.

Transmitter

#include <VirtualWire.h>
#include <EEPROM.h>
#define txPowerPin 8
const int ledPin = 13;
#define trigPin1 2
#define echoPin1 4
long duration, distance, UltraSensor;
int Sensor1Data;
char Sensor1CharMsg[4];
int ZeroCalib = 0;
byte ZeroLevel;
#include <IRremote.h>
int RECV_PIN = 9;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup() {
irrecv.enableIRIn(); // Start the receiver
pinMode(txPowerPin, OUTPUT);
pinMode(txPowerPin, LOW);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(ledPin,OUTPUT);
Serial.begin(9600);
vw_setup(1000); // Bits per sec
vw_set_tx_pin(12); // VirtualWire transmit pin

}
unsigned long last = millis();
void loop() {
ZeroCalib = constrain(ZeroCalib, 0, 255);
if (irrecv.decode(&results)) {
if (results.value == 0xEF1020DF) {
ZeroCalib++;
EEPROM.write(1, ZeroCalib);
}
else if (results.value == 0xEF10A05F) {
ZeroCalib--;
EEPROM.write(1, ZeroCalib);
}
irrecv.resume(); // Receive the next value
}
else{
ZeroLevel = EEPROM.read(1);
SonarSensor(trigPin1, echoPin1);
UltraSensor = ZeroLevel-distance;
digitalWrite(txPowerPin, HIGH);
Sensor1Data = UltraSensor;
// Convert integer data to Char array directly
itoa(Sensor1Data,Sensor1CharMsg,10);
// DEBUG
Serial.print("Sensor1 Integer: ");
Serial.print(Sensor1Data);
Serial.print(" Sensor1 CharMsg: ");
Serial.print(Sensor1CharMsg);
Serial.println(" ");

digitalWrite(13, true); // Turn on a light to show transmitting


vw_send((uint8_t *)Sensor1CharMsg, strlen(Sensor1CharMsg));
vw_wait_tx(); // Wait until the whole message is gone
digitalWrite(13, false); // Turn off a light after transmission
digitalWrite(txPowerPin, LOW);
delay(1000);
}
} // END void loop...
void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
delay(100);
}

Receiver

#include <MaxMatrix.h> //include matrix library


#include <VirtualWire.h>
#include <Wire.h>
int ledPin = 13;
int Sensor1Data;
char Sensor1CharMsg[4];
const PROGMEM prog_uchar CH[] = {
3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B00100100, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // DIN pin of MAX7219 module


int load = 10; // CS pin of MAX7219 module
int clock = 11; // CLK pin of MAX7219 module
int maxInUse = 3; //change this variable to set how many MAX7219's you'll use
MaxMatrix m(data, load, clock, maxInUse); // define module
byte buffer[10];

void setup(){

m.init(); // module initialize


m.setIntensity(1); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
pinMode(ledPin, OUTPUT);
vw_set_ptt_inverted(true);
// Bits per sec
vw_setup(1000);

// Start the receiver PLL running


vw_rx_start();
vw_set_rx_pin(2);
}
void loop(){

uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

// Non-blocking
if (vw_get_message(buf, &buflen))
{
int i;
// Turn on a light to show received good message
digitalWrite(13, true);

// Message with a good checksum received, dump it.


for (i = 0; i < buflen; i++)
{

Sensor1CharMsg[i] = char(buf[i]);
}

Sensor1CharMsg[buflen] = '\0';

// Convert Sensor1CharMsg Char array to integer


Sensor1Data = atoi(Sensor1CharMsg);
m.init();
m.setIntensity(1);
int sensorValue = Sensor1Data;
char sens[4];
itoa(sensorValue,sens,10); //convert int to char!!!!
printString(sens);
Serial.println(sensorValue);

digitalWrite(13, false);
}
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
125. DHT 22 WITH LED MATRIX-RTC

#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
#include <MaxMatrix.h> //include matrix library
const float fVerNum = 0.03;
#include <avr/pgmspace.h>
#include <stdlib.h>
#include "DHT.h" //include the temp sensor library
#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 11 temp&humid sensor
DHT dht(DHTPIN, DHTTYPE);

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B00100100, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // DIN pin of MAX7219 module


int load = 10; // CS pin of MAX7219 module
int clock = 11; // CLK pin of MAX7219 module
int maxInUse = 8; //change this variable to set how many MAX7219's you'll use
MaxMatrix m(data, load, clock, maxInUse); // define module
byte buffer[10];

void setup(){
//pinMode(2,INPUT); //button input
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
Serial.println("DHTxx test!");
dht.begin();
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
}

void loop(){

float t = dht.readTemperature();
float h = dht.readHumidity();
char temp[4];
char hum[4];
itoa(t,temp,10); //convert int to char!!!!
itoa(h,hum,10); //convert int to char!!!!
DateTime now = RTC.now();

int mt = (now.month());
int dy = (now.day());
int y = (now.year());
int jm = (now.hour());
int men = (now.minute());
int dt = (now.second());
char tahun[5];
char bulan[4];
char tanggal[4];
char jam[4];
char menit[4];
char detik[4];

itoa(mt,bulan,10); //convert int to char!!!!


itoa(dy,tanggal,10); //convert int to char!!!!
itoa(y,tahun,10); //convert int to char!!!!
itoa(jm,jam,10); //convert int to char!!!!
itoa(men,menit,10); //convert int to char!!!!
itoa(dt,detik,10); //convert int to char!!!!

if(now.dayOfWeek()==1){
printStringWithShift("MONDAY", 100);
}
if(now.dayOfWeek()==2){
printStringWithShift("TUESDAY", 100);
}
if(now.dayOfWeek()==3){
printStringWithShift("WEDNESDAY", 100);
}
if(now.dayOfWeek()==4){
printStringWithShift("THURSDAY", 100);
}
if(now.dayOfWeek()==5){
printStringWithShift("FRIDAY", 100);
}
if(now.dayOfWeek()==6){
printStringWithShift("SATURDAY", 100);
}
if(now.dayOfWeek()==0){
printStringWithShift("SUNDAY", 100);
}
printStringWithShift(" ", 100);
printStringWithShift(tanggal, 100);
printStringWithShift("/", 100);
printStringWithShift(bulan, 100);
printStringWithShift("/", 100);
printStringWithShift(tahun, 100);
printStringWithShift(" ", 100);
printStringWithShift(jam, 100);
printStringWithShift(":", 100);
printStringWithShift(menit, 100);
printStringWithShift(":", 100);
printStringWithShift(detik, 100);
printStringWithShift(" ", 100);
printStringWithShift("temp: ", 100);
printStringWithShift(temp, 100);
printStringWithShift(" C ", 100);
printStringWithShift("humidity: ", 100);
printStringWithShift(hum, 100);
printStringWithShift(" % ", 100);
printStringWithShift(" ", 100);

m.shiftLeft(false, true);
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
====================================================================
126. CONTROL SERVO BY MOUSE

Arduino Sketch

#include <Servo.h>

Servo servo1; Servo servo2;

void setup() {

pinMode(1,OUTPUT);
servo1.attach(14); //analog pin 0
//servo1.setMaximumPulse(2000);
//servo1.setMinimumPulse(700);

servo2.attach(15); //analog pin 1


Serial.begin(19200);
Serial.println("Ready");

void loop() {

static int v = 0;
if ( Serial.available()) {
char ch = Serial.read();

switch(ch) {
case '0'...'9':
v = v * 10 + ch - '0';
break;
case 's':
servo1.write(v);
v = 0;
break;
case 'w':
servo2.write(v);
v = 0;
break;
case 'd':
servo2.detach();
break;
case 'a':
servo2.attach(15);
break;
}
}

//Servo::refresh();

Processing sketch

/**
* Servocontrol (derived from processing Mouse 1D example.)
*
* Updated 24 November 2007
*/

// Use the included processing code serial library


import processing.serial.*;

int gx = 15;
int gy = 35;
int spos1=90;
int spos2=90;

float leftColor = 0.0;


float rightColor = 0.0;
Serial port; // The serial port
void setup()
{
size(720, 720);
colorMode(RGB, 1.0);
noStroke();
rectMode(CENTER);
frameRate(100);

println(Serial.list()); // List COM-ports

//select second com-port from the list


port = new Serial(this, Serial.list()[1], 19200);
}

void draw()
{
background(0.0);
update(mouseX,mouseY);
/*
fill(mouseX/4);
rect(150, 320, gx*2, gx*2);
fill(180 - (mouseX/4));
rect(450, 320, gy*2, gy*2);
*/
}

void update(int x,int y)


{
//Calculate servo postion from mouseX
spos1= x/4;
spos2= y/4;

//Output the servo position ( from 0 to 180)


port.write("s"+spos1);
port.write("w"+spos2);

// Just some graphics


leftColor = -0.002 * x/2 + 0.06;
rightColor = 0.002 * x/2 + 0.06;

gx = x/2;
gy = 100-x/2;

}
127. SETUP BLUETOOTH MODULE AS MASTER OR SLAVE

Wiring arduino and bluetooth module as above. Upload this sketch

#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.

char c = ' ';

void setup()
{
Serial.begin(9600);
Serial.println("Arduino is ready");
Serial.println("Remember to select Both NL & CR in the serial monitor");

// HC-05 default serial speed for AT mode is 38400


BTserial.begin(38400);
}

void loop()
{

// Keep reading from HC-05 and send to Arduino Serial Monitor


if (BTserial.available())
{
c = BTserial.read();
Serial.write(c);
}

// Keep reading from Arduino Serial Monitor and send to HC-05


if (Serial.available())
{
c = Serial.read();
BTserial.write(c);
}

Prefer upload with Arduino IDE version 1.6.xx.


After upload completted, disconnect VCC jumper from bluetooth module, than press small button
on the bluetooth module, hold press and reconnect VCC jumper to bluetooth module, than release
button, LED on module will flushing every two second, module now ready to be in AT command.
Next, open serial monitor with baud rate 9600 and Both NL & CR, than follow below steps :

Setup for slave :


type AT than enter, it will get message OK,
type AT+ROLE=0 than enter, it will get message OK,
type AT+ADDR? it will get message +ADDR:2016:10:315904 -------> write this number on paper,
this will be used for address bind to master.
Now slave module ready to be used,

Setup for master:


type AT than enter, it will get message OK,
type AT+ROLE=1 than enter, it will get message OK,
type AT+CMODE=0 it will get message OK,
type AT+BIND=2016,10,315904, it will get message OK,
Now master module ready to be used,
128. SEND ANALOG DATA ARDUINO TO ARDUINO VIA BLUETOOTH

First step we have to setup one bluetooth module as master and other one as slave. The master or
slave we can use for transmitter or receiver.

int potValue = 0;
void setup() {
Serial.begin(9600); // Default communication rate of the Bluetooth module
}
void loop() {
potValue = analogRead(A0);
//int potValueMapped = map(potValue, 0, 1023, 0, 180);
Serial.println(potValue); // Sends potValue to servo motor
delay(100);
}
int state = 0;
int buttonState = 0;
void setup() {
Serial.begin(9600); // Default communication rate of the Bluetooth module
}
void loop() {
if(Serial.available() > 0){ // Checks whether data is comming from the serial port
int state = Serial.parseInt(); // Reads the data from the serial port
Serial.println(state);
}
}
129. CONTROL SERVO VIA BLUETOOTH

int potValue = 0;
void setup() {
Serial.begin(9600); // Default communication rate of the Bluetooth module
}
void loop() {
potValue = analogRead(A0);
int potValueMapped = map(potValue, 0, 1023, 0, 180);
Serial.println(potValueMapped); // Sends potValue to servo motor
delay(10);
}
#include <Servo.h>
Servo myServo;
int state = 0;
int buttonState = 0;
void setup() {
myServo.attach(9);
Serial.begin(9600); // Default communication rate of the Bluetooth module
}
void loop() {
if(Serial.available() > 0){ // Checks whether data is comming from the serial port
int state = Serial.parseInt(); // Reads the data from the serial port
Serial.println(state);
myServo.write(state);
}
}
130. SEND ANALOG DATA ARDUINO TO ARDUINO VIA BLUETOOTH BY LED MATRIX

#include <MaxMatrix.h>
#include <avr/pgmspace.h>

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 3; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];
int state = 0;
void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
if(Serial.available() > 0){
// Checks whether data is comming from the serial port
int state = Serial.parseInt(); // Reads the data from the serial port
char value[10];
itoa(state,value,10);
Serial.println(state);
m.init();
m.setIntensity(0);
printString(value);
}
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
int potValue = 0;
void setup() {
Serial.begin(9600); // Default communication rate of the Bluetooth module
}
void loop() {
potValue = analogRead(A0);
Serial.println(potValue); // Sends potValue to servo motor
delay(1000);
}
131. BODY HEIGHT MEASUREMENT BY ULTRASONIC VIA BLUETOOTH

#include <EEPROM.h>
#define trigPin1 2
#define echoPin1 4
long duration, distance, UltraSensor;
int Sensor1Data;
int ZeroCalib = 0;
byte ZeroLevel;
#include <IRremote.h>
int RECV_PIN = 9;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup() {
irrecv.enableIRIn(); // Start the receiver
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
Serial.begin(9600);
}
unsigned long last = millis();
void loop() {
ZeroCalib = constrain(ZeroCalib, 0, 255);
if (irrecv.decode(&results)) {
if (results.value == 0xEF1020DF) {
ZeroCalib++;
EEPROM.write(1, ZeroCalib);
}
else if (results.value == 0xEF10A05F) {
ZeroCalib--;
EEPROM.write(1, ZeroCalib);
}
irrecv.resume(); // Receive the next value
}
else{
ZeroLevel = EEPROM.read(1);
SonarSensor(trigPin1, echoPin1);
UltraSensor = ZeroLevel-distance;
Sensor1Data = UltraSensor;
Serial.print("Sensor1 Integer: ");
Serial.println(Sensor1Data);
delay(1000);
}
} // END void loop...
void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
delay(100);
}

#include <MaxMatrix.h>
#include <avr/pgmspace.h>

const PROGMEM prog_uchar CH[] = {


3, 8, B00000000, B00000000, B00000000, B00000000, B00000000, // space
1, 8, B01011111, B00000000, B00000000, B00000000, B00000000, // !
3, 8, B00000011, B00000000, B00000011, B00000000, B00000000, // "
5, 8, B00010100, B00111110, B00010100, B00111110, B00010100, // #
4, 8, B00100100, B01101010, B00101011, B00010010, B00000000, // $
5, 8, B01100011, B00010011, B00001000, B01100100, B01100011, // %
5, 8, B00110110, B01001001, B01010110, B00100000, B01010000, // &
1, 8, B00000011, B00000000, B00000000, B00000000, B00000000, // '
3, 8, B00011100, B00100010, B01000001, B00000000, B00000000, // (
3, 8, B01000001, B00100010, B00011100, B00000000, B00000000, // )
5, 8, B00101000, B00011000, B00001110, B00011000, B00101000, // *
5, 8, B00001000, B00001000, B00111110, B00001000, B00001000, // +
2, 8, B10110000, B01110000, B00000000, B00000000, B00000000, // ,
4, 8, B00001000, B00001000, B00001000, B00001000, B00000000, // -
2, 8, B01100000, B01100000, B00000000, B00000000, B00000000, // .
4, 8, B01100000, B00011000, B00000110, B00000001, B00000000, // /
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // 0
3, 8, B01000010, B01111111, B01000000, B00000000, B00000000, // 1
4, 8, B01100010, B01010001, B01001001, B01000110, B00000000, // 2
4, 8, B00100010, B01000001, B01001001, B00110110, B00000000, // 3
4, 8, B00011000, B00010100, B00010010, B01111111, B00000000, // 4
4, 8, B00100111, B01000101, B01000101, B00111001, B00000000, // 5
4, 8, B00111110, B01001001, B01001001, B00110000, B00000000, // 6
4, 8, B01100001, B00010001, B00001001, B00000111, B00000000, // 7
4, 8, B00110110, B01001001, B01001001, B00110110, B00000000, // 8
4, 8, B00000110, B01001001, B01001001, B00111110, B00000000, // 9
2, 8, B01010000, B00000000, B00000000, B00000000, B00000000, // :
2, 8, B10000000, B01010000, B00000000, B00000000, B00000000, // ;
3, 8, B00010000, B00101000, B01000100, B00000000, B00000000, // <
3, 8, B00010100, B00010100, B00010100, B00000000, B00000000, // =
3, 8, B01000100, B00101000, B00010000, B00000000, B00000000, // >
4, 8, B00000010, B01011001, B00001001, B00000110, B00000000, // ?
5, 8, B00111110, B01001001, B01010101, B01011101, B00001110, // @
4, 8, B01111110, B00010001, B00010001, B01111110, B00000000, // A
4, 8, B01111111, B01001001, B01001001, B00110110, B00000000, // B
4, 8, B00111110, B01000001, B01000001, B00100010, B00000000, // C
4, 8, B01111111, B01000001, B01000001, B00111110, B00000000, // D
4, 8, B01111111, B01001001, B01001001, B01000001, B00000000, // E
4, 8, B01111111, B00001001, B00001001, B00000001, B00000000, // F
4, 8, B00111110, B01000001, B01001001, B01111010, B00000000, // G
4, 8, B01111111, B00001000, B00001000, B01111111, B00000000, // H
3, 8, B01000001, B01111111, B01000001, B00000000, B00000000, // I
4, 8, B00110000, B01000000, B01000001, B00111111, B00000000, // J
4, 8, B01111111, B00001000, B00010100, B01100011, B00000000, // K
4, 8, B01111111, B01000000, B01000000, B01000000, B00000000, // L
5, 8, B01111111, B00000010, B00001100, B00000010, B01111111, // M
5, 8, B01111111, B00000100, B00001000, B00010000, B01111111, // N
4, 8, B00111110, B01000001, B01000001, B00111110, B00000000, // O
4, 8, B01111111, B00001001, B00001001, B00000110, B00000000, // P
4, 8, B00111110, B01000001, B01000001, B10111110, B00000000, // Q
4, 8, B01111111, B00001001, B00001001, B01110110, B00000000, // R
4, 8, B01000110, B01001001, B01001001, B00110010, B00000000, // S
5, 8, B00000001, B00000001, B01111111, B00000001, B00000001, // T
4, 8, B00111111, B01000000, B01000000, B00111111, B00000000, // U
5, 8, B00001111, B00110000, B01000000, B00110000, B00001111, // V
5, 8, B00111111, B01000000, B00111000, B01000000, B00111111, // W
5, 8, B01100011, B00010100, B00001000, B00010100, B01100011, // X
5, 8, B00000111, B00001000, B01110000, B00001000, B00000111, // Y
4, 8, B01100001, B01010001, B01001001, B01000111, B00000000, // Z
2, 8, B01111111, B01000001, B00000000, B00000000, B00000000, // [
4, 8, B00000001, B00000110, B00011000, B01100000, B00000000, // \ backslash
2, 8, B01000001, B01111111, B00000000, B00000000, B00000000, // ]
3, 8, B00000010, B00000001, B00000010, B00000000, B00000000, // hat
4, 8, B01000000, B01000000, B01000000, B01000000, B00000000, // _
2, 8, B00000001, B00000010, B00000000, B00000000, B00000000, // `
4, 8, B00100000, B01010100, B01010100, B01111000, B00000000, // a
4, 8, B01111111, B01000100, B01000100, B00111000, B00000000, // b
4, 8, B00111000, B01000100, B01000100, B00101000, B00000000, // c
4, 8, B00111000, B01000100, B01000100, B01111111, B00000000, // d
4, 8, B00111000, B01010100, B01010100, B00011000, B00000000, // e
3, 8, B00000100, B01111110, B00000101, B00000000, B00000000, // f
4, 8, B10011000, B10100100, B10100100, B01111000, B00000000, // g
4, 8, B01111111, B00000100, B00000100, B01111000, B00000000, // h
3, 8, B01000100, B01111101, B01000000, B00000000, B00000000, // i
4, 8, B01000000, B10000000, B10000100, B01111101, B00000000, // j
4, 8, B01111111, B00010000, B00101000, B01000100, B00000000, // k
3, 8, B01000001, B01111111, B01000000, B00000000, B00000000, // l
5, 8, B01111100, B00000100, B01111100, B00000100, B01111000, // m
4, 8, B01111100, B00000100, B00000100, B01111000, B00000000, // n
4, 8, B00111000, B01000100, B01000100, B00111000, B00000000, // o
4, 8, B11111100, B00100100, B00100100, B00011000, B00000000, // p
4, 8, B00011000, B00100100, B00100100, B11111100, B00000000, // q
4, 8, B01111100, B00001000, B00000100, B00000100, B00000000, // r
4, 8, B01001000, B01010100, B01010100, B00100100, B00000000, // s
3, 8, B00000100, B00111111, B01000100, B00000000, B00000000, // t
4, 8, B00111100, B01000000, B01000000, B01111100, B00000000, // u
5, 8, B00011100, B00100000, B01000000, B00100000, B00011100, // v
5, 8, B00111100, B01000000, B00111100, B01000000, B00111100, // w
5, 8, B01000100, B00101000, B00010000, B00101000, B01000100, // x
4, 8, B10011100, B10100000, B10100000, B01111100, B00000000, // y
3, 8, B01100100, B01010100, B01001100, B00000000, B00000000, // z
3, 8, B00001000, B00110110, B01000001, B00000000, B00000000, // {
1, 8, B01111111, B00000000, B00000000, B00000000, B00000000, // |
3, 8, B01000001, B00110110, B00001000, B00000000, B00000000, // }
4, 8, B00001000, B00000100, B00001000, B00000100, B00000000, // ~
};

int data = 12; // 8, DIN pin of MAX7219 module


int load = 10; // 9, CS pin of MAX7219 module
int clock = 11; // 10, CLK pin of MAX7219 module

int maxInUse = 3; //change this variable to set how many MAX7219's you'll use

MaxMatrix m(data, load, clock, maxInUse); // define module

byte buffer[10];
int state = 0;
void setup(){
m.init(); // module initialize
m.setIntensity(0); // dot matix intensity 0-15
Serial.begin(9600); // serial communication initialize
}

void loop(){
if(Serial.available() > 0){
// Checks whether data is comming from the serial port
int state = Serial.parseInt(); // Reads the data from the serial port
char value[10];
itoa(state,value,10);
Serial.println(state);
m.init();
m.setIntensity(0);
printString(value);
}
}

void printCharWithShift(char c, int shift_speed){


if (c < 32) return;
c -= 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(maxInUse*8, 0, buffer);
m.setColumn(maxInUse*8 + buffer[0], 0);

for (int i=0; i<buffer[0]+1; i++)


{
delay(shift_speed);
m.shiftLeft(false, false);
}
}

void printStringWithShift(char* s, int shift_speed){


while (*s != 0){
printCharWithShift(*s, shift_speed);
s++;
}
}

void printString(char* s)
{
int col = 0;
while (*s != 0)
{
if (*s < 32) continue;
char c = *s - 32;
memcpy_P(buffer, CH + 7*c, 7);
m.writeSprite(col, 0, buffer);
m.setColumn(col + buffer[0], 0);
col += buffer[0] + 1;
s++;
}
}
132. PIR ALARM VIA RF

int led = 13;


int speaker = 10;
#define wait 1
#define time 100
int freq = 0;
#include <VirtualWire.h>
void setup(){
Serial.begin(9600); // Debugging only
vw_setup(2000);
vw_set_rx_pin(11);
vw_rx_start();
pinMode(speaker, OUTPUT);
pinMode(led, OUTPUT);
}
void loop(){
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen))
{
for (int i = 0; i < buflen; i++)
{
if(buf[i] == 'A') {
digitalWrite(led, HIGH);
digitalWrite(speaker, HIGH);
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000; freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker,
freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500;
freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
} if(buf[i] == 'a')
{ digitalWrite(led, LOW); digitalWrite(speaker, LOW);
}
}
}
}

int pirPin = 2;
int statePir = 0;
#include <VirtualWire.h>
void setup(){
Serial.begin(9600);
vw_setup(2000);
vw_set_tx_pin(3);
pinMode(pirPin,INPUT);
}
void loop(){
statePir = digitalRead(pirPin);
if (statePir == HIGH){
const char *msg = "A";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if (statePir == LOW){
const char *msg = "a";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
}
133. RFID READ CODE

/*
* --------------------------------------------------------------------------------------------------------------------
* Example sketch/program showing how to read data from a PICC to serial.
* --------------------------------------------------------------------------------------------------------------------
* This is a MFRC522 library example; for further details and other examples see:
https://github.com/miguelbalboa/rfid
*
* Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card)
using a MFRC522 based RFID
* Reader on the Arduino SPI interface.
*
* When the Arduino and the MFRC522 module are connected (see the pin layout below), load this
sketch into Arduino IDE
* then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit
Ctrl+Shft+M). When
* you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522
Reader/PCD, the serial output
* will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in
communication" messages
* when removing the PICC from reading distance too early.
*
* If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple
tag reading).
* So if you stack two or more PICCs on top of each other and present them to the reader, it will
first output all
* details of the first and then the next PICC. Note that this may take some time as all data blocks
are dumped, so
* keep the PICCs at reading distance until complete.
*
* @license Released into the public domain.
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9 // Configurable, see typical pin layout above


#define SS_PIN 10 // Configurable, see typical pin layout above

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

void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos
based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card
Reader details
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

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

// Select one of the cards


if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}

// Dump debug info about the card; PICC_HaltA() is automatically called


mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
134. RFID LIGHT SWITCH

/*
*
* All the resources for this project: https://www.hackster.io/Aritro
* Modified by Aritro Mukherjee
*
*
*/
int led = 5; //bring the signal to relay when used for drive high voltage power
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
MFRC522::MIFARE_Key key;
void setup()
{
pinMode(led, OUTPUT);
Serial.begin(9600); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println("Approximate your card to the reader...");
Serial.println();
//dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
}
int on = 0;
void loop()
{
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("UID tag :");
String content= "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.print("Message : ");
content.toUpperCase();
//if ((content.substring(1) == "E0 7C F4 79") || (content.substring(1) == "A0 D1 39 83" )) //change
here the UID of the card/cards that you want to give access
if (content.substring(1) == "E0 7C F4 79")// single card
{
Serial.println("Authorized access");
on = !on;
digitalWrite(led, on? HIGH:LOW);
Serial.println(on?"ON":"OFF");
//Serial.println();
delay(1000);
}

else {
Serial.println(" Access denied");
digitalWrite(led, LOW);
delay(1000);
}
}
135. RFID ROOM POWER SWITCH

#include <SPI.h>
#include <Wire.h>
#include <MFRC522.h>
#define RST_PIN 9
#define SS_PIN 10

#define address 2
int led = 5; //bring the signal to relay when used for drive high voltage power
uint16_t xor_uid = 0;

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

void setup()
{
pinMode(led, OUTPUT);
SPI.begin(); // Init SPI bus
Serial.begin(9600);
mfrc522.PCD_Init(); // Init MFRC522
Wire.begin(address);
Wire.onRequest(sendCardInfo); // register event
//mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
}

uint16_t read_card() {
uint16_t xor_uid = 0;
if (! mfrc522.PICC_ReadCardSerial())
{ //Okay. This does the same PICC_Select as the previous ReadCardSerial(), but this one fails if
there is no card on the reader. Funny.
//Seems like we need two Select's in a row to detect card's presence.
xor_uid = 0;
Serial.println("NOK");
digitalWrite(led, LOW);
}
else
{
for (int i = 0; i < mfrc522.uid.size; i=i+2)
{
xor_uid = xor_uid ^ (mfrc522.uid.uidByte[i]<<8 | mfrc522.uid.uidByte[i+1]);
}
Serial.println("OK");
digitalWrite(led, HIGH);
}
return xor_uid;
}

void loop()
{
mfrc522.PICC_ReadCardSerial(); //Always fails
mfrc522.PICC_IsNewCardPresent(); //Does RequestA
xor_uid = read_card();
delay(1);
}

void sendCardInfo() {
byte myArray[2]; //Thanks http://thewanderingengineer.com/2015/05/06/sending-16-bit-and-32-bit-
numbers-with-arduino-i2c for this solution
myArray[0] = (xor_uid >> 8) & 0xFF;
myArray[1] = xor_uid & 0xFF;
Wire.write(myArray, 2);
}
136. RFID ROOM DOOR KEY

/*
*
* All the resources for this project: https://www.hackster.io/Aritro
* Modified by Aritro Mukherjee
*
*
*/
int led = 5; //bring the signal to relay when used for drive high voltage power
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
MFRC522::MIFARE_Key key;
void setup()
{
pinMode(led, OUTPUT);
Serial.begin(9600); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println("Approximate your card to the reader...");
Serial.println();
//dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
}
int on = 0;
void loop()
{
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("UID tag :");
String content= "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.print("Message : ");
content.toUpperCase();
if ((content.substring(1) == "E0 7C F4 79") || (content.substring(1) == "A0 D1 39 83")) //change
here the UID of the card/cards that you want to give access
{
Serial.println("Authorized access");
//on = !on;
digitalWrite(led,HIGH);
Serial.println("UNLOCK");
//Serial.println();
delay(3000);
digitalWrite(led,LOW);
Serial.println("LOCK");
}

else {
Serial.println(" Access denied");
digitalWrite(led, LOW);
delay(1000);
}
}

=====================================================================
137. LED LEVEL INDICATOR

int clockPin = 11;


int latchPin = 12;
int dataPin = 13;
byte possible_patterns[17] = {
B00000000,
B11100001,
B11010001,
B10110001,
B01110001,

B11100010,
B11010010,
B10110010,
B01110010,

B11100100,
B11010100,
B10110100,
B01110100,

B11101000,
B11011000,
B10111000,
B01111000,

};
int proximity=0;
void setup() {
Serial.begin (9600);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
int sensorValue = analogRead(A0);
digitalWrite(latchPin, LOW);
Serial.println(sensorValue);
proximity=map(sensorValue, 0, 1024, 0, 17);
shiftOut(dataPin, clockPin, MSBFIRST,possible_patterns[proximity]);
digitalWrite(latchPin, HIGH);
}
138. LED BAR LEVEL INDICATOR

//Pin connected to ST_CP of 74HC595


int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

//holders for infromation you're going to pass to shifting function


byte dataRED;
byte dataGREEN;
byte dataBLUE;
byte dataArrayRED[25];
byte dataArrayGREEN[25];
byte dataArrayBLUE[25];

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
Serial.begin(9600);

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.
dataArrayGREEN[0] = 0x00; //00000000
dataArrayGREEN[1] = 0x80; //00000001
dataArrayGREEN[2] = 0xC0; //00000011
dataArrayGREEN[3] = 0xE0; //00000111
dataArrayGREEN[4] = 0xF0; //00001111
dataArrayGREEN[5] = 0xF8; //00011111
dataArrayGREEN[6] = 0xFC; //00111111
dataArrayGREEN[7] = 0xFE; //01111111
dataArrayGREEN[8] = 0xFF; //11111111
dataArrayGREEN[9] = 0xFF; //11111111
dataArrayGREEN[10] = 0xFF; //11111111
dataArrayGREEN[11] = 0xFF; //11111111
dataArrayGREEN[12] = 0xFF; //11111111
dataArrayGREEN[13] = 0xFF; //11111111
dataArrayGREEN[14] = 0xFF; //11111111
dataArrayGREEN[15] = 0xFF; //11111111
dataArrayGREEN[16] = 0xFF; //11111111
dataArrayGREEN[17] = 0xFF; //11111111
dataArrayGREEN[18] = 0xFF; //11111111
dataArrayGREEN[19] = 0xFF; //11111111
dataArrayGREEN[20] = 0xFF; //11111111
dataArrayGREEN[21] = 0xFF; //11111111
dataArrayGREEN[22] = 0xFF; //11111111
dataArrayGREEN[23] = 0xFF; //11111111
dataArrayGREEN[24] = 0xFF; //11111111

//Arduino doesn't seem to have a way to write binary straight into the code
//so these values are in HEX. Decimal would have been fine, too.
dataArrayRED[0] = 0x00; //11111111
dataArrayRED[1] = 0x00; //00000000
dataArrayRED[2] = 0x00; //00000000
dataArrayRED[3] = 0x00; //00000000
dataArrayRED[4] = 0x00; //00000000
dataArrayRED[5] = 0x00; //00000000
dataArrayRED[6] = 0x00; //00000000
dataArrayRED[7] = 0x00; //00000000
dataArrayRED[8] = 0x00; //00000000
dataArrayRED[9] = 0x80; //10000000
dataArrayRED[10] = 0xC0; //11000000
dataArrayRED[11] = 0xE0; //11100000
dataArrayRED[12] = 0xF0; //11110000
dataArrayRED[13] = 0xF8; //11111000
dataArrayRED[14] = 0xFC; //11111100
dataArrayRED[15] = 0xFE; //11111110
dataArrayRED[16] = 0xFF; //11111111
dataArrayRED[17] = 0xFF; //11111111
dataArrayRED[18] = 0xFF; //11111111
dataArrayRED[19] = 0xFF; //11111111
dataArrayRED[20] = 0xFF; //11111111
dataArrayRED[21] = 0xFF; //11111111
dataArrayRED[22] = 0xFF; //11111111
dataArrayRED[23] = 0xFF; //11111111
dataArrayRED[24] = 0xFF; //11111111

dataArrayBLUE[0] = 0x00; //00000000


dataArrayBLUE[1] = 0x00; //00000000
dataArrayBLUE[2] = 0x00; //00000000
dataArrayBLUE[3] = 0x00; //00000000
dataArrayBLUE[4] = 0x00; //00000000
dataArrayBLUE[5] = 0x00; //00000000
dataArrayBLUE[6] = 0x00; //00000000
dataArrayBLUE[7] = 0x00; //00000000
dataArrayBLUE[8] = 0x00; //00000000
dataArrayBLUE[9] = 0x00; //00000000
dataArrayBLUE[10] = 0x00; //00000000
dataArrayBLUE[11] = 0x00; //00000000
dataArrayBLUE[12] = 0x00; //00000000
dataArrayBLUE[13] = 0x00; //00000000
dataArrayBLUE[14] = 0x00; //00000000
dataArrayBLUE[15] = 0x00; //00000000
dataArrayBLUE[16] = 0x00; //00000000
dataArrayBLUE[17] = 0x80; //10000000
dataArrayBLUE[18] = 0xC0; //11000000
dataArrayBLUE[19] = 0xE0; //11100000
dataArrayBLUE[20] = 0xF0; //11110000
dataArrayBLUE[21] = 0xF8; //11111000
dataArrayBLUE[22] = 0xFC; //11111100
dataArrayBLUE[23] = 0xFE; //11111110
dataArrayBLUE[24] = 0xFF; //11111111

//function that blinks all the LEDs


//gets passed the number of blinks and the pause time
blinkAll_2Bytes(2,300);
}
int proximity=0;
void loop() {
int sensorValue = analogRead(A0);
proximity=map(sensorValue, 0, 1023, 0, 25);
Serial.println(sensorValue);
//for (int j = 0; j < 24; j++) {
//load the light sequence you want from array
dataGREEN = dataArrayGREEN[proximity];
dataRED = dataArrayRED[proximity];
dataBLUE = dataArrayBLUE[proximity];

//ground latchPin and hold low for as long as you are transmitting
digitalWrite(latchPin, 1);
//move 'em out
shiftOut(dataPin, clockPin, dataGREEN);
shiftOut(dataPin, clockPin, dataRED);
shiftOut(dataPin, clockPin, dataBLUE);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, 0);
//delay(100);
//}
}
// the heart of the program
void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low

//internal function setup


int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);

//clear everything out just in case to


//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);

//for each bit in the byte myDataOut�


//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);

//if the value passed to myDataOut and a bitmask result


// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}

//Sets the pin to HIGH or LOW depending on pinState


digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}

//stop shifting
digitalWrite(myClockPin, 0);
}

//blinks the whole register based on the number of times you want to
//blink "n" and the pause between them "d"
//starts with a moment of darkness to make sure the first blink
//has its full visual effect.
void blinkAll_2Bytes(int n, int d) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(200);
for (int x = 0; x < n; x++) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
digitalWrite(latchPin, 1);
delay(d);
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
}
===================================================================
139. OSCILOSCOPE

//Arduino Code:

#define ANALOG_IN 0
void setup() {
Serial.begin(9600);
//Serial.begin(115200);
}
void loop() {
int val = analogRead(ANALOG_IN);
Serial.write( 0xff );
Serial.write( (val >> 8) & 0xff );
Serial.write( val & 0xff );
}

-----------------------------------------------------

//Proscessing code:

import processing.serial.*;
Serial port; // Create object from Serial class
int val;
// Data received from the serial port
int[] values;
float zoom;
void setup()
{
size(1280, 480);
// Open the port that the board is connected to and use the same speed (9600 bps)
port = new Serial(this, Serial.list()[0], 9600);
values = new int[width];
zoom = 1.0f;
smooth();
}
int getY(int val) {
return (int)(height - val / 1023.0f * (height - 1));
}
int getValue() {
int value = -1;
while (port.available() >= 3) {
if (port.read() == 0xff) {
value = (port.read() << 8) | (port.read());
}
}
return value;
}
void pushValue(int value) {
for (int i=0; i<width-1; i++)
values[i] = values[i+1];
values[width-1] = value;
}
void drawLines() {
stroke(255);
int displayWidth = (int) (width / zoom);
int k = values.length - displayWidth;
int x0 = 0;
int y0 = getY(values[k]);
for (int i=1; i<displayWidth; i++) {
k++;
int x1 = (int) (i * (width-1) / (displayWidth-1));
int y1 = getY(values[k]);
line(x0, y0, x1, y1);
x0 = x1;
y0 = y1;
}
}
void drawGrid() {
stroke(255, 0, 0);
line(0, height/2, width, height/2);
}
void keyReleased() {
switch (key) {
case '+':
zoom *= 2.0f;
println(zoom);
if ( (int) (width / zoom) <= 1 )
zoom /= 2.0f;
break;
case '-':
zoom /= 2.0f;
if (zoom < 1.0f)
zoom *= 2.0f;
break;
}
}
void draw()
{
background(0);
drawGrid();
val = getValue();
if (val != -1) {
pushValue(val);
}
drawLines();
}
140. WRITING STRING ON EEPROM VIA SERIAL MONITOR

//
// EEPROM utility functions with usage example
//
// This example defines some utility functions
// to write byte arrays, integers and strings
// to eeprom and read them back.
//
// Some usage examples are provided.

#include <EEPROM.h>

//
// Absolute min and max eeprom addresses.
// Actual values are hardware-dependent.
//
// These values can be changed e.g. to protect
// eeprom cells outside this range.
//
const int EEPROM_MIN_ADDR = 0;
const int EEPROM_MAX_ADDR = 511;

//
// Initialize eeprom memory with
// the specified byte.
// Default value is 0xFF.
//
void eeprom_erase_all(byte b = 0xFF) {
int i;

for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {


EEPROM.write(i, b);
}
}

//
// Dump eeprom memory contents over serial port.
// For each byte, address and value are written.
//
void eeprom_serial_dump_column() {
// counter
int i;

// byte read from eeprom


byte b;

// buffer used by sprintf


char buf[10];

for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {


b = EEPROM.read(i);
sprintf(buf, "%03X: %02X", i, b);
Serial.println(buf);
}
}

//
// Dump eeprom memory contents over serial port in tabular form.
// Each printed row shows the value of bytesPerRow bytes
// (by default 16).
//
void eeprom_serial_dump_table(int bytesPerRow = 16) {
// address counter
int i;

// row bytes counter


int j;

// byte read from eeprom


byte b;

// temporary buffer for sprintf


char buf[10];

// initialize row counter


j = 0;

// go from first to last eeprom address


for (i = EEPROM_MIN_ADDR; i <= EEPROM_MAX_ADDR; i++) {

// if this is the first byte of the row,


// start row by printing the byte address
if (j == 0) {
sprintf(buf, "%03X: ", i);
Serial.print(buf);
}

// read current byte from eeprom


b = EEPROM.read(i);

// write byte in hex form


sprintf(buf, "%02X ", b);

// increment row counter


j++;

// if this is the last byte of the row,


// reset row counter and use println()
// to start a new line
if (j == bytesPerRow) {
j = 0;
Serial.println(buf);
}
// else just print the hex value with print()
else {
Serial.print(buf);
}
}
}

//
// Returns true if the address is between the
// minimum and maximum allowed values,
// false otherwise.
//
// This function is used by the other, higher-level functions
// to prevent bugs and runtime errors due to invalid addresses.
//
boolean eeprom_is_addr_ok(int addr) {
return ((addr >= EEPROM_MIN_ADDR) && (addr <= EEPROM_MAX_ADDR));
}

//
// Writes a sequence of bytes to eeprom starting at the specified address.
// Returns true if the whole array is successfully written.
// Returns false if the start or end addresses aren't between
// the minimum and maximum allowed values.
// When returning false, nothing gets written to eeprom.
//
boolean eeprom_write_bytes(int startAddr, const byte* array, int numBytes) {
// counter
int i;

// both first byte and last byte addresses must fall within
// the allowed range
if (!eeprom_is_addr_ok(startAddr) || !eeprom_is_addr_ok(startAddr + numBytes)) {
return false;
}

for (i = 0; i < numBytes; i++) {


EEPROM.write(startAddr + i, array[i]);
}

return true;
}
//
// Reads the specified number of bytes from the specified address into the provided buffer.
// Returns true if all the bytes are successfully read.
// Returns false if the star or end addresses aren't between
// the minimum and maximum allowed values.
// When returning false, the provided array is untouched.
//
// Note: the caller must ensure that array[] has enough space
// to store at most numBytes bytes.
//
boolean eeprom_read_bytes(int startAddr, byte array[], int numBytes) {
int i;

// both first byte and last byte addresses must fall within
// the allowed range
if (!eeprom_is_addr_ok(startAddr) || !eeprom_is_addr_ok(startAddr + numBytes)) {
return false;
}

for (i = 0; i < numBytes; i++) {


array[i] = EEPROM.read(startAddr + i);
}

return true;
}

//
// Writes an int variable at the specified address.
// Returns true if the variable value is successfully written.
// Returns false if the specified address is outside the
// allowed range or too close to the maximum value
// to store all of the bytes (an int variable requires
// more than one byte).
//
boolean eeprom_write_int(int addr, int value) {
byte *ptr;

ptr = (byte*)&value;
return eeprom_write_bytes(addr, ptr, sizeof(value));
}

//
// Reads an integer value at the specified address.
// Returns true if the variable is successfully read.
// Returns false if the specified address is outside the
// allowed range or too close to the maximum vlaue
// to hold all of the bytes (an int variable requires
// more than one byte).
//
boolean eeprom_read_int(int addr, int* value) {
return eeprom_read_bytes(addr, (byte*)value, sizeof(int));
}

//
// Writes a string starting at the specified address.
// Returns true if the whole string is successfully written.
// Returns false if the address of one or more bytes
// fall outside the allowed range.
// If false is returned, nothing gets written to the eeprom.
//
boolean eeprom_write_string(int addr, const char* string) {
// actual number of bytes to be written
int numBytes;

// we'll need to write the string contents


// plus the string terminator byte (0x00)
numBytes = strlen(string) + 1;

return eeprom_write_bytes(addr, (const byte*)string, numBytes);


}

//
// Reads a string starting from the specified address.
// Returns true if at least one byte (even only the
// string terminator one) is read.
// Returns false if the start address falls outside
// or declare buffer size os zero.
// the allowed range.
// The reading might stop for several reasons:
// - no more space in the provided buffer
// - last eeprom address reached
// - string terminator byte (0x00) encountered.
// The last condition is what should normally occur.
//
boolean eeprom_read_string(int addr, char* buffer, int bufSize) {
// byte read from eeprom
byte ch;

// number of bytes read so far


int bytesRead;

// check start address


if (!eeprom_is_addr_ok(addr)) {
return false;
}

// how can we store bytes in an empty buffer ?


if (bufSize == 0) {
return false;
}
// is there is room for the string terminator only,
// no reason to go further
if (bufSize == 1) {
buffer[0] = 0;
return true;
}

// initialize byte counter


bytesRead = 0;

// read next byte from eeprom


ch = EEPROM.read(addr + bytesRead);

// store it into the user buffer


buffer[bytesRead] = ch;

// increment byte counter


bytesRead++;

// stop conditions:
// - the character just read is the string terminator one (0x00)
// - we have filled the user buffer
// - we have reached the last eeprom address
while ( (ch != 0x00) && (bytesRead < bufSize) && ((addr + bytesRead) <=
EEPROM_MAX_ADDR) ) {
// if no stop condition is met, read the next byte from eeprom
ch = EEPROM.read(addr + bytesRead);

// store it into the user buffer


buffer[bytesRead] = ch;

// increment byte counter


bytesRead++;
}

// make sure the user buffer has a string terminator


// (0x00) as its last byte
if ((ch != 0x00) && (bytesRead >= 1)) {
buffer[bytesRead - 1] = 0;
}

return true;
}

//
// A pair of functions to show how long it takes to work with eeprom.
//
int start_time;
int stop_time;
void start_timing() {
start_time = millis();
}

void print_elapsed() {
stop_time = millis();
Serial.print("Time elapsed (ms): ");
Serial.println(stop_time - start_time);
}
//======================================
bool write_StringEE(int Addr, String input)
{
char cbuff[input.length() + 1];
input.toCharArray(cbuff, input.length() + 1);
return eeprom_write_string(Addr, cbuff);
}

//Given the starting address, and the length, this function will return
//a String and not a Char array
String read_StringEE(int Addr, int length)
{

char cbuff[length+1];
eeprom_read_string(Addr, cbuff, length+1);

String stemp(cbuff);
return stemp;

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

//
// SETUP
//

const int BUFSIZE = 50;


char buf[BUFSIZE];

void setup()
{

Serial.begin(9600);
/*
Serial.println("Starting...");//Say hello

String text = "Ini adalah string eeprom tulisan yang panjang.maaf perjalanan anda
tergangu";//String to write

Serial.print("Writting: ");
Serial.println(text);
write_StringEE(0, text);//Write string starting at address 0

Serial.print("Reading: ");
Serial.println(read_StringEE(0,text.length()));//Read String starting a address 0 with given lenth of
String

*/

//
// LOOP
//
void loop() {
//int sensorValue0 = analogRead(A0);
//String text = "ini pesan pendek";//String to write
String text;
//Serial.print("Writting: ");
//Serial.println(text);
if(Serial.available()) {
text = Serial.readString();
write_StringEE(0, text);//Write string starting at address 0
}
else {
Serial.print("Reading: ");
Serial.println(read_StringEE(0,100));//Read String starting a address 0 with given lenth of String
delay(1000);

}
141. WRITING STRING VIA SERIAL MONITOR

String a;

void setup() {

Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

void loop() {

if(Serial.available()) {

a= Serial.readString();// read the incoming data as string

Serial.println(a);

=======================================================================
142. POWER SWITCH WITH MOC3011 AND BT136

This circuit is applied to AC power source only.

int led = 13;


void setup() {
pinMode(led, OUTPUT);
}
void loop() {
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
}

==================================================================
143. CONTACTLESS THERMOMETER MLX90614

#include <Wire.h>
#include <Adafruit_MLX90614.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

void setup()
{
Serial.begin(9600);

Serial.println("Adafruit MLX90614 test");

mlx.begin();
}

void loop()
{
Serial.print("Ambient = ");
Serial.print(" ");
Serial.print(mlx.readAmbientTempC());
Serial.print(" ");
Serial.print("*C");
Serial.print(" ");
Serial.print("Object = ");
Serial.print(" ");
Serial.print(mlx.readObjectTempC());
Serial.print(" ");
Serial.print("*C");
Serial.print(" ");
Serial.print("Ambient = ");
Serial.print(" ");
Serial.print(mlx.readAmbientTempF());
Serial.print(" ");
Serial.print("*F");
Serial.print(" ");
Serial.print("Object = ");
Serial.print(" ");
Serial.print(mlx.readObjectTempF());
Serial.print(" ");
Serial.println("*F");
delay(500);
}

=======================================================================
144. CAR POWER LOCK

Pada proyek ini kita coba gabungkak beberapa module untuk membuat power lock untuk mobil.
Penerapan ini berguna saat mobil kita dirampok orang, maka kira serahkan saja mobil itu dan semua
penumpang dikeluarkan. Ketika mobil sudah dibawa kabur oleh si perampok, ketika jaraknya tidak
lebih dari 100 meter maka kita tekan push button para transmitter yang kita pegang, maka dalam 10
menit mobil akan mati secara otomatis, si pemilik mobil dan penumpang punya kesempatan
melarikan diri sebelum perampok kembali ke TKP karena mobil mati. Ketika mobil mati karena
button transmitter ditekan maka tidak dapat dinyalakan lagi, untuk menyalakan lagi harus mamakai
RFID.

Receiver

const int ledPin = 5;//this signal go to relay or mosfet or for drive triac
#include <EEPROM.h>
int addr = 0;
byte value;

//=========================================
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;

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

#include <SoftwareSerial.h>

//RFID ...
const int RFID_TX_Pin = 2; // the TX pin that the RDIF Sensor is attached
String Parsed_Tag_ID, Stored_Tag_ID;
char c;
SoftwareSerial RFID(RFID_TX_Pin , 255); // RX, TX for serial communication on any digital
pins.
// RX port : 2 -- TX port : 255 (do not need any TX port)

////////////////////////////////////////////////////////////////////////////
//AUX FUNCTIONS BEGIN
boolean CheckSum_Tag_ID(String Tag_ID) {
boolean res = false;
unsigned int b1,b2,b3,b4,b5,checksum;

//Convert Tag_ID String into array of chars in order to use sscanf


char charBuf[13];
Tag_ID.toCharArray(charBuf, 13);
sscanf(charBuf , "%2x%2x%2x%2x%2x%2x", &b1, &b2, &b3, &b4, &b5, &checksum);

//Control now the TAG ID


if ( (b1 ^ b2 ^ b3 ^ b4 ^ b5) == checksum ) {
return true;
} else {
Serial.println("Tag ID is INVALID");
return false;
}
}

//============================
void setup() {
Serial.begin(9600);
RFID.begin(9600);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}
void(* resetFunc) (void) = 0;
void loop(){
value = EEPROM.read(addr);
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
Serial.print("NRF24L01 Receiver: ");
Serial.println(DataMgs[0]);

if ((DataMgs[0] == 1) && (value==0))


{
digitalWrite(ledPin, HIGH);
delay(60000); //delay 10 minutes
EEPROM.write(addr, 1);
}
}
}
else {
value = EEPROM.read(addr);
if (value==1){
digitalWrite(ledPin, LOW);
}
Serial.println(value);
}
//===========================================================

Stored_Tag_ID="";

//Read the RFID TAG BEGIN


RFID.listen();
if ( RFID.isListening() ) {
while( RFID.available() > 0 ){
c=RFID.read();
Parsed_Tag_ID += c;
if ( Parsed_Tag_ID.length() == 14 ) {
if ( (Parsed_Tag_ID[0]==2) && (Parsed_Tag_ID[13]==3) ) {
Parsed_Tag_ID = Parsed_Tag_ID.substring(1,13);
if ( CheckSum_Tag_ID(Parsed_Tag_ID) == true ) {
Stored_Tag_ID=Parsed_Tag_ID;
}
}
Parsed_Tag_ID="";
}
}
}
//Read the RFID TAG END

//Print & use the Stored Tag ID ...


if ( Stored_Tag_ID =="13000D65EF94" || Stored_Tag_ID =="13002F81E558" ){
Serial.println("Captured Tag ID : " + Stored_Tag_ID);
EEPROM.write(addr, 0);
Stored_Tag_ID="";
Parsed_Tag_ID="";
resetFunc(); //call reset
}
//======================================

Transmitter

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

int DataMsg[1];

RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;

int Button1 = 3;
void setup()
{
pinMode(3, INPUT);
digitalWrite(3,HIGH);
Serial.begin(9600);
Serial.println("NRF24L01 Transmitter");

radio.begin();
radio.openWritingPipe(pipe);
}

void loop()
{
if (digitalRead(Button1) == LOW)
{
Serial.println("Button 1 pressed");
DataMsg[0] = 1;
radio.write(DataMsg, 1);
}

==================================================================
145. RFID 125kHz CODE READING

//Made By TrustFm for http://www.Hw2Sw.com

//Documentation :
//The TAG ID has this format :
// HEX : 2 | 30 31 30 30 34 45 32 37 31 37 | 37 46 | 3 -> Total 14 bytes (chars)
// Start byte : 2 | 10 ascii chars (10 bytes) | 2 ascii chars (bytes) checksum | End byte : 3
// We DEFINE the TAG ID as the 10 ascii chars + 2 ascii chars of the checksum -> total 12
chars/bytes [we remove the start/end bytes]

#include <SoftwareSerial.h> //for serial communication on any digital pins.


//More info : http://arduino.cc/en/Reference/SoftwareSerial

//RFID ...
const int RFID_TX_Pin = 2; // the TX pin that the RDIF Sensor is attached
String Parsed_Tag_ID, Stored_Tag_ID;
char c;
SoftwareSerial RFID(RFID_TX_Pin , 255); // RX, TX for serial communication on any digital
pins.
// RX port : 2 -- TX port : 255 (do not need any TX port)
////////////////////////////////////////////////////////////////////////////
//AUX FUNCTIONS BEGIN
boolean CheckSum_Tag_ID(String Tag_ID) {
boolean res = false;
unsigned int b1,b2,b3,b4,b5,checksum;

//Convert Tag_ID String into array of chars in order to use sscanf


char charBuf[13];
Tag_ID.toCharArray(charBuf, 13);
sscanf(charBuf , "%2x%2x%2x%2x%2x%2x", &b1, &b2, &b3, &b4, &b5, &checksum);

//Control now the TAG ID


if ( (b1 ^ b2 ^ b3 ^ b4 ^ b5) == checksum ) {
return true;
} else {
Serial.println("Tag ID is INVALID");
return false;
}
}
//AUX FUNCTIONS END
////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////
//The setup BEGIN
void setup()
{
//Setup serial
Serial.begin(9600);

//Setup RFID serial


RFID.begin(9600);
}
//The setup END
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
//The main LOOP BEGIN
void loop(){

Stored_Tag_ID="";

//Read the RFID TAG BEGIN


RFID.listen(); //Enables the selected software serial port to listen.
//Only one software serial port can listen at a time; data that arrives for other ports will be
discarded.
//Any data already received is discarded during the call to listen() (unless the given
instance is already listening).
if ( RFID.isListening() ) { //Tests to see if requested software serial port is actively listening.
while( RFID.available() > 0 ){ //Get the number of bytes (characters) available for reading from a
software serial port.
//This is data that's already arrived and stored in the serial receive buffer.
c=RFID.read(); //Reads one char/byte at a time
Parsed_Tag_ID += c; //Store the char into the Parsed_Tag_ID string
if ( Parsed_Tag_ID.length() == 14 ) { //The TAG ID has 14 chars in total
if ( (Parsed_Tag_ID[0]==2) && (Parsed_Tag_ID[13]==3) ) { //If the first char is 2 and the last
one is 3 then ...
Parsed_Tag_ID = Parsed_Tag_ID.substring(1,13); //Delete the 1st and the 13th (last) char
if ( CheckSum_Tag_ID(Parsed_Tag_ID) == true ) { //Validate the Parsed Tag Id
Stored_Tag_ID=Parsed_Tag_ID;
}
}
Parsed_Tag_ID="";
}//end i have read the 14 chars
}
}
//Read the RFID TAG END

//Print & use the Stored Tag ID ...


if ( Stored_Tag_ID!="" ){
Serial.println("Captured Tag ID : '" + Stored_Tag_ID + "'");
}

//The main LOOP END

================================================================

#include <SoftwareSerial.h>

#define ADD_TAG_CODE "120010752750#" //change this ID with your own card TAG

#define DEL_TAG_CODE "13002F81E558" //change this ID with your own card TAG

SoftwareSerial rfid = SoftwareSerial(2, 6);

String msg;

String ID ; //string to store allowed cards

void setup()

Serial.begin(9600);

Serial.println("Serial Ready");
rfid.begin(9600);

Serial.println("RFID Ready");

char c;

void loop(){

while(rfid.available()>0){

c=rfid.read();

msg += c;

Serial.println(msg);

Serial.println(msg.length());

msg=msg.substring(1,13);

if(msg.indexOf(ADD_TAG_CODE)>=0) add();

else if(msg.indexOf(DEL_TAG_CODE)>=0) del();

else if(msg.length()>10) verifica();

msg="";

void add(){

Serial.print("What TAG do you wanna grant access?: ");

msg="";
while(msg.length()<13){

while(rfid.available()>0){

c=rfid.read();

msg += c;

if(ID.indexOf(msg)>=0) {

Serial.println("\nAccess already granted for this card.");

msg="";

else{

Serial.print("Card: ");

Serial.println(msg);

ID += msg;

ID += ",";

//Serial.print("ID: ");

// Serial.println(ID);

msg="";

Serial.println("Access granted for this card.");

void del(){

msg="";

Serial.print("What TAG do you wanna deny access?: ");


while(msg.length()<13){

while(rfid.available()>0){

c=rfid.read();

msg += c;

msg=msg.substring(1,13);

if(ID.indexOf(msg)>=0){

Serial.println(msg);

Serial.println("TAG found. Access for this card denied.");

//ID.replace(card,"");

int pos=ID.indexOf(msg);

msg="";

msg += ID.substring(0,pos);

msg += ID.substring(pos+15,ID.length());

ID="";

ID += msg;

//Serial.print("ID: ");

//Serial.println(ID);

} else Serial.println("\nTAG not found or already denied");

msg="";

void verifica(){

msg=msg.substring(1,13);

if(ID.indexOf(msg)>=0) Serial.println("Access granted.");


else Serial.println("Access denied.");

=================================================================

#include <SoftwareSerial.h>
SoftwareSerial RFID(2, 3); // RX and TX

int i;

void setup()
{
RFID.begin(9600); // start serial to RFID reader
Serial.begin(9600); // start serial to PC
}

void loop()
{
if (RFID.available() > 0)
{
i = RFID.read();
Serial.print(i, DEC);
Serial.println(" ");
}
}
146. RFID 125kHz CODE READING WITH RX PIN

//remove Rx pin when uploading sketch


int readCard[13]; //For holding the ID we receive
int val = 0;
int rfid_1[12] = { 54,54,48,48,54,67,49,67,70,54,69,48};

void setup()
{
Serial.begin(9600);

delay(500);
while(Serial.available()>0)
{
Serial.read();
}
Serial.println();
Serial.println("RFID module started in Auto Read Mode, Waiting for Card...");
}

void loop()
{
// read the serial port
if(Serial.available() > 0) {
val = Serial.read();
if (val == 2)
{
Serial.print(" Start the real read: ");
Serial.println(val);
val = Serial.read();
int count = 0;
while(count < 13)
{
readCard[count] = val;
Serial.print(" Reading: ");
Serial.print(val);
Serial.print(", saved: ");
Serial.println(readCard[count]);
val = Serial.read();
count++;
}
Serial.println(" Done reading ");
int count2 = 0;
while(count2 < 13)
{
Serial.print(readCard[count2]);
Serial.print(" ");
count2++;
}
Serial.println();
}
}

delay(500);
Serial.println("Waiting");
}

=============================================================

char ID ; //Variable to store the character that was recived from the ID

void setup()
{

Serial.begin(9600); //Initiates the serial with baud rate of 9600

void loop ()
{
if(Serial.available() > 0) //If the serial receive some character
{
ID = Serial.read(); //Store on ID variable the received character
Serial.println(ID,DEC); //Print on serial the character received.
}

}
147. RFID POWER SWITCH

//Made By TrustFm for http://www.Hw2Sw.com

//Documentation :
//The TAG ID has this format :
// HEX : 2 | 30 31 30 30 34 45 32 37 31 37 | 37 46 | 3 -> Total 14 bytes (chars)
// Start byte : 2 | 10 ascii chars (10 bytes) | 2 ascii chars (bytes) checksum | End byte : 3
// We DEFINE the TAG ID as the 10 ascii chars + 2 ascii chars of the checksum -> total 12
chars/bytes [we remove the start/end bytes]

#include <SoftwareSerial.h> //for serial communication on any digital pins.


//More info : http://arduino.cc/en/Reference/SoftwareSerial
//RFID ...
const int RFID_TX_Pin = 2; // the TX pin that the RDIF Sensor is attached
String Parsed_Tag_ID, Stored_Tag_ID;
char c;
SoftwareSerial RFID(RFID_TX_Pin , 255); // RX, TX for serial communication on any digital
pins.
// RX port : 2 -- TX port : 255 (do not need any TX port)

////////////////////////////////////////////////////////////////////////////
//AUX FUNCTIONS BEGIN
boolean CheckSum_Tag_ID(String Tag_ID) {
boolean res = false;
unsigned int b1,b2,b3,b4,b5,checksum;

//Convert Tag_ID String into array of chars in order to use sscanf


char charBuf[13];
Tag_ID.toCharArray(charBuf, 13);
sscanf(charBuf , "%2x%2x%2x%2x%2x%2x", &b1, &b2, &b3, &b4, &b5, &checksum);

//Control now the TAG ID


if ( (b1 ^ b2 ^ b3 ^ b4 ^ b5) == checksum ) {
return true;
} else {
Serial.println("Tag ID is INVALID");
return false;
}
}
//AUX FUNCTIONS END
////////////////////////////////////////////////////////////////////////////
int led = 3;
////////////////////////////////////////////////////////////////////////////
//The setup BEGIN
void setup()
{
//Setup serial
Serial.begin(9600);
pinMode(led, OUTPUT);
//Setup RFID serial
RFID.begin(9600);
}
//The setup END
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
//The main LOOP BEGIN
void loop(){

Stored_Tag_ID="";

//Read the RFID TAG BEGIN


RFID.listen(); //Enables the selected software serial port to listen.
//Only one software serial port can listen at a time; data that arrives for other ports will be
discarded.
//Any data already received is discarded during the call to listen() (unless the given
instance is already listening).
if ( RFID.isListening() ) { //Tests to see if requested software serial port is actively listening.
while( RFID.available() > 0 ){ //Get the number of bytes (characters) available for reading from a
software serial port.
//This is data that's already arrived and stored in the serial receive buffer.
c=RFID.read(); //Reads one char/byte at a time
Parsed_Tag_ID += c; //Store the char into the Parsed_Tag_ID string
if ( Parsed_Tag_ID.length() == 14 ) { //The TAG ID has 14 chars in total
if ( (Parsed_Tag_ID[0]==2) && (Parsed_Tag_ID[13]==3) ) { //If the first char is 2 and the last
one is 3 then ...
Parsed_Tag_ID = Parsed_Tag_ID.substring(1,13); //Delete the 1st and the 13th (last) char
if ( CheckSum_Tag_ID(Parsed_Tag_ID) == true ) { //Validate the Parsed Tag Id
Stored_Tag_ID=Parsed_Tag_ID;
}
}
Parsed_Tag_ID="";
}//end i have read the 14 chars
}
}
//Read the RFID TAG END

//Print & use the Stored Tag ID ...


if ( Stored_Tag_ID =="13000D65EF94" || Stored_Tag_ID =="13002F81E558" ){
Serial.println("Captured Tag ID : " + Stored_Tag_ID);
digitalWrite(led,HIGH); // this signal go to relay to drive power
delay(2000);
Stored_Tag_ID="";
Parsed_Tag_ID="";
}
else if(Stored_Tag_ID !="") {
digitalWrite(led, LOW);
Serial.println("Captured Tag ID : " + Stored_Tag_ID);
}
else{
digitalWrite(led, LOW);
}
}

//The main LOOP END


148. RF24 LIGHT SWITCH

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

int DataMsg[1];

RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;

int Button1 = 3;
int Button2 = 2;

void setup()
{
//ativa pull-up
pinMode(3, INPUT);
digitalWrite(3,HIGH);
pinMode(2, INPUT);
digitalWrite(2,HIGH);

Serial.begin(9600);
Serial.println("NRF24L01 Transmitter");

radio.begin();
radio.openWritingPipe(pipe);
}

void loop()
{
if (digitalRead(Button1) == LOW)
{
Serial.println("Button 1 pressed");
DataMsg[0] = 1;
radio.write(DataMsg, 1);
}
if (digitalRead(Button2) == LOW)
{
Serial.println("Button 2 pressed");
DataMsg[0] = 2;
radio.write(DataMsg, 1);
}
}
Receiver

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

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;
int Relay1 = 5;

void setup()
{
pinMode(Relay1, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}

void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
Serial.print("NRF24L01 Receiver: ");
Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{
delay(10);
digitalWrite(Relay1, HIGH);
}

if (DataMgs[0] == 2)
{
delay(10);
digitalWrite(Relay1, LOW);
}
delay(100);
}
}
else
{
Serial.println("Waiting for signal...");
}
}
149. RF 24 PIR ALARM

Transmitter

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int pirPin = 2;
int statePir = 0;
int DataMsg[1];

RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;

void setup()
{
pinMode(pirPin,INPUT);
Serial.begin(9600);
Serial.println("NRF24L01 Transmitter");
radio.begin();
radio.openWritingPipe(pipe);
}

void loop()
{
statePir = digitalRead(pirPin);
if (statePir == HIGH)
{
DataMsg[0] = 1;
radio.write(DataMsg, 1);
}
if (statePir == LOW)
{
DataMsg[0] = 2;
radio.write(DataMsg, 1);
}
}
Receiver

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

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;
int Relay1 = 5;
int speaker = 10;
#define wait 1
#define time 100
int freq = 0;
void setup()
{
pinMode(Relay1, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
pinMode(speaker, OUTPUT);
}

void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
Serial.print("NRF24L01 Receiver: ");
Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{
digitalWrite(Relay1, HIGH);
digitalWrite(speaker, HIGH);
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000; freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker,
freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500;
freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}

if (DataMgs[0] == 2)
{
digitalWrite(Relay1, LOW);
digitalWrite(speaker, LOW);

}
delay(100);
}
}
else
{
Serial.println("Waiting for signal...");
}
}

======================================================================
150. RF24 SERVO

Transmitter

#include <SPI.h>
#include "RF24.h"
int msg[1]; //SCK -> 13//MISO -> 12//MOSI -> 11//CSN -> 7//CE -> 8
RF24 radio(8,7);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int potpin = 0;
int val;
void setup(void)
{
radio.begin();
radio.openWritingPipe(pipe);
}
void loop(void)
{
val = analogRead(potpin);
val = map(val, 0, 1023, 0, 179);
msg[0] = val;
radio.write(msg, 1);
}
Receiver

#include <Servo.h>
#include <SPI.h>
#include "RF24.h"
Servo myservo;
//SCK -> 13//MISO -> 12//MOSI -> 11//CSN -> 7//CE -> 8
RF24 radio(8,7);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int msg[1];
void setup()
{
myservo.attach(9);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}
void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(msg, 1);
myservo.write (msg[0]);
}
}}
151. RF24 TEST RUN

Proyek ini hanya untuk testing sampai berapa meter signal RF24 masih kuat tertangkap.

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

int DataMsg[1];

RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;

void setup()
{
Serial.begin(9600);
Serial.println("NRF24L01 Transmitter");

radio.begin();
radio.openWritingPipe(pipe);
}

void loop()
{
DataMsg[0] = 1;
radio.write(DataMsg, 1);
DataMsg[0] = 2;
radio.write(DataMsg, 1);
}
Receiver

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

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;
int Relay1 = 5;

void setup()
{
pinMode(Relay1, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}

void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
Serial.print("NRF24L01 Receiver: ");
Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{
delay(10);
digitalWrite(Relay1, HIGH);
}

if (DataMgs[0] == 2)
{
delay(10);digitalWrite(Relay1, LOW);
}
delay(100);
}
}
else
{
Serial.println("Waiting for signal...");
}
}
152. RF24 ANALOG DATA

Transmitter

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(8,7);

void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();
}

void setup()
{

setupRadio();

void loop()
{

int temperature = analogRead(A0);

// Open a writing pipe on the radio


radio.openWritingPipe(0xE8E8F0F0E1LL);

// Write the temperature to the pipe


radio.write(&temperature, sizeof(int));

}
Receiver

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

// -- Global variables --
RF24 radio(8,7);
//int packetCounter = 0;

// -- Functions --

void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


// Must be the same on the sensor and the master node
radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();

// Open reading pipe


radio.openReadingPipe(1, 0xE8E8F0F0E1LL);

// Start listening for packets


radio.startListening();
}

void setup()
{
// Initiate serial connection
Serial.begin(9600);

// RF Radio setup
setupRadio();
}

void loop()
{
// Check if the radio has received any data
if(radio.available()) {
int temperature = 0;

// Read the packet received into the temperature variable


if(!radio.read(&temperature, sizeof(int))) {
// The sensor did not receive the ACK packet
Serial.println("ACK not received by client.");
}

// Print the temperature


Serial.println(temperature);

// Wait for serial print to complete


//delay(100);
}
}

===============================================================
153. LED BAR INDICATOR TLC5940

#include <Tlc5940.h>

void tlc_progress(word value, word prefix)


{
byte out_num = value / 4096;
word out_brg = value % 4096;

for (byte out=0; out<16; out++)


{
if (out < out_num)
{
Tlc.set(out, prefix);
}

else if (out == out_num)


{
Tlc.set(out, out_brg);
}

else
{
Tlc.set(out, 0);
}
}
}

void setup()
{
Tlc.init();
}

void loop()
{
int value = analogRead(0);
value = map(value, 0, 1023, 0, 65535);
tlc_progress(value, 4095);
Tlc.update();
}
154. TLC5940 LED ANIMATION
/*
Basic Pin setup:
------------ ---u----
ARDUINO 13|-> SCLK (pin 25) OUT1 |1 28| OUT channel 0
12| OUT2 |2 27|-> GND (VPRG)
11|-> SIN (pin 26) OUT3 |3 26|-> SIN (pin 11)
10|-> BLANK (pin 23) OUT4 |4 25|-> SCLK (pin 13)
9|-> XLAT (pin 24) . |5 24|-> XLAT (pin 9)
8| . |6 23|-> BLANK (pin 10)
7| . |7 22|-> GND
6| . |8 21|-> VCC (+5V)
5| . |9 20|-> 2K Resistor -> GND
4| . |10 19|-> +5V (DCPRG)
3|-> GSCLK (pin 18) . |11 18|-> GSCLK (pin 3)
2| . |12 17|-> SOUT
1| . |13 16|-> XERR
0| OUT14|14 15| OUT channel 15
------------ --------

- Put the longer leg (anode) of the LEDs in the +5V and the shorter leg
(cathode) in OUT(0-15).
- +5V from Arduino -> TLC pin 21 and 19 (VCC and DCPRG)
- GND from Arduino -> TLC pin 22 and 27 (GND and VPRG)
- digital 3 -> TLC pin 18 (GSCLK)
- digital 9 -> TLC pin 24 (XLAT)
- digital 10 -> TLC pin 23 (BLANK)
- digital 11 -> TLC pin 26 (SIN)
- digital 13 -> TLC pin 25 (SCLK)
- The 2K resistor between TLC pin 20 and GND will let ~20mA through each
LED. To be precise, it's I = 39.06 / R (in ohms). This doesn't depend
on the LED driving voltage.
- (Optional): put a pull-up resistor (~10k) between +5V and BLANK so that
all the LEDs will turn off when the Arduino is reset.

If you are daisy-chaining more than one TLC, connect the SOUT of the first
TLC to the SIN of the next. All the other pins should just be connected
together:
BLANK on Arduino -> BLANK of TLC1 -> BLANK of TLC2 -> ...
XLAT on Arduino -> XLAT of TLC1 -> XLAT of TLC2 -> ...
The one exception is that each TLC needs it's own resistor between pin 20
and GND.

This library uses the PWM output ability of digital pins 3, 9, 10, and 11.
Do not use analogWrite(...) on these pins.

This sketch does the Knight Rider strobe across a line of LEDs.

Alex Leone <acleone ~AT~ gmail.com>, 2009-02-03 */

#include "Tlc5940.h"

void setup()
{
/* Call Tlc.init() to setup the tlc.
You can optionally pass an initial PWM value (0 - 4095) for all channels.*/
Tlc.init();
}

/* This loop will create a Knight Rider-like effect if you have LEDs plugged
into all the TLC outputs. NUM_TLCS is defined in "tlc_config.h" in the
library folder. After editing tlc_config.h for your setup, delete the
Tlc5940.o file to save the changes. */

void loop()
{
int direction = 1;
for (int channel = 0; channel < NUM_TLCS * 16; channel += direction) {

/* Tlc.clear() sets all the grayscale values to zero, but does not send
them to the TLCs. To actually send the data, call Tlc.update() */
Tlc.clear();

/* Tlc.set(channel (0-15), value (0-4095)) sets the grayscale value for


one channel (15 is OUT15 on the first TLC, if multiple TLCs are daisy-
chained, then channel = 16 would be OUT0 of the second TLC, etc.).

value goes from off (0) to always on (4095).


Like Tlc.clear(), this function only sets up the data, Tlc.update()
will send the data. */
if (channel == 0) {
direction = 1;
} else {
Tlc.set(channel - 1, 1000);
}
Tlc.set(channel, 4095);
if (channel != NUM_TLCS * 16 - 1) {
Tlc.set(channel + 1, 1000);
} else {
direction = -1;
}

/* Tlc.update() sends the data to the TLCs. This is when the LEDs will
actually change. */
Tlc.update();

delay(75);
}

}
155. TLC5940 LED SHIFT

#include <Tlc5940.h>
#include <tlc_shifts.h>

void setup()
{
Tlc.init();
}

void loop()
{
static byte counter = 0;
if (counter % 4)
tlc_shiftUp(0);

else
tlc_shiftUp(4095);

counter++;
Tlc.update();
delay(100);
}

156. TCL5940 LED BLINK


#include "Tlc5940.h"
void setup() {
Tlc.init(0); // Initiates the TLC5940 and set all channels off
}

void loop() {
Tlc.set(0,4095); //(Output Pin from 0 to 15,PWM Value from 0 to 4095)
// Note: The previous function doesn't activates the output right away. The output will be activated
when the Tlc.update() function will be executed!

Tlc.update(); // Activates the previously set outputs


delay(1000);
// For activating all 16 outputs at the same time we can use a for loop for setting all of them to be
set to PWM value of 4095. Then the Tlc.updata() function will active them all at the same time.
for (int i = 0; i < 16; i++) {
Tlc.set(i, 4095);
}
Tlc.update();
delay(1000);
//The Tlc.clear() function clears all the outputs, or sets the PWM value of all outputs to 0
Tlc.clear();
Tlc.update();
delay(1000);
// This for loop will active all 16 LEDs one by one
for (int i = 0; i < 16; i++) {
Tlc.set(i, 4095);
Tlc.update();
delay(200);
Tlc.clear();
Tlc.update();
delay(200);
}
}

157. TCL5940 ONE LED FADE


#include <Tlc5940.h>
#include <tlc_fades.h>

void setup()
{
Tlc.init();
}

void loop()
{
if (!tlc_isFading(1))
{
unsigned long time = millis();
tlc_addFade(1, 0, 4095, time+1000, time+1250);
tlc_addFade(1, 4095, 0, time+1500, time+2000);
}
tlc_updateFades();
}

158. TCL5940 ALL LED FADE


#include "Tlc5940.h"
void setup()
{
Tlc.init(0); // initialise TLC5940 and set all channels off
}

void loop()
{
for (int i = 0; i < 16; i++)
{
Tlc.set(i, 1023);
}
Tlc.update();
delay(1000);
for (int i = 0; i < 16; i++)
{
Tlc.set(i, 2046);
}
Tlc.update();
delay(1000);
for (int i = 0; i < 16; i++)
{
Tlc.set(i, 3069);
}
Tlc.update();
delay(1000);
for (int i = 0; i < 16; i++)
{
Tlc.set(i, 4095);
}
Tlc.update();
delay(1000);
}

159. RF24 TWO ANALOG DATA TRANSFER


Transmitter

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

RF24 radio(8,7);
void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();
}
struct package
{
int temperature ;
int humidity ;
};
typedef struct package Package;
Package data;
void setup()
{

setupRadio();

void loop()
{

data.temperature = analogRead(A0);
data.humidity = analogRead(A1);

// Open a writing pipe on the radio


radio.openWritingPipe(0xE8E8F0F0E1LL);

// Write the temperature to the pipe


radio.write(&data, sizeof(data));

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

// -- Global variables --
RF24 radio(8,7);
//int packetCounter = 0;

// -- Functions --

void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


// Must be the same on the sensor and the master node
radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();

// Open reading pipe


radio.openReadingPipe(1, 0xE8E8F0F0E1LL);

// Start listening for packets


radio.startListening();
}
struct package
{
int temperature ;
int humidity ;
};
typedef struct package Package;
Package data;
void setup()
{
// Initiate serial connection
Serial.begin(9600);

// RF Radio setup
setupRadio();
}

void loop()
{
// Check if the radio has received any data
if(radio.available()) {
//int temperature = 0;

// Read the packet received into the temperature variable


if(!radio.read(&data, sizeof(data))) {
// The sensor did not receive the ACK packet
Serial.println("ACK not received by client.");
}

// Print the temperature


Serial.print(data.temperature);
Serial.print(" ");
Serial.println(data.humidity);

// Wait for serial print to complete


//delay(100);
}
}

or other with delay

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

// -- Global variables --

RF24 radio(8,7);
//int packetCounter = 0;

// -- Functions --

void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


// Must be the same on the sensor and the master node
radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);
// Enable dynamic payloads for packets
radio.enableDynamicPayloads();

// Open reading pipe


radio.openReadingPipe(1, 0xE8E8F0F0E1LL);

// Start listening for packets


radio.startListening();
}
struct package
{
int temperature ;
int humidity ;
};
typedef struct package Package;
Package data;
void setup()
{
// Initiate serial connection
Serial.begin(9600);

// RF Radio setup
setupRadio();
}

void loop()
{
// Check if the radio has received any data
if(radio.available()) {
//int temperature = 0;

// Read the packet received into the temperature variable


if(!radio.read(&data, sizeof(data))) {
// The sensor did not receive the ACK packet
//Serial.println("ACK not received by client.");
}

// Print the temperature


Serial.print(data.temperature);
Serial.print(" ");
Serial.println(data.humidity);

// Wait for serial print to complete


delay(1000);
}
}

160. TLC5940 TWO CASCADE


/*
Basic Pin setup:
------------ ---u----
ARDUINO 13|-> SCLK (pin 25) OUT1 |1 28| OUT channel 0
12| OUT2 |2 27|-> GND (VPRG)
11|-> SIN (pin 26) OUT3 |3 26|-> SIN (pin 11)
10|-> BLANK (pin 23) OUT4 |4 25|-> SCLK (pin 13)
9|-> XLAT (pin 24) . |5 24|-> XLAT (pin 9)
8| . |6 23|-> BLANK (pin 10)
7| . |7 22|-> GND
6| . |8 21|-> VCC (+5V)
5| . |9 20|-> 2K Resistor -> GND
4| . |10 19|-> +5V (DCPRG)
3|-> GSCLK (pin 18) . |11 18|-> GSCLK (pin 3)
2| . |12 17|-> SOUT
1| . |13 16|-> XERR
0| OUT14|14 15| OUT channel 15
------------ --------

- Put the longer leg (anode) of the LEDs in the +5V and the shorter leg
(cathode) in OUT(0-15).
- +5V from Arduino -> TLC pin 21 and 19 (VCC and DCPRG)
- GND from Arduino -> TLC pin 22 and 27 (GND and VPRG)
- digital 3 -> TLC pin 18 (GSCLK)
- digital 9 -> TLC pin 24 (XLAT)
- digital 10 -> TLC pin 23 (BLANK)
- digital 11 -> TLC pin 26 (SIN)
- digital 13 -> TLC pin 25 (SCLK)
- The 2K resistor between TLC pin 20 and GND will let ~20mA through each
LED. To be precise, it's I = 39.06 / R (in ohms). This doesn't depend
on the LED driving voltage.
- (Optional): put a pull-up resistor (~10k) between +5V and BLANK so that
all the LEDs will turn off when the Arduino is reset.

If you are daisy-chaining more than one TLC, connect the SOUT of the first
TLC to the SIN of the next. All the other pins should just be connected
together:
BLANK on Arduino -> BLANK of TLC1 -> BLANK of TLC2 -> ...
XLAT on Arduino -> XLAT of TLC1 -> XLAT of TLC2 -> ...
The one exception is that each TLC needs it's own resistor between pin 20
and GND.

This library uses the PWM output ability of digital pins 3, 9, 10, and 11.
Do not use analogWrite(...) on these pins.

This sketch does the Knight Rider strobe across a line of LEDs.

Alex Leone <acleone ~AT~ gmail.com>, 2009-02-03 */

#include "Tlc5940.h"

void setup()
{
/* Call Tlc.init() to setup the tlc.
You can optionally pass an initial PWM value (0 - 4095) for all channels.*/
Tlc.init();
}

/* This loop will create a Knight Rider-like effect if you have LEDs plugged
into all the TLC outputs. NUM_TLCS is defined in "tlc_config.h" in the
library folder. After editing tlc_config.h for your setup, delete the
Tlc5940.o file to save the changes. */

void loop()
{
int d=50;

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(31, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(1, 1000);
Tlc.set(30, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(2, 1000);
Tlc.set(29, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(3, 1000);
Tlc.set(28, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(4, 1000);
Tlc.set(27, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(5, 1000);
Tlc.set(26, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(6, 1000);
Tlc.set(25, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(7, 1000);
Tlc.set(24, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(8, 1000);
Tlc.set(23, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(9, 1000);
Tlc.set(22, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(10, 1000);
Tlc.set(21, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(11, 1000);
Tlc.set(20, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(12, 1000);
Tlc.set(19, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(13, 1000);
Tlc.set(18, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(14, 1000);
Tlc.set(17, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.update();
delay(d);

}
Other sketch

#include "Tlc5940.h"

void setup()
{
/* Call Tlc.init() to setup the tlc.
You can optionally pass an initial PWM value (0 - 4095) for all channels.*/
Tlc.init();
}

void loop()
{
int d=50;

Tlc.clear();
Tlc.set(0, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(1, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(2, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(3, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(4, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(5, 1000);

Tlc.update();
delay(d);
Tlc.clear();
Tlc.set(6, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(7, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(8, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(9, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(10, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(11, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(12, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(13, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(14, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(15, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(16, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(17, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(18, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(19, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(20, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(21, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(22, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(23, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(24, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(25, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(26, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(27, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(28, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(29, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(30, 1000);

Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(31, 1000);

Tlc.update();
delay(d);
}

Other sketch

#include <Tlc5940.h>
#include <tlc_shifts.h>

void setup()
{
Tlc.init();
}

void loop()
{
static byte counter = 0;
if (counter % 4)
tlc_shiftUp(0);

else
tlc_shiftUp(4095);

counter++;
Tlc.update();
delay(100);
}

Other sketch

#include "Tlc5940.h"
void setup() {
Tlc.init(0); // Initiates the TLC5940 and set all channels off
}

void loop() {
Tlc.set(0,4095); //(Output Pin from 0 to 15,PWM Value from 0 to 4095)
// Note: The previous function doesn't activates the output right away. The output will be activated
when the Tlc.update() function will be executed!

Tlc.update(); // Activates the previously set outputs


delay(1000);
// For activating all 16 outputs at the same time we can use a for loop for setting all of them to be
set to PWM value of 4095. Then the Tlc.updata() function will active them all at the same time.
for (int i = 0; i < 32; i++) {
Tlc.set(i, 4095);
}
Tlc.update();
delay(1000);
//The Tlc.clear() function clears all the outputs, or sets the PWM value of all outputs to 0
Tlc.clear();
Tlc.update();
delay(1000);
// This for loop will active all 16 LEDs one by one
for (int i = 0; i < 32; i++) {
Tlc.set(i, 4095);
Tlc.update();
delay(200);
Tlc.clear();
Tlc.update();
delay(200);
}
}

Other sketch

#include "Tlc5940.h"
void setup()
{
Tlc.init(0); // initialise TLC5940 and set all channels off
}

void loop()
{
for (int i = 0; i < 32; i++)
{
Tlc.set(i, 1023);
}
Tlc.update();
delay(1000);
for (int i = 0; i < 32; i++)
{
Tlc.set(i, 2046);
}
Tlc.update();
delay(1000);
for (int i = 0; i < 32; i++)
{
Tlc.set(i, 3069);
}
Tlc.update();
delay(1000);
for (int i = 0; i < 32; i++)
{
Tlc.set(i, 4095);
}
Tlc.update();
delay(1000);
}
Other sketch

#include "Tlc5940.h"

void setup()
{

Tlc.init();
}

void loop()
{
int direction = 1;
for (int channel = 0; channel < NUM_TLCS * 16; channel += direction) {

Tlc.clear();

if (channel == 0) {
direction = 1;
} else {
Tlc.set(channel - 1, 1000);
}
Tlc.set(channel, 4095);
if (channel != NUM_TLCS * 16 - 1) {
Tlc.set(channel + 1, 1000);
} else {
direction = -1;
}

Tlc.update();

delay(75);
}

Other sketch

#include "Tlc5940.h"

void setup()
{
Tlc.init();
}

void loop()
{
int d=50;
int value = analogRead(0);
value = map(value, 0, 1023, 0, 31);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.update();

delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.set(29, 1000);
Tlc.update();
delay(d);

Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.set(29, 1000);
Tlc.set(30, 1000);
Tlc.update();
delay(d);
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.set(29, 1000);
Tlc.set(30, 1000);
Tlc.set(31, 1000);
Tlc.update();
delay(d);
}

161. 32 LED LEVEL INDICATOR TLC5940


#include "Tlc5940.h"
void setup()
{
/* Call Tlc.init() to setup the tlc.
You can optionally pass an initial PWM value (0 - 4095) for all channels.*/
Tlc.init();
}

/* This loop will create a Knight Rider-like effect if you have LEDs plugged
into all the TLC outputs. NUM_TLCS is defined in "tlc_config.h" in the
library folder. After editing tlc_config.h for your setup, delete the
Tlc5940.o file to save the changes. */

void loop()
{
int d=50;
int value = analogRead(0);
value = map(value, 0, 1023, 0, 31);

if(value==0){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.update();
}
//delay(d);

if(value==1){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.update();
//delay(d);
}
if(value==2){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.update();
//delay(d);
}
if(value==3){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.update();
//delay(d);
}
if(value==4){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.update();
//delay(d);
}
if(value==5){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.update();
//delay(d);
}
if(value==6){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.update();
//delay(d);
}
if(value==7){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.update();
//delay(d);
}
if(value==8){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.update();
//delay(d);
}
if(value==9){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.update();
//delay(d);
}
if(value==10){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.update();
//delay(d);
}
if(value==11){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.update();
//delay(d);
}
if(value==12){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.update();
//delay(d);
}
if(value==13){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.update();
//delay(d);
}
if(value==14){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.update();
//delay(d);
}
if(value==15){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.update();
//delay(d);
}

if(value==16){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.update();
//delay(d);
}

if(value==17){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.update();
//delay(d);
}

if(value==18){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.update();
//delay(d);
}

if(value==19){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.update();
//delay(d);
}

if(value==20){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.update();
//delay(d);
}

if(value==21){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.update();
//delay(d);
}

if(value==22){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.update();
//delay(d);
}

if(value==23){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.update();
//delay(d);
}

if(value==24){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.update();
//delay(d);
}

if(value==25){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.update();
//delay(d);
}

if(value==26){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.update();
//delay(d);
}

if(value==27){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.update();
//delay(d);
}

if(value==28){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.update();
//delay(d);
}

if(value==29){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.set(29, 1000);
Tlc.update();
//delay(d);
}

if(value==30){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.set(29, 1000);
Tlc.set(30, 1000);
Tlc.update();
//delay(d);
}

if(value==31){
Tlc.clear();
Tlc.set(0, 1000);
Tlc.set(1, 1000);
Tlc.set(2, 1000);
Tlc.set(3, 1000);
Tlc.set(4, 1000);
Tlc.set(5, 1000);
Tlc.set(6, 1000);
Tlc.set(7, 1000);
Tlc.set(8, 1000);
Tlc.set(9, 1000);
Tlc.set(10, 1000);
Tlc.set(11, 1000);
Tlc.set(12, 1000);
Tlc.set(13, 1000);
Tlc.set(14, 1000);
Tlc.set(15, 1000);
Tlc.set(16, 1000);
Tlc.set(17, 1000);
Tlc.set(18, 1000);
Tlc.set(19, 1000);
Tlc.set(20, 1000);
Tlc.set(21, 1000);
Tlc.set(22, 1000);
Tlc.set(23, 1000);
Tlc.set(24, 1000);
Tlc.set(25, 1000);
Tlc.set(26, 1000);
Tlc.set(27, 1000);
Tlc.set(28, 1000);
Tlc.set(29, 1000);
Tlc.set(30, 1000);
Tlc.set(31, 1000);
Tlc.update();
//delay(d);
}
//}

}
162. RGB LED COMMON CATHODE
#include <SoftPWM.h>

void setup()
{
SoftPWMBegin();

SoftPWMSet(7, 0);
SoftPWMSet(6, 0);
SoftPWMSet(5, 0);

SoftPWMSetFadeTime(7, 1000, 1000);


SoftPWMSetFadeTime(6, 1000, 1000);
SoftPWMSetFadeTime(5, 1000, 1000);
}

void loop()
{
SoftPWMSet(7, 255);
SoftPWMSet(6, 0);
SoftPWMSet(5, 0);
delay(1000);
SoftPWMSet(7, 0);
SoftPWMSet(6, 255);
SoftPWMSet(5, 0);
delay(1000);

SoftPWMSet(7, 0);
SoftPWMSet(6, 0);
SoftPWMSet(5, 255);
delay(1000);

SoftPWMSet(7, 85);
SoftPWMSet(6, 85);
SoftPWMSet(5, 85);
delay(1000);
SoftPWMSet(7, 90);
SoftPWMSet(6, 80);
SoftPWMSet(5, 85);
delay(1000);
SoftPWMSet(7, 95);
SoftPWMSet(6, 75);
SoftPWMSet(5, 85);
delay(1000);
SoftPWMSet(7, 100);
SoftPWMSet(6, 70);
SoftPWMSet(5, 85);
delay(1000);
}

Other sketch

int redPin= 7;
int greenPin = 6;
int bluePin = 5;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
setColor(255, 0, 0); // Red Color
delay(1000);
setColor(0, 255, 0); // Green Color
delay(1000);
setColor(0, 0, 255); // Blue Color
delay(1000);
setColor(255, 255, 255); // White Color
delay(1000);
setColor(170, 0, 255); // Purple Color
delay(1000);
setColor(200, 50, 255);
delay(1000);
setColor(40, 80, 255);
delay(1000);
setColor(255, 80, 40);
delay(1000);
}
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}

Other sketch

const int RED_PIN = 7;


const int GREEN_PIN = 6;
const int BLUE_PIN = 5;

int DISPLAY_TIME = 20; // In milliseconds

void setup()
{
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}

void loop()
{
mainColors();
showSpectrum();
}

void mainColors()
{
// Off (all LEDs off):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Red (turn just the red LED on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Green (turn just the green LED on):


digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Blue (turn just the blue LED on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// Yellow (turn red and green on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);

delay(1000);

// Cyan (turn green and blue on):

digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// Purple (turn red and blue on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);

// White (turn all the LEDs on):

digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);

delay(1000);
}

void showSpectrum()
{
int x; // define an integer variable called "x"

for (x = 0; x < 768; x++)


{
showRGB(x); // Call RGBspectrum() with our new x
delay(DISPLAY_TIME); // Delay for 10 ms (1/100th of a second)
}
}

void showRGB(int color)


{
int redIntensity;
int greenIntensity;
int blueIntensity;

if (color <= 255) // zone 1


{
redIntensity = 255 - color; // red goes from on to off
greenIntensity = color; // green goes from off to on
blueIntensity = 0; // blue is always off
}
else if (color <= 511) // zone 2
{
redIntensity = 0; // red is always off
greenIntensity = 255 - (color - 256); // green on to off
blueIntensity = (color - 256); // blue off to on
}
else // color >= 512 // zone 3
{
redIntensity = (color - 512); // red off to on
greenIntensity = 0; // green is always off
blueIntensity = 255 - (color - 512); // blue on to off
}

analogWrite(RED_PIN, redIntensity);
analogWrite(BLUE_PIN, blueIntensity);
analogWrite(GREEN_PIN, greenIntensity);
}

163. LIGHT INTENSITY BH1750


/*

Example of BH1750 library usage.

This example initalises the BH1750 object using the default


high resolution mode and then makes a light level reading every second.

Connection:
VCC-5v
GND-GND
SCL-SCL(analog pin 5)
SDA-SDA(analog pin 4)
ADD-NC or GND

*/

#include <Wire.h>
#include <BH1750.h>

BH1750 lightMeter;

void setup(){
Serial.begin(9600);
lightMeter.begin();
Serial.println("Running...");
}

void loop() {
uint16_t lux = lightMeter.readLightLevel();
Serial.print("Light: ");
Serial.print(lux);
Serial.println(" lx");
delay(100);
}

164. RF24 EARTHQUAKE ALARM


Transmitter
#include <Wire.h>

#define MPU6050_AUX_VDDIO 0x01 // R/W


#define MPU6050_SMPLRT_DIV 0x19 // R/W
#define MPU6050_CONFIG 0x1A // R/W
#define MPU6050_GYRO_CONFIG 0x1B // R/W
#define MPU6050_ACCEL_CONFIG 0x1C // R/W
#define MPU6050_FF_THR 0x1D // R/W
#define MPU6050_FF_DUR 0x1E // R/W
#define MPU6050_MOT_THR 0x1F // R/W
#define MPU6050_MOT_DUR 0x20 // R/W
#define MPU6050_ZRMOT_THR 0x21 // R/W
#define MPU6050_ZRMOT_DUR 0x22 // R/W
#define MPU6050_FIFO_EN 0x23 // R/W
#define MPU6050_I2C_MST_CTRL 0x24 // R/W
#define MPU6050_I2C_SLV0_ADDR 0x25 // R/W
#define MPU6050_I2C_SLV0_REG 0x26 // R/W
#define MPU6050_I2C_SLV0_CTRL 0x27 // R/W
#define MPU6050_I2C_SLV1_ADDR 0x28 // R/W
#define MPU6050_I2C_SLV1_REG 0x29 // R/W
#define MPU6050_I2C_SLV1_CTRL 0x2A // R/W
#define MPU6050_I2C_SLV2_ADDR 0x2B // R/W
#define MPU6050_I2C_SLV2_REG 0x2C // R/W
#define MPU6050_I2C_SLV2_CTRL 0x2D // R/W
#define MPU6050_I2C_SLV3_ADDR 0x2E // R/W
#define MPU6050_I2C_SLV3_REG 0x2F // R/W
#define MPU6050_I2C_SLV3_CTRL 0x30 // R/W
#define MPU6050_I2C_SLV4_ADDR 0x31 // R/W
#define MPU6050_I2C_SLV4_REG 0x32 // R/W
#define MPU6050_I2C_SLV4_DO 0x33 // R/W
#define MPU6050_I2C_SLV4_CTRL 0x34 // R/W
#define MPU6050_I2C_SLV4_DI 0x35 // R
#define MPU6050_I2C_MST_STATUS 0x36 // R
#define MPU6050_INT_PIN_CFG 0x37 // R/W
#define MPU6050_INT_ENABLE 0x38 // R/W
#define MPU6050_INT_STATUS 0x3A // R
#define MPU6050_ACCEL_XOUT_H 0x3B // R
#define MPU6050_ACCEL_XOUT_L 0x3C // R
#define MPU6050_ACCEL_YOUT_H 0x3D // R
#define MPU6050_ACCEL_YOUT_L 0x3E // R
#define MPU6050_ACCEL_ZOUT_H 0x3F // R
#define MPU6050_ACCEL_ZOUT_L 0x40 // R
#define MPU6050_TEMP_OUT_H 0x41 // R
#define MPU6050_TEMP_OUT_L 0x42 // R
#define MPU6050_GYRO_XOUT_H 0x43 // R
#define MPU6050_GYRO_XOUT_L 0x44 // R
#define MPU6050_GYRO_YOUT_H 0x45 // R
#define MPU6050_GYRO_YOUT_L 0x46 // R
#define MPU6050_GYRO_ZOUT_H 0x47 // R
#define MPU6050_GYRO_ZOUT_L 0x48 // R
#define MPU6050_EXT_SENS_DATA_00 0x49 // R
#define MPU6050_EXT_SENS_DATA_01 0x4A // R
#define MPU6050_EXT_SENS_DATA_02 0x4B // R
#define MPU6050_EXT_SENS_DATA_03 0x4C // R
#define MPU6050_EXT_SENS_DATA_04 0x4D // R
#define MPU6050_EXT_SENS_DATA_05 0x4E // R
#define MPU6050_EXT_SENS_DATA_06 0x4F // R
#define MPU6050_EXT_SENS_DATA_07 0x50 // R
#define MPU6050_EXT_SENS_DATA_08 0x51 // R
#define MPU6050_EXT_SENS_DATA_09 0x52 // R
#define MPU6050_EXT_SENS_DATA_10 0x53 // R
#define MPU6050_EXT_SENS_DATA_11 0x54 // R
#define MPU6050_EXT_SENS_DATA_12 0x55 // R
#define MPU6050_EXT_SENS_DATA_13 0x56 // R
#define MPU6050_EXT_SENS_DATA_14 0x57 // R
#define MPU6050_EXT_SENS_DATA_15 0x58 // R
#define MPU6050_EXT_SENS_DATA_16 0x59 // R
#define MPU6050_EXT_SENS_DATA_17 0x5A // R
#define MPU6050_EXT_SENS_DATA_18 0x5B // R
#define MPU6050_EXT_SENS_DATA_19 0x5C // R
#define MPU6050_EXT_SENS_DATA_20 0x5D // R
#define MPU6050_EXT_SENS_DATA_21 0x5E // R
#define MPU6050_EXT_SENS_DATA_22 0x5F // R
#define MPU6050_EXT_SENS_DATA_23 0x60 // R
#define MPU6050_MOT_DETECT_STATUS 0x61 // R
#define MPU6050_I2C_SLV0_DO 0x63 // R/W
#define MPU6050_I2C_SLV1_DO 0x64 // R/W
#define MPU6050_I2C_SLV2_DO 0x65 // R/W
#define MPU6050_I2C_SLV3_DO 0x66 // R/W
#define MPU6050_I2C_MST_DELAY_CTRL 0x67 // R/W
#define MPU6050_SIGNAL_PATH_RESET 0x68 // R/W
#define MPU6050_MOT_DETECT_CTRL 0x69 // R/W
#define MPU6050_USER_CTRL 0x6A // R/W
#define MPU6050_PWR_MGMT_1 0x6B // R/W
#define MPU6050_PWR_MGMT_2 0x6C // R/W
#define MPU6050_FIFO_COUNTH 0x72 // R/W
#define MPU6050_FIFO_COUNTL 0x73 // R/W
#define MPU6050_FIFO_R_W 0x74 // R/W
#define MPU6050_WHO_AM_I 0x75 // R

#define MPU6050_D0 0
#define MPU6050_D1 1
#define MPU6050_D2 2
#define MPU6050_D3 3
#define MPU6050_D4 4
#define MPU6050_D5 5
#define MPU6050_D6 6
#define MPU6050_D7 7

// AUX_VDDIO Register
#define MPU6050_AUX_VDDIO MPU6050_D7 // I2C high: 1=VDD, 0=VLOGIC

#define MPU6050_DLPF_CFG0 MPU6050_D0


#define MPU6050_DLPF_CFG1 MPU6050_D1
#define MPU6050_DLPF_CFG2 MPU6050_D2
#define MPU6050_EXT_SYNC_SET0 MPU6050_D3
#define MPU6050_EXT_SYNC_SET1 MPU6050_D4
#define MPU6050_EXT_SYNC_SET2 MPU6050_D5

#define MPU6050_EXT_SYNC_SET_0 (0)


#define MPU6050_EXT_SYNC_SET_1 (bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_2 (bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_3 (bit(MPU6050_EXT_SYNC_SET1)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_4 (bit(MPU6050_EXT_SYNC_SET2))
#define MPU6050_EXT_SYNC_SET_5 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET0))
#define MPU6050_EXT_SYNC_SET_6 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1))
#define MPU6050_EXT_SYNC_SET_7 (bit(MPU6050_EXT_SYNC_SET2)|
bit(MPU6050_EXT_SYNC_SET1)|bit(MPU6050_EXT_SYNC_SET0))

#define MPU6050_EXT_SYNC_DISABLED MPU6050_EXT_SYNC_SET_0


#define MPU6050_EXT_SYNC_TEMP_OUT_L MPU6050_EXT_SYNC_SET_1
#define MPU6050_EXT_SYNC_GYRO_XOUT_L MPU6050_EXT_SYNC_SET_2
#define MPU6050_EXT_SYNC_GYRO_YOUT_L MPU6050_EXT_SYNC_SET_3
#define MPU6050_EXT_SYNC_GYRO_ZOUT_L MPU6050_EXT_SYNC_SET_4
#define MPU6050_EXT_SYNC_ACCEL_XOUT_L MPU6050_EXT_SYNC_SET_5
#define MPU6050_EXT_SYNC_ACCEL_YOUT_L MPU6050_EXT_SYNC_SET_6
#define MPU6050_EXT_SYNC_ACCEL_ZOUT_L MPU6050_EXT_SYNC_SET_7

#define MPU6050_DLPF_CFG_0 (0)


#define MPU6050_DLPF_CFG_1 (bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_2 (bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_3 (bit(MPU6050_DLPF_CFG1)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_4 (bit(MPU6050_DLPF_CFG2))
#define MPU6050_DLPF_CFG_5 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG0))
#define MPU6050_DLPF_CFG_6 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1))
#define MPU6050_DLPF_CFG_7 (bit(MPU6050_DLPF_CFG2)|bit(MPU6050_DLPF_CFG1)|
bit(MPU6050_DLPF_CFG0))

#define MPU6050_DLPF_260HZ MPU6050_DLPF_CFG_0


#define MPU6050_DLPF_184HZ MPU6050_DLPF_CFG_1
#define MPU6050_DLPF_94HZ MPU6050_DLPF_CFG_2
#define MPU6050_DLPF_44HZ MPU6050_DLPF_CFG_3
#define MPU6050_DLPF_21HZ MPU6050_DLPF_CFG_4
#define MPU6050_DLPF_10HZ MPU6050_DLPF_CFG_5
#define MPU6050_DLPF_5HZ MPU6050_DLPF_CFG_6
#define MPU6050_DLPF_RESERVED MPU6050_DLPF_CFG_7

#define MPU6050_FS_SEL0 MPU6050_D3


#define MPU6050_FS_SEL1 MPU6050_D4
#define MPU6050_ZG_ST MPU6050_D5
#define MPU6050_YG_ST MPU6050_D6
#define MPU6050_XG_ST MPU6050_D7

#define MPU6050_FS_SEL_0 (0)


#define MPU6050_FS_SEL_1 (bit(MPU6050_FS_SEL0))
#define MPU6050_FS_SEL_2 (bit(MPU6050_FS_SEL1))
#define MPU6050_FS_SEL_3 (bit(MPU6050_FS_SEL1)|bit(MPU6050_FS_SEL0))

#define MPU6050_FS_SEL_250 MPU6050_FS_SEL_0


#define MPU6050_FS_SEL_500 MPU6050_FS_SEL_1
#define MPU6050_FS_SEL_1000 MPU6050_FS_SEL_2
#define MPU6050_FS_SEL_2000 MPU6050_FS_SEL_3

#define MPU6050_ACCEL_HPF0 MPU6050_D0


#define MPU6050_ACCEL_HPF1 MPU6050_D1
#define MPU6050_ACCEL_HPF2 MPU6050_D2
#define MPU6050_AFS_SEL0 MPU6050_D3
#define MPU6050_AFS_SEL1 MPU6050_D4
#define MPU6050_ZA_ST MPU6050_D5
#define MPU6050_YA_ST MPU6050_D6
#define MPU6050_XA_ST MPU6050_D7

#define MPU6050_ACCEL_HPF_0 (0)


#define MPU6050_ACCEL_HPF_1 (bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_2 (bit(MPU6050_ACCEL_HPF1))
#define MPU6050_ACCEL_HPF_3 (bit(MPU6050_ACCEL_HPF1)|
bit(MPU6050_ACCEL_HPF0))
#define MPU6050_ACCEL_HPF_4 (bit(MPU6050_ACCEL_HPF2))
#define MPU6050_ACCEL_HPF_7 (bit(MPU6050_ACCEL_HPF2)|
bit(MPU6050_ACCEL_HPF1)|bit(MPU6050_ACCEL_HPF0))

#define MPU6050_ACCEL_HPF_RESET MPU6050_ACCEL_HPF_0


#define MPU6050_ACCEL_HPF_5HZ MPU6050_ACCEL_HPF_1
#define MPU6050_ACCEL_HPF_2_5HZ MPU6050_ACCEL_HPF_2
#define MPU6050_ACCEL_HPF_1_25HZ MPU6050_ACCEL_HPF_3
#define MPU6050_ACCEL_HPF_0_63HZ MPU6050_ACCEL_HPF_4
#define MPU6050_ACCEL_HPF_HOLD MPU6050_ACCEL_HPF_7

#define MPU6050_AFS_SEL_0 (0)


#define MPU6050_AFS_SEL_1 (bit(MPU6050_AFS_SEL0))
#define MPU6050_AFS_SEL_2 (bit(MPU6050_AFS_SEL1))
#define MPU6050_AFS_SEL_3 (bit(MPU6050_AFS_SEL1)|bit(MPU6050_AFS_SEL0))

#define MPU6050_AFS_SEL_2G MPU6050_AFS_SEL_0


#define MPU6050_AFS_SEL_4G MPU6050_AFS_SEL_1
#define MPU6050_AFS_SEL_8G MPU6050_AFS_SEL_2
#define MPU6050_AFS_SEL_16G MPU6050_AFS_SEL_3

#define MPU6050_SLV0_FIFO_EN MPU6050_D0


#define MPU6050_SLV1_FIFO_EN MPU6050_D1
#define MPU6050_SLV2_FIFO_EN MPU6050_D2
#define MPU6050_ACCEL_FIFO_EN MPU6050_D3
#define MPU6050_ZG_FIFO_EN MPU6050_D4
#define MPU6050_YG_FIFO_EN MPU6050_D5
#define MPU6050_XG_FIFO_EN MPU6050_D6
#define MPU6050_TEMP_FIFO_EN MPU6050_D7

#define MPU6050_I2C_MST_CLK0 MPU6050_D0


#define MPU6050_I2C_MST_CLK1 MPU6050_D1
#define MPU6050_I2C_MST_CLK2 MPU6050_D2
#define MPU6050_I2C_MST_CLK3 MPU6050_D3
#define MPU6050_I2C_MST_P_NSR MPU6050_D4
#define MPU6050_SLV_3_FIFO_EN MPU6050_D5
#define MPU6050_WAIT_FOR_ES MPU6050_D6
#define MPU6050_MULT_MST_EN MPU6050_D7

// Combined definitions for the I2C_MST_CLK


#define MPU6050_I2C_MST_CLK_0 (0)
#define MPU6050_I2C_MST_CLK_1 (bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_2 (bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_3 (bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_4 (bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_5 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_6 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_7 (bit(MPU6050_I2C_MST_CLK2)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_8 (bit(MPU6050_I2C_MST_CLK3))
#define MPU6050_I2C_MST_CLK_9 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_10 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_11 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK1)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_12 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2))
#define MPU6050_I2C_MST_CLK_13 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK0))
#define MPU6050_I2C_MST_CLK_14 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1))
#define MPU6050_I2C_MST_CLK_15 (bit(MPU6050_I2C_MST_CLK3)|
bit(MPU6050_I2C_MST_CLK2)|bit(MPU6050_I2C_MST_CLK1)|
bit(MPU6050_I2C_MST_CLK0))

#define MPU6050_I2C_MST_CLK_348KHZ MPU6050_I2C_MST_CLK_0


#define MPU6050_I2C_MST_CLK_333KHZ MPU6050_I2C_MST_CLK_1
#define MPU6050_I2C_MST_CLK_320KHZ MPU6050_I2C_MST_CLK_2
#define MPU6050_I2C_MST_CLK_308KHZ MPU6050_I2C_MST_CLK_3
#define MPU6050_I2C_MST_CLK_296KHZ MPU6050_I2C_MST_CLK_4
#define MPU6050_I2C_MST_CLK_286KHZ MPU6050_I2C_MST_CLK_5
#define MPU6050_I2C_MST_CLK_276KHZ MPU6050_I2C_MST_CLK_6
#define MPU6050_I2C_MST_CLK_267KHZ MPU6050_I2C_MST_CLK_7
#define MPU6050_I2C_MST_CLK_258KHZ MPU6050_I2C_MST_CLK_8
#define MPU6050_I2C_MST_CLK_500KHZ MPU6050_I2C_MST_CLK_9
#define MPU6050_I2C_MST_CLK_471KHZ MPU6050_I2C_MST_CLK_10
#define MPU6050_I2C_MST_CLK_444KHZ MPU6050_I2C_MST_CLK_11
#define MPU6050_I2C_MST_CLK_421KHZ MPU6050_I2C_MST_CLK_12
#define MPU6050_I2C_MST_CLK_400KHZ MPU6050_I2C_MST_CLK_13
#define MPU6050_I2C_MST_CLK_381KHZ MPU6050_I2C_MST_CLK_14
#define MPU6050_I2C_MST_CLK_364KHZ MPU6050_I2C_MST_CLK_15

#define MPU6050_I2C_SLV0_RW MPU6050_D7

#define MPU6050_I2C_SLV0_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV0_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV0_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV0_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV0_GRP MPU6050_D4
#define MPU6050_I2C_SLV0_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV0_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV0_EN MPU6050_D7

#define MPU6050_I2C_SLV0_LEN_MASK 0x0F

#define MPU6050_I2C_SLV1_RW MPU6050_D7

#define MPU6050_I2C_SLV1_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV1_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV1_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV1_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV1_GRP MPU6050_D4
#define MPU6050_I2C_SLV1_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV1_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV1_EN MPU6050_D7

#define MPU6050_I2C_SLV1_LEN_MASK 0x0F

#define MPU6050_I2C_SLV2_RW MPU6050_D7

#define MPU6050_I2C_SLV2_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV2_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV2_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV2_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV2_GRP MPU6050_D4
#define MPU6050_I2C_SLV2_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV2_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV2_EN MPU6050_D7

#define MPU6050_I2C_SLV2_LEN_MASK 0x0F

#define MPU6050_I2C_SLV3_RW MPU6050_D7

#define MPU6050_I2C_SLV3_LEN0 MPU6050_D0


#define MPU6050_I2C_SLV3_LEN1 MPU6050_D1
#define MPU6050_I2C_SLV3_LEN2 MPU6050_D2
#define MPU6050_I2C_SLV3_LEN3 MPU6050_D3
#define MPU6050_I2C_SLV3_GRP MPU6050_D4
#define MPU6050_I2C_SLV3_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV3_BYTE_SW MPU6050_D6
#define MPU6050_I2C_SLV3_EN MPU6050_D7

#define MPU6050_I2C_SLV3_LEN_MASK 0x0F

#define MPU6050_I2C_SLV4_RW MPU6050_D7

#define MPU6050_I2C_MST_DLY0 MPU6050_D0


#define MPU6050_I2C_MST_DLY1 MPU6050_D1
#define MPU6050_I2C_MST_DLY2 MPU6050_D2
#define MPU6050_I2C_MST_DLY3 MPU6050_D3
#define MPU6050_I2C_MST_DLY4 MPU6050_D4
#define MPU6050_I2C_SLV4_REG_DIS MPU6050_D5
#define MPU6050_I2C_SLV4_INT_EN MPU6050_D6
#define MPU6050_I2C_SLV4_EN MPU6050_D7

#define MPU6050_I2C_MST_DLY_MASK 0x1F


#define MPU6050_I2C_SLV0_NACK MPU6050_D0
#define MPU6050_I2C_SLV1_NACK MPU6050_D1
#define MPU6050_I2C_SLV2_NACK MPU6050_D2
#define MPU6050_I2C_SLV3_NACK MPU6050_D3
#define MPU6050_I2C_SLV4_NACK MPU6050_D4
#define MPU6050_I2C_LOST_ARB MPU6050_D5
#define MPU6050_I2C_SLV4_DONE MPU6050_D6
#define MPU6050_PASS_THROUGH MPU6050_D7

#define MPU6050_CLKOUT_EN MPU6050_D0


#define MPU6050_I2C_BYPASS_EN MPU6050_D1
#define MPU6050_FSYNC_INT_EN MPU6050_D2
#define MPU6050_FSYNC_INT_LEVEL MPU6050_D3
#define MPU6050_INT_RD_CLEAR MPU6050_D4
#define MPU6050_LATCH_INT_EN MPU6050_D5
#define MPU6050_INT_OPEN MPU6050_D6
#define MPU6050_INT_LEVEL MPU6050_D7

#define MPU6050_DATA_RDY_EN MPU6050_D0


#define MPU6050_I2C_MST_INT_EN MPU6050_D3
#define MPU6050_FIFO_OFLOW_EN MPU6050_D4
#define MPU6050_ZMOT_EN MPU6050_D5
#define MPU6050_MOT_EN MPU6050_D6
#define MPU6050_FF_EN MPU6050_D7

#define MPU6050_DATA_RDY_INT MPU6050_D0


#define MPU6050_I2C_MST_INT MPU6050_D3
#define MPU6050_FIFO_OFLOW_INT MPU6050_D4
#define MPU6050_ZMOT_INT MPU6050_D5
#define MPU6050_MOT_INT MPU6050_D6
#define MPU6050_FF_INT MPU6050_D7

#define MPU6050_MOT_ZRMOT MPU6050_D0


#define MPU6050_MOT_ZPOS MPU6050_D2
#define MPU6050_MOT_ZNEG MPU6050_D3
#define MPU6050_MOT_YPOS MPU6050_D4
#define MPU6050_MOT_YNEG MPU6050_D5
#define MPU6050_MOT_XPOS MPU6050_D6
#define MPU6050_MOT_XNEG MPU6050_D7

#define MPU6050_I2C_SLV0_DLY_EN MPU6050_D0


#define MPU6050_I2C_SLV1_DLY_EN MPU6050_D1
#define MPU6050_I2C_SLV2_DLY_EN MPU6050_D2
#define MPU6050_I2C_SLV3_DLY_EN MPU6050_D3
#define MPU6050_I2C_SLV4_DLY_EN MPU6050_D4
#define MPU6050_DELAY_ES_SHADOW MPU6050_D7
#define MPU6050_TEMP_RESET MPU6050_D0
#define MPU6050_ACCEL_RESET MPU6050_D1
#define MPU6050_GYRO_RESET MPU6050_D2

#define MPU6050_MOT_COUNT0 MPU6050_D0


#define MPU6050_MOT_COUNT1 MPU6050_D1
#define MPU6050_FF_COUNT0 MPU6050_D2
#define MPU6050_FF_COUNT1 MPU6050_D3
#define MPU6050_ACCEL_ON_DELAY0 MPU6050_D4
#define MPU6050_ACCEL_ON_DELAY1 MPU6050_D5

#define MPU6050_MOT_COUNT_0 (0)


#define MPU6050_MOT_COUNT_1 (bit(MPU6050_MOT_COUNT0))
#define MPU6050_MOT_COUNT_2 (bit(MPU6050_MOT_COUNT1))
#define MPU6050_MOT_COUNT_3 (bit(MPU6050_MOT_COUNT1)|
bit(MPU6050_MOT_COUNT0))

#define MPU6050_MOT_COUNT_RESET MPU6050_MOT_COUNT_0

#define MPU6050_FF_COUNT_0 (0)


#define MPU6050_FF_COUNT_1 (bit(MPU6050_FF_COUNT0))
#define MPU6050_FF_COUNT_2 (bit(MPU6050_FF_COUNT1))
#define MPU6050_FF_COUNT_3 (bit(MPU6050_FF_COUNT1)|bit(MPU6050_FF_COUNT0))

#define MPU6050_FF_COUNT_RESET MPU6050_FF_COUNT_0

#define MPU6050_ACCEL_ON_DELAY_0 (0)


#define MPU6050_ACCEL_ON_DELAY_1 (bit(MPU6050_ACCEL_ON_DELAY0))
#define MPU6050_ACCEL_ON_DELAY_2 (bit(MPU6050_ACCEL_ON_DELAY1))
#define MPU6050_ACCEL_ON_DELAY_3 (bit(MPU6050_ACCEL_ON_DELAY1)|
bit(MPU6050_ACCEL_ON_DELAY0))

#define MPU6050_ACCEL_ON_DELAY_0MS MPU6050_ACCEL_ON_DELAY_0


#define MPU6050_ACCEL_ON_DELAY_1MS MPU6050_ACCEL_ON_DELAY_1
#define MPU6050_ACCEL_ON_DELAY_2MS MPU6050_ACCEL_ON_DELAY_2
#define MPU6050_ACCEL_ON_DELAY_3MS MPU6050_ACCEL_ON_DELAY_3

#define MPU6050_SIG_COND_RESET MPU6050_D0


#define MPU6050_I2C_MST_RESET MPU6050_D1
#define MPU6050_FIFO_RESET MPU6050_D2
#define MPU6050_I2C_IF_DIS MPU6050_D4 // must be 0 for MPU-6050
#define MPU6050_I2C_MST_EN MPU6050_D5
#define MPU6050_FIFO_EN MPU6050_D6

#define MPU6050_CLKSEL0 MPU6050_D0


#define MPU6050_CLKSEL1 MPU6050_D1
#define MPU6050_CLKSEL2 MPU6050_D2
#define MPU6050_TEMP_DIS MPU6050_D3 // 1: disable temperature sensor
#define MPU6050_CYCLE MPU6050_D5 // 1: sample and sleep
#define MPU6050_SLEEP MPU6050_D6 // 1: sleep mode
#define MPU6050_DEVICE_RESET MPU6050_D7 // 1: reset to default values

#define MPU6050_CLKSEL_0 (0)


#define MPU6050_CLKSEL_1 (bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_2 (bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_3 (bit(MPU6050_CLKSEL1)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_4 (bit(MPU6050_CLKSEL2))
#define MPU6050_CLKSEL_5 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL0))
#define MPU6050_CLKSEL_6 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1))
#define MPU6050_CLKSEL_7 (bit(MPU6050_CLKSEL2)|bit(MPU6050_CLKSEL1)|
bit(MPU6050_CLKSEL0))

#define MPU6050_CLKSEL_INTERNAL MPU6050_CLKSEL_0


#define MPU6050_CLKSEL_X MPU6050_CLKSEL_1
#define MPU6050_CLKSEL_Y MPU6050_CLKSEL_2
#define MPU6050_CLKSEL_Z MPU6050_CLKSEL_3
#define MPU6050_CLKSEL_EXT_32KHZ MPU6050_CLKSEL_4
#define MPU6050_CLKSEL_EXT_19_2MHZ MPU6050_CLKSEL_5
#define MPU6050_CLKSEL_RESERVED MPU6050_CLKSEL_6
#define MPU6050_CLKSEL_STOP MPU6050_CLKSEL_7

#define MPU6050_STBY_ZG MPU6050_D0


#define MPU6050_STBY_YG MPU6050_D1
#define MPU6050_STBY_XG MPU6050_D2
#define MPU6050_STBY_ZA MPU6050_D3
#define MPU6050_STBY_YA MPU6050_D4
#define MPU6050_STBY_XA MPU6050_D5
#define MPU6050_LP_WAKE_CTRL0 MPU6050_D6
#define MPU6050_LP_WAKE_CTRL1 MPU6050_D7

#define MPU6050_LP_WAKE_CTRL_0 (0)


#define MPU6050_LP_WAKE_CTRL_1 (bit(MPU6050_LP_WAKE_CTRL0))
#define MPU6050_LP_WAKE_CTRL_2 (bit(MPU6050_LP_WAKE_CTRL1))
#define MPU6050_LP_WAKE_CTRL_3 (bit(MPU6050_LP_WAKE_CTRL1)|
bit(MPU6050_LP_WAKE_CTRL0))

#define MPU6050_LP_WAKE_1_25HZ MPU6050_LP_WAKE_CTRL_0


#define MPU6050_LP_WAKE_2_5HZ MPU6050_LP_WAKE_CTRL_1
#define MPU6050_LP_WAKE_5HZ MPU6050_LP_WAKE_CTRL_2
#define MPU6050_LP_WAKE_10HZ MPU6050_LP_WAKE_CTRL_3

#define MPU6050_I2C_ADDRESS 0x68

typedef union accel_t_gyro_union


{
struct
{
uint8_t x_accel_h;
uint8_t x_accel_l;
uint8_t y_accel_h;
uint8_t y_accel_l;
uint8_t z_accel_h;
uint8_t z_accel_l;
uint8_t t_h;
uint8_t t_l;
uint8_t x_gyro_h;
uint8_t x_gyro_l;
uint8_t y_gyro_h;
uint8_t y_gyro_l;
uint8_t z_gyro_h;
uint8_t z_gyro_l;
} reg;
struct
{
int x_accel;
int y_accel;
int z_accel;
int temperature;
int x_gyro;
int y_gyro;
int z_gyro;
} value;
};

// Use the following global variables and access functions to help store the overall
// rotation angle of the sensor
unsigned long last_read_time;
float last_x_angle; // These are the filtered angles
float last_y_angle;
float last_z_angle;
float last_gyro_x_angle; // Store the gyro angles to compare drift
float last_gyro_y_angle;
float last_gyro_z_angle;

void set_last_read_angle_data(unsigned long time, float x, float y, float z, float x_gyro, float
y_gyro, float z_gyro) {
last_read_time = time;
last_x_angle = x;
last_y_angle = y;
last_z_angle = z;
last_gyro_x_angle = x_gyro;
last_gyro_y_angle = y_gyro;
last_gyro_z_angle = z_gyro;
}

inline unsigned long get_last_time() {return last_read_time;}


inline float get_last_x_angle() {return last_x_angle;}
inline float get_last_y_angle() {return last_y_angle;}
inline float get_last_z_angle() {return last_z_angle;}
inline float get_last_gyro_x_angle() {return last_gyro_x_angle;}
inline float get_last_gyro_y_angle() {return last_gyro_y_angle;}
inline float get_last_gyro_z_angle() {return last_gyro_z_angle;}

// Use the following global variables and access functions


// to calibrate the acceleration sensor
float base_x_accel;
float base_y_accel;
float base_z_accel;

float base_x_gyro;
float base_y_gyro;
float base_z_gyro;

int read_gyro_accel_vals(uint8_t* accel_t_gyro_ptr) {


// Read the raw values.
// Read 14 bytes at once,
// containing acceleration, temperature and gyro.
// With the default settings of the MPU-6050,
// there is no filter enabled, and the values
// are not very stable. Returns the error value

accel_t_gyro_union* accel_t_gyro = (accel_t_gyro_union *) accel_t_gyro_ptr;

int error = MPU6050_read (MPU6050_ACCEL_XOUT_H, (uint8_t *) accel_t_gyro,


sizeof(*accel_t_gyro));

// Swap all high and low bytes.


// After this, the registers values are swapped,
// so the structure name like x_accel_l does no
// longer contain the lower byte.
uint8_t swap;
#define SWAP(x,y) swap = x; x = y; y = swap

SWAP ((*accel_t_gyro).reg.x_accel_h, (*accel_t_gyro).reg.x_accel_l);


SWAP ((*accel_t_gyro).reg.y_accel_h, (*accel_t_gyro).reg.y_accel_l);
SWAP ((*accel_t_gyro).reg.z_accel_h, (*accel_t_gyro).reg.z_accel_l);
SWAP ((*accel_t_gyro).reg.t_h, (*accel_t_gyro).reg.t_l);
SWAP ((*accel_t_gyro).reg.x_gyro_h, (*accel_t_gyro).reg.x_gyro_l);
SWAP ((*accel_t_gyro).reg.y_gyro_h, (*accel_t_gyro).reg.y_gyro_l);
SWAP ((*accel_t_gyro).reg.z_gyro_h, (*accel_t_gyro).reg.z_gyro_l);

return error;
}

// The sensor should be motionless on a horizontal surface


// while calibration is happening
void calibrate_sensors() {
int num_readings = 10;
float x_accel = 0;
float y_accel = 0;
float z_accel = 0;
float x_gyro = 0;
float y_gyro = 0;
float z_gyro = 0;
accel_t_gyro_union accel_t_gyro;

//Serial.println("Starting Calibration");

// Discard the first set of values read from the IMU


read_gyro_accel_vals((uint8_t *) &accel_t_gyro);

// Read and average the raw values from the IMU


for (int i = 0; i < num_readings; i++) {
read_gyro_accel_vals((uint8_t *) &accel_t_gyro);
x_accel += accel_t_gyro.value.x_accel;
y_accel += accel_t_gyro.value.y_accel;
z_accel += accel_t_gyro.value.z_accel;
x_gyro += accel_t_gyro.value.x_gyro;
y_gyro += accel_t_gyro.value.y_gyro;
z_gyro += accel_t_gyro.value.z_gyro;
delay(100);
}
x_accel /= num_readings;
y_accel /= num_readings;
z_accel /= num_readings;
x_gyro /= num_readings;
y_gyro /= num_readings;
z_gyro /= num_readings;

// Store the raw calibration values globally


base_x_accel = x_accel;
base_y_accel = y_accel;
base_z_accel = z_accel;
base_x_gyro = x_gyro;
base_y_gyro = y_gyro;
base_z_gyro = z_gyro;

//Serial.println("Finishing Calibration");
}
//====================================radio
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
//int pirPin = 2;
//int statePir = 0;
int DataMsg[1];

RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;

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

//int led30 = 13;

float diffy;
float lasty; //previous "action number"
float y;
float diffx;
float lastx; //previous "action number"
float x;
void setup()
{

//pinMode(led30, OUTPUT);

//=======================radio
radio.begin();
radio.openWritingPipe(pipe);

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

int error;
uint8_t c;

Serial.begin(9600);

Wire.begin();

error = MPU6050_read (MPU6050_WHO_AM_I, &c, 1);

error = MPU6050_read (MPU6050_PWR_MGMT_2, &c, 1);

MPU6050_write_reg (MPU6050_PWR_MGMT_1, 0);

calibrate_sensors();
set_last_read_angle_data(millis(), 0, 0, 0, 0, 0, 0);
}
void(* resetFunc) (void) = 0; //declare reset function @ address 0
void loop()
{

int error;
double dT;
accel_t_gyro_union accel_t_gyro;

error = read_gyro_accel_vals((uint8_t*) &accel_t_gyro);

unsigned long t_now = millis();

float FS_SEL = 131;

float gyro_x = (accel_t_gyro.value.x_gyro - base_x_gyro)/FS_SEL;


float gyro_y = (accel_t_gyro.value.y_gyro - base_y_gyro)/FS_SEL;
float gyro_z = (accel_t_gyro.value.z_gyro - base_z_gyro)/FS_SEL;

float accel_x = accel_t_gyro.value.x_accel;


float accel_y = accel_t_gyro.value.y_accel;
float accel_z = accel_t_gyro.value.z_accel;

float RADIANS_TO_DEGREES = 180/3.14159;

float accel_angle_y = atan(-1*accel_x/sqrt(pow(accel_y,2) +


pow(accel_z,2)))*RADIANS_TO_DEGREES;
float accel_angle_x = atan(accel_y/sqrt(pow(accel_x,2) +
pow(accel_z,2)))*RADIANS_TO_DEGREES;

float accel_angle_z = 0;

float dt =(t_now - get_last_time())/1000.0;


float gyro_angle_x = gyro_x*dt + get_last_x_angle();
float gyro_angle_y = gyro_y*dt + get_last_y_angle();
float gyro_angle_z = gyro_z*dt + get_last_z_angle();

float unfiltered_gyro_angle_x = gyro_x*dt + get_last_gyro_x_angle();


float unfiltered_gyro_angle_y = gyro_y*dt + get_last_gyro_y_angle();
float unfiltered_gyro_angle_z = gyro_z*dt + get_last_gyro_z_angle();

float alpha = 0.96;


float angle_x = alpha*gyro_angle_x + (1.0 - alpha)*accel_angle_x;
float angle_y = alpha*gyro_angle_y + (1.0 - alpha)*accel_angle_y;
float angle_z = gyro_angle_z; //Accelerometer doesn't give z-angle

// Update the saved data with the latest values


set_last_read_angle_data(t_now, angle_x, angle_y, angle_z, unfiltered_gyro_angle_x,
unfiltered_gyro_angle_y, unfiltered_gyro_angle_z);

// Send the data to the serial port


y=abs(accel_angle_y);
diffy = y-lasty;
lasty = y;
x=abs(accel_angle_x);
diffx = x-lastx;
lastx = x;
float a = pow(diffx,2);
float b = pow(diffy,2);
float c = a + b;
float force = sqrt(c);

Serial.print("diffx: ");
Serial.print(abs(diffx));
Serial.print(" diffy: ");
Serial.print(abs(diffy));
Serial.print(" a: ");
Serial.print(a);
Serial.print(" b: ");
Serial.print(b);
Serial.print(" c: ");
Serial.print(c);
Serial.print(" force: ");
Serial.println(force);

if(force > 1.6){


DataMsg[0] = 1;
radio.write(DataMsg, 1);
}

else {
DataMsg[0] = 2;
radio.write(DataMsg, 1);
}
}

int MPU6050_read(int start, uint8_t *buffer, int size)


{
int i, n, error;

Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start);
if (n != 1)
return (-10);

n = Wire.endTransmission(false); // hold the I2C-bus


if (n != 0)
return (n);

// Third parameter is true: relase I2C-bus after data is read.


Wire.requestFrom(MPU6050_I2C_ADDRESS, size, true);
i = 0;
while(Wire.available() && i<size)
{
buffer[i++]=Wire.read();
}
if ( i != size)
return (-11);

return (0); // return : no error


}

int MPU6050_write(int start, const uint8_t *pData, int size)


{
int n, error;

Wire.beginTransmission(MPU6050_I2C_ADDRESS);
n = Wire.write(start); // write the start address
if (n != 1)
return (-20);

n = Wire.write(pData, size); // write data bytes


if (n != size)
return (-21);

error = Wire.endTransmission(true); // release the I2C-bus


if (error != 0)
return (error);

return (0); // return : no error


}

int MPU6050_write_reg(int reg, uint8_t data)


{
int error;

error = MPU6050_write(reg, &data, 1);

return (error);
}
Receiver
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;
int Relay1 = 5;
int speaker = 10;
#define wait 1
#define time 100
int freq = 0;
void setup()
{
pinMode(Relay1, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
pinMode(speaker, OUTPUT);
}

void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
Serial.print("NRF24L01 Receiver: ");
Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{
digitalWrite(Relay1, HIGH);
digitalWrite(speaker, HIGH);
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000; freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500;
freq < 3000;
freq += 10) //
{
tone(speaker,
freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500;
freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 500; freq < 3000; freq += 10)
{
tone(speaker, freq, time);
delay(wait);
}
for (freq = 3000;
freq > 500; freq -= 10)
{
tone(speaker, freq, time);
delay(wait);
}

if (DataMgs[0] == 2)
{
digitalWrite(Relay1, LOW);
digitalWrite(speaker, LOW);

}
delay(100);
}
}
else
{
Serial.println("Waiting for signal...");
}
}

165. RF24 DHT22


Transmitter
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "DHT.h" // DHT & AM2302 library

// Version number
const float fVerNum = 0.03;

// Data pin connected to AM2302


#define DHTPIN 2

#define DHTTYPE DHT22 // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE); // LED pins

//////////////////////////////////////////////////////
RF24 radio(8,7);

void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();
}
struct package
{
float temperature ;
float humidity ;
};
typedef struct package Package;
Package data;
void setup()
{

setupRadio();
dht.begin();
}

void loop()
{

data.temperature = dht.readTemperature();
data.humidity = dht.readHumidity();
// Open a writing pipe on the radio
radio.openWritingPipe(0xE8E8F0F0E1LL);

// Write the temperature to the pipe


radio.write(&data, sizeof(data));

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

// -- Global variables --

RF24 radio(8,7);
//int packetCounter = 0;

// -- Functions --

void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


// Must be the same on the sensor and the master node
radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();

// Open reading pipe


radio.openReadingPipe(1, 0xE8E8F0F0E1LL);

// Start listening for packets


radio.startListening();
}
struct package
{
float temperature ;
float humidity ;
};
typedef struct package Package;
Package data;
void setup()
{
// Initiate serial connection
Serial.begin(9600);

// RF Radio setup
setupRadio();
}

void loop()
{
// Check if the radio has received any data
if(radio.available()) {
//int temperature = 0;

// Read the packet received into the temperature variable


if(!radio.read(&data, sizeof(data))) {
// The sensor did not receive the ACK packet
//Serial.println("ACK not received by client.");
}

// Print the temperature


Serial.print("TEMP: ");
Serial.print(data.temperature,1);
Serial.print(" ");
Serial.print("HUM: ");
Serial.println(data.humidity,1);

// Wait for serial print to complete


delay(1000);
}
}

166. AMBIENT WEATHER MONITORING

Receiver
/*sket ini didesain untuk memantau temperatur, kelembaban dan tekanan udara, data dimonitor dari
LCD dan dikirim ke file exel dengan PLX-DAQ.
LCD monitor dengan teknik serial dengan memanfaatkan IC 74HC595
*/
int ROW = 0;
int LABEL = 1;
//#include <dht.h>
//dht DHT;
//#define DHT11_PIN 5
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
//int led = 13;
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(4,3);
/*
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>
*/
#include <LiquidCrystal_SR.h>
#include "BMP280.h"
//#include "Wire.h"
#define P0 1013.25
BMP280 bmp;
LiquidCrystal_SR lcd(6, 7, 8); //6 to pin14(IC595),7 to pin11(IC595),8 to pin12(IC595)
//jika mp3 shield di pasang maka pin 6,7,8 digantikan dengan pin 14,15,16, karena pin 6,7,8 dipakai
oleh shield
/*
SdFat sd;
SFEMP3Shield MP3player;
*/
void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


// Must be the same on the sensor and the master node
radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();

// Open reading pipe


radio.openReadingPipe(1, 0xE8E8F0F0E1LL);

// Start listening for packets


radio.startListening();
}
struct package
{
float temperature ;
float humidity ;
};
typedef struct package Package;
Package data;
void setup(){
setupRadio();
if(!bmp.begin()){
Serial.println("BMP init failed!");
while(1);
}
else Serial.println("BMP init success!");

bmp.setOversampling(4);

lcd.begin(16, 4);
Serial.begin(9600);
Serial.println("CLEARDATA");
Serial.println("LABEL,Date,Time,temp1,hum,P,RTC Time");
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
//Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
//sd.begin(SD_SEL, SPI_HALF_SPEED);
//MP3player.begin();
}
void loop(){
if(radio.available()){
if(!radio.read(&data, sizeof(data))) {
// The sensor did not receive the ACK packet
//Serial.println("ACK not received by client.");
}
/*{
double T,P;
char result = bmp.startMeasurment();

if(result!=0){
delay(result);
result = bmp.getTemperatureAndPressure(T,P);

if(result!=0)
{
double A = bmp.altitude(P,P0);

Serial.print("T = \t");Serial.print(T,2); Serial.print(" degC\t");


Serial.print("P = \t");Serial.print(P,2); Serial.print(" mBar\t");
Serial.print("A = \t");Serial.print(A,2); Serial.println(" m");
lcd.setCursor(5, 3);
lcd.print(P);
}
else {
Serial.println("Error.");
}
}
else {
Serial.println("Error.");
}

//delay(1000);
}*/
/*int nilai2 = analogRead(PinSensorMasuk2);
int nilai3 = analogRead(PinSensorMasuk3);
float milivolt2 = (nilai2 / 1024.0) * 5000;
float temp2 = milivolt2 / 10;
float milivolt3 = (nilai3 / 1024.0) * 5000;
float temp3 = milivolt3 / 10;*/
//----bagian ini untuk membuyikan alarm musik dari mp3 shield
DateTime now = RTC.now();
/*
if(now.hour() == 8 && now.minute() == 0){
MP3player.playTrack(1);
}
if(now.hour() == 9 && now.minute() == 0){
MP3player.playTrack(2);
}
if(now.hour() == 10 && now.minute() == 0){
MP3player.playTrack(3);
}
if(now.hour() == 11 && now.minute() == 0){
MP3player.playTrack(4);
}
if(now.hour() == 12 && now.minute() == 0){
MP3player.playTrack(5);
}
if(now.hour() == 13 && now.minute() == 0){
MP3player.playTrack(6);
}
if(now.hour() == 14 && now.minute() == 0){
MP3player.playTrack(7);
}
if(now.hour() == 15 && now.minute() == 0){
MP3player.playTrack(8);
}
if(now.hour() == 16 && now.minute() == 0){
MP3player.playTrack(9);
}
if(now.hour() == 17 && now.minute() == 0){
MP3player.playTrack(10);
}
if(now.hour() == 18 && now.minute() == 0){
MP3player.playTrack(11);
}
if(now.hour() == 19 && now.minute() == 0){
MP3player.playTrack(12);
}
if(now.hour() == 20 && now.minute() == 0){
MP3player.playTrack(13);
}
if(now.hour() == 21 && now.minute() == 0){
MP3player.playTrack(14);
}
if(now.hour() == 22 && now.minute() == 0){
MP3player.playTrack(15);
}
*/

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.print(" ");
//delay(1000);

if(now.minute() == 10 && now.second()== 10) {


tampilan();
}
if(now.minute() == 20 && now.second()== 10){
tampilan();
}
if(now.minute() == 30 && now.second()== 10){
tampilan();
}
if(now.minute() == 40 && now.second()== 10){
tampilan();
}
if(now.minute() == 0 && now.second()== 10){
tampilan();
}
if(now.minute() == 50 && now.second()== 10){
tampilan();
}

int suhu = data.temperature;


int lembab = data.humidity;
float temp1 = data.temperature;
float hum = data.humidity;
double T,P;
char result = bmp.startMeasurment();
result = bmp.getTemperatureAndPressure(T,P);
double A = bmp.altitude(P,P0);

lcd.clear();
lcd.setCursor(0, 0);
lcd.print(now.hour(), DEC);
lcd.setCursor(2, 0);
lcd.print(":");
lcd.setCursor(3, 0);
lcd.print(now.minute(), DEC);
lcd.setCursor(5, 0);
lcd.print(":");
lcd.setCursor(6, 0);
lcd.print(now.second(),DEC);
lcd.setCursor(0, 3);
lcd.print(now.year(), DEC);
lcd.setCursor(5, 3);
lcd.print(P);
lcd.setCursor(0, 2);
lcd.print(now.day(), DEC);
lcd.setCursor(2, 2);
lcd.print("-");
lcd.setCursor(10, 0);
lcd.print(suhu);
lcd.setCursor(12, 0);
lcd.print("C");
lcd.setCursor(10, 1);
lcd.print(lembab);
lcd.setCursor(12, 1);
lcd.print("%");
Serial.print(temp1,1);
Serial.print(" ");
Serial.print(hum,1);
Serial.print(" ");
Serial.print(P,2);
Serial.println();

if(now.dayOfWeek()==1){
lcd.setCursor(0, 1);
lcd.print("MONDAY");
}
if(now.dayOfWeek()==2){
lcd.setCursor(0, 1);
lcd.print("TUESDAY");
}
if(now.dayOfWeek()==3){
lcd.setCursor(0, 1);
lcd.print("WEDNESDAY");
}
if(now.dayOfWeek()==4){
lcd.setCursor(0, 1);
lcd.print("THURSDAY");
}
if(now.dayOfWeek()==5){
lcd.setCursor(0, 1);
lcd.print("FRIDAY");
}
if(now.dayOfWeek()==6){
lcd.setCursor(0, 1);
lcd.print("SATURDAY");
}
if(now.dayOfWeek()==0){
lcd.setCursor(0, 1);
lcd.print("SUNDAY");
}
if(now.month()==1){
lcd.setCursor(3, 2);
lcd.print("JANUARY");
}
if(now.month()==2){
lcd.setCursor(3, 2);
lcd.print("FEBRUARY");
}
if(now.month()==3){
lcd.setCursor(3, 2);
lcd.print("MARCH");
}
if(now.month()==4){
lcd.setCursor(3, 2);
lcd.print("APRIL");
}
if(now.month()==5){
lcd.setCursor(3, 2);
lcd.print("MAY");
}
if(now.month()==6){
lcd.setCursor(3, 2);
lcd.print("JUNE");
}
if(now.month()==7){
lcd.setCursor(3, 2);
lcd.print("JULY");
}
if(now.month()==8){
lcd.setCursor(3, 2);
lcd.print("AUGUST");
}
if(now.month()==9){
lcd.setCursor(3, 2);
lcd.print("SEPTEMBER");
}
if(now.month()==10){
lcd.setCursor(3, 2);
lcd.print("OCTOBER");
}
if(now.month()==11){
lcd.setCursor(3, 2);
lcd.print("NOVEMBER");
}
if(now.month()==12){
lcd.setCursor(3, 2);
lcd.print("DECEMBER");
}
delay(1000);
}
}
void tampilan(){
//int chk = DHT.read11(DHT11_PIN);
float temp1 = data.temperature;
float hum = data.humidity;
double T,P;
char result = bmp.startMeasurment();
result = bmp.getTemperatureAndPressure(T,P);
double A = bmp.altitude(P,P0);
ROW++;

Serial.print("DATA,DATE,TIME,");
Serial.print(temp1,2);
Serial.print(",");
Serial.print(hum,2);
Serial.print(",");
Serial.print(P,2);
Serial.print(",");

if (ROW > 9999)


{
ROW = 0;
Serial.println("ROW,SET,2");
}}

Transmitter DHT22
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "DHT.h" // DHT & AM2302 library

// Version number
const float fVerNum = 0.03;
// Data pin connected to AM2302
#define DHTPIN 2

#define DHTTYPE DHT22 // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE); // LED pins

//////////////////////////////////////////////////////
RF24 radio(8,7);

void setupRadio()
{
// Initiate the radio
radio.begin();

// Define the number of retries sending a packet


radio.setRetries(15,15);

// Define the radio's broadcast channel (0 - 127)


radio.setChannel(30);

// Define the radio's bitrate (using cards lowest bitrate)


radio.setDataRate(RF24_250KBPS);

// Define the radio's power amplifier level (RF24_PA_MIN for debugging, RF24_PA_HIGH for
longest range)
radio.setPALevel(RF24_PA_MIN);

// Enable dynamic payloads for packets


radio.enableDynamicPayloads();
}
struct package
{
float temperature ;
float humidity ;
};
typedef struct package Package;
Package data;
void setup()
{

setupRadio();
dht.begin();
}

void loop()
{

data.temperature = dht.readTemperature();
data.humidity = dht.readHumidity();
// Open a writing pipe on the radio
radio.openWritingPipe(0xE8E8F0F0E1LL);

// Write the temperature to the pipe


radio.write(&data, sizeof(data));

167. WEATHER MONITORING DHT11


/*sket ini didesain untuk memantau temperatur, kelembaban dan tekanan udara, data dimonitor dari
LCD dan dikirim ke file exel dengan PLX-DAQ.
LCD monitor dengan teknik serial dengan memanfaatkan IC 74HC595
*/
int ROW = 0;
int LABEL = 1;
#include <dht.h>
dht DHT;
#define DHT11_PIN 5
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
//int led = 13;
#include <SPI.h>
/*
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>
*/
#include <LiquidCrystal_SR.h>
#include "BMP280.h"
//#include "Wire.h"
#define P0 1013.25
BMP280 bmp;
LiquidCrystal_SR lcd(6, 7, 8); //6 to pin14(IC595),7 to pin11(IC595),8 to pin12(IC595)
//jika mp3 shield di pasang maka pin 6,7,8 digantikan dengan pin 14,15,16, karena pin 6,7,8 dipakai
oleh shield
/*
SdFat sd;
SFEMP3Shield MP3player;
*/
void setup(){
if(!bmp.begin()){
Serial.println("BMP init failed!");
while(1);
}
else Serial.println("BMP init success!");

bmp.setOversampling(4);

lcd.begin(16, 4);
Serial.begin(9600);
Serial.println("CLEARDATA");
Serial.println("LABEL,Date,Time,temp1,hum,P,RTC Time");
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
//Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
//sd.begin(SD_SEL, SPI_HALF_SPEED);
//MP3player.begin();
}
void loop(){
/*{
double T,P;
char result = bmp.startMeasurment();

if(result!=0){
delay(result);
result = bmp.getTemperatureAndPressure(T,P);

if(result!=0)
{
double A = bmp.altitude(P,P0);

Serial.print("T = \t");Serial.print(T,2); Serial.print(" degC\t");


Serial.print("P = \t");Serial.print(P,2); Serial.print(" mBar\t");
Serial.print("A = \t");Serial.print(A,2); Serial.println(" m");
lcd.setCursor(5, 3);
lcd.print(P);
}
else {
Serial.println("Error.");
}
}
else {
Serial.println("Error.");
}

//delay(1000);
}*/
/*int nilai2 = analogRead(PinSensorMasuk2);
int nilai3 = analogRead(PinSensorMasuk3);
float milivolt2 = (nilai2 / 1024.0) * 5000;
float temp2 = milivolt2 / 10;
float milivolt3 = (nilai3 / 1024.0) * 5000;
float temp3 = milivolt3 / 10;*/
//----bagian ini untuk membuyikan alarm musik dari mp3 shield
DateTime now = RTC.now();
/*
if(now.hour() == 8 && now.minute() == 0){
MP3player.playTrack(1);
}
if(now.hour() == 9 && now.minute() == 0){
MP3player.playTrack(2);
}
if(now.hour() == 10 && now.minute() == 0){
MP3player.playTrack(3);
}
if(now.hour() == 11 && now.minute() == 0){
MP3player.playTrack(4);
}
if(now.hour() == 12 && now.minute() == 0){
MP3player.playTrack(5);
}
if(now.hour() == 13 && now.minute() == 0){
MP3player.playTrack(6);
}
if(now.hour() == 14 && now.minute() == 0){
MP3player.playTrack(7);
}
if(now.hour() == 15 && now.minute() == 0){
MP3player.playTrack(8);
}
if(now.hour() == 16 && now.minute() == 0){
MP3player.playTrack(9);
}
if(now.hour() == 17 && now.minute() == 0){
MP3player.playTrack(10);
}
if(now.hour() == 18 && now.minute() == 0){
MP3player.playTrack(11);
}
if(now.hour() == 19 && now.minute() == 0){
MP3player.playTrack(12);
}
if(now.hour() == 20 && now.minute() == 0){
MP3player.playTrack(13);
}
if(now.hour() == 21 && now.minute() == 0){
MP3player.playTrack(14);
}
if(now.hour() == 22 && now.minute() == 0){
MP3player.playTrack(15);
}
*/

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
//delay(1000);

if(now.minute() == 10 && now.second()== 10) {


tampilan();
}
if(now.minute() == 20 && now.second()== 10){
tampilan();
}
if(now.minute() == 30 && now.second()== 10){
tampilan();
}
if(now.minute() == 40 && now.second()== 10){
tampilan();
}
if(now.minute() == 0 && now.second()== 10){
tampilan();
}
if(now.minute() == 50 && now.second()== 10){
tampilan();
}

int suhu = DHT.temperature;


int lembab = DHT.humidity;
double T,P;
char result = bmp.startMeasurment();
result = bmp.getTemperatureAndPressure(T,P);
double A = bmp.altitude(P,P0);

lcd.clear();
lcd.setCursor(0, 0);
lcd.print(now.hour(), DEC);
lcd.setCursor(2, 0);
lcd.print(":");
lcd.setCursor(3, 0);
lcd.print(now.minute(), DEC);
lcd.setCursor(5, 0);
lcd.print(":");
lcd.setCursor(6, 0);
lcd.print(now.second(),DEC);
lcd.setCursor(0, 3);
lcd.print(now.year(), DEC);
lcd.setCursor(5, 3);
lcd.print(P);
lcd.setCursor(0, 2);
lcd.print(now.day(), DEC);
lcd.setCursor(2, 2);
lcd.print("-");
lcd.setCursor(10, 0);
lcd.print(suhu);
lcd.setCursor(12, 0);
lcd.print("C");
lcd.setCursor(10, 1);
lcd.print(lembab);
lcd.setCursor(12, 1);
lcd.print("%");

if(now.dayOfWeek()==1){
lcd.setCursor(0, 1);
lcd.print("MONDAY");
}
if(now.dayOfWeek()==2){
lcd.setCursor(0, 1);
lcd.print("TUESDAY");
}
if(now.dayOfWeek()==3){
lcd.setCursor(0, 1);
lcd.print("WEDNESDAY");
}
if(now.dayOfWeek()==4){
lcd.setCursor(0, 1);
lcd.print("THURSDAY");
}
if(now.dayOfWeek()==5){
lcd.setCursor(0, 1);
lcd.print("FRIDAY");
}
if(now.dayOfWeek()==6){
lcd.setCursor(0, 1);
lcd.print("SATURDAY");
}
if(now.dayOfWeek()==0){
lcd.setCursor(0, 1);
lcd.print("SUNDAY");
}
if(now.month()==1){
lcd.setCursor(3, 2);
lcd.print("JANUARY");
}
if(now.month()==2){
lcd.setCursor(3, 2);
lcd.print("FEBRUARY");
}
if(now.month()==3){
lcd.setCursor(3, 2);
lcd.print("MARCH");
}
if(now.month()==4){
lcd.setCursor(3, 2);
lcd.print("APRIL");
}
if(now.month()==5){
lcd.setCursor(3, 2);
lcd.print("MAY");
}
if(now.month()==6){
lcd.setCursor(3, 2);
lcd.print("JUNE");
}
if(now.month()==7){
lcd.setCursor(3, 2);
lcd.print("JULY");
}
if(now.month()==8){
lcd.setCursor(3, 2);
lcd.print("AUGUST");
}
if(now.month()==9){
lcd.setCursor(3, 2);
lcd.print("SEPTEMBER");
}
if(now.month()==10){
lcd.setCursor(3, 2);
lcd.print("OCTOBER");
}
if(now.month()==11){
lcd.setCursor(3, 2);
lcd.print("NOVEMBER");
}
if(now.month()==12){
lcd.setCursor(3, 2);
lcd.print("DECEMBER");
}
delay(1000);
}
void tampilan(){
int chk = DHT.read11(DHT11_PIN);
float temp1 = DHT.temperature;
float hum = DHT.humidity;
double T,P;
char result = bmp.startMeasurment();
result = bmp.getTemperatureAndPressure(T,P);
double A = bmp.altitude(P,P0);
ROW++;

Serial.print("DATA,DATE,TIME,");
Serial.print(temp1,2);
Serial.print(",");
Serial.print(hum,2);
Serial.print(",");
Serial.print(P,2);
Serial.print(",");

if (ROW > 9999)


{
ROW = 0;
Serial.println("ROW,SET,2");
}}

168. LED PETERN SELECT BY IR REMOTE


#include <EEPROM.h>
#include <IRremote.h>
int RECV_PIN = 12;
byte petern;
// Inisialisasi Pin LED
const int pinLED1 =2;
const int pinLED2 =3;
const int pinLED3 =4;
const int pinLED4 =5;
const int pinLED5 =6;
const int pinLED6 =7;
const int pinLED7 =8;
const int pinLED8 =9;
const int pinLED9 =10;
const int pinLED10=11;
const int pinLED11=14;

IRrecv irrecv(RECV_PIN);
decode_results results;
void setup() {
irrecv.enableIRIn(); // Start the receiver
// pin LED sebagai output
pinMode(pinLED1, OUTPUT);
pinMode(pinLED2, OUTPUT);
pinMode(pinLED3, OUTPUT);
pinMode(pinLED4, OUTPUT);
pinMode(pinLED5, OUTPUT);
pinMode(pinLED6, OUTPUT);
pinMode(pinLED7, OUTPUT);
pinMode(pinLED8, OUTPUT);
pinMode(pinLED9, OUTPUT);
pinMode(pinLED10, OUTPUT);
pinMode(pinLED11, OUTPUT);

}
int on = 0;
unsigned long last = millis();
void loop() {
if (irrecv.decode(&results)) {
if (results.value == 0x20F0E01F) {
EEPROM.write(1, 1);
}
else if (results.value == 0x20F002FD) {
EEPROM.write(1, 2);
}
else if (results.value == 0x20F0609F) {
EEPROM.write(1, 3);
}
irrecv.resume(); // Receive the next value
}

petern = EEPROM.read(1);

if(petern == 1){
petern1();
}
if(petern == 2){
petern2();
}
if(petern == 3){
petern3();
}
}#

void petern1(){
for(int i=0; i<12; i++){
if(i==0){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==1){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==2){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==3){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==4){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==5){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==6){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==7){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==8){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==9){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==10){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, LOW);
}
else if(i==11){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);
}
delay(100);
}
}
void petern2(){
for(int i=0; i<12; i++){
if(i==0){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==1){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, HIGH);

}else if(i==2){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);

}else if(i==3){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);

}else if(i==4){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);

}else if(i==5){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);

}else if(i==6){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, HIGH);

}else if(i==7){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, LOW);

}else if(i==8){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==9){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==10){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==11){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
delay(100);
}
}

void petern3(){
for(int i=0; i<21; i++){
if(i==0){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==1){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==2){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}else if(i==3){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==4){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==5){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==6){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==7){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==8){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);

}else if(i==9){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, LOW);

}else if(i==10){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, HIGH);
}
else if(i==11){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, HIGH);
digitalWrite(pinLED11, LOW);
}
else if(i==12){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, HIGH);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==13){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, HIGH);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==14){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, HIGH);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==15){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, HIGH);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==16){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, HIGH);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==17){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, HIGH);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==18){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, HIGH);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==19){
digitalWrite(pinLED1, LOW);
digitalWrite(pinLED2, HIGH);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
else if(i==20){
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, LOW);
digitalWrite(pinLED3, LOW);
digitalWrite(pinLED4, LOW);
digitalWrite(pinLED5, LOW);
digitalWrite(pinLED6, LOW);
digitalWrite(pinLED7, LOW);
digitalWrite(pinLED8, LOW);
digitalWrite(pinLED9, LOW);
digitalWrite(pinLED10, LOW);
digitalWrite(pinLED11, LOW);
}
delay(100);
}
}

169. SWITCH AC LAMP BY IR REMOTE


/*
source: www.electroschematics.com
You'll need to change the led pins and the codes
accordingly to your configuration and IR remote
552656927
552600317
552624287
*/

#include <IRremote.h>

int RECV_PIN = 3; // the pin where you connect the output pin of TSOP4838
int led1 = 2;
int led2 = 4;
int led3 = 7;
int itsONled[] = {0,0,0,0};
/* the initial state of LEDs is OFF (zero)
the first zero must remain zero but you can
change the others to 1's if you want a certain
led to light when the board is powered */
#define code1 552656927 // code received from button A
#define code2 552600317 // code received from button B
#define code3 552624287 // code received from button C
IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
Serial.begin(9600); // you can comment this line
irrecv.enableIRIn(); // Start the receiver
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}

void loop() {
if (irrecv.decode(&results)) {
unsigned int value = results.value;
switch(value) {
case code1:
if(itsONled[1] == 1) { // if first led is on then
digitalWrite(led1, LOW); // turn it off when button is pressed
itsONled[1] = 0; // and set its state as off
} else { // else if first led is off
digitalWrite(led1, HIGH); // turn it on when the button is pressed
itsONled[1] = 1; // and set its state as on
}
break;
case code2:
if(itsONled[2] == 1) {
digitalWrite(led2, LOW);
itsONled[2] = 0;
} else {
digitalWrite(led2, HIGH);
itsONled[2] = 1;
}
break;
case code3:
if(itsONled[3] == 1) {
digitalWrite(led3, LOW);
itsONled[3] = 0;
} else {
digitalWrite(led3, HIGH);
itsONled[3] = 1;
}
break;
}
Serial.println(value); // you can comment this line
irrecv.resume(); // Receive the next value
}
}

170. TLC5940 RGB LED COMMON ANODE


/*
Pin 1 (OUT1) RGB LED 1 – green
Pin 2 (OUT2) RGB LED 1 – blue
Pin 3 (OUT3) RGB LED 2 – red
Pin 4 (OUT4) RGB LED 2 – green
Pin 5 (OUT5) RGB LED 2 – blue
Pin 6 (OUT6) RGB LED 3 – red
Pin 7 (OUT7) RGB LED 3 – green
Pin 8 (OUT8) RGB LED 3 – blue
Pin 9 (OUT9) RGB LED 4 – red
Pin 10 (OUT10) RGB LED 4 – green
Pin 11 (OUT11) RGB LED 4 – blue
Pin 12 (OUT12) RGB LED 5 – red
Pin 13 (OUT13) RGB LED 5 – green
Pin 14 (OUT14) RGB LED 5 – blue
Pin 15 (OUT15) not connected
Pin 16 (XERR) not connected
Pin 17 (SOUT) not connected
Pin 18 (GSCLK) Arduino – D3
Pin 19 (DCPRG) +5V
Pin 20 (IREF) Resistor 2kOhm to Ground
Pin 21 (VCC) +5V
Pin 22 (GND) Ground
Pin 23 (BLANK) Arduino – D10, Resistor 10kOhm to +5V
Pin 24 (XLAT) Arduino – D9
Pin 25 (SCLK) Arduino – D13
Pin 26 (SIN) Arduino – D11
Pin 27 (VPRG) Ground
Pin 28 (OUT0) RGB LED 1 – red
*/
#include "Tlc5940.h"
#define NUM_LEDS 5

struct RGB { byte r; byte g; byte b; };

RGB rgb;
int global_dim=16;

void setup(){

Tlc.init();
}

void loop(){

randomSeed(millis());

int wait=random(1,30);
int dim=random(4,6);
int max_cycles=8;
int cycles=random(1,max_cycles+1);

rainbowCycle(wait,cycles,dim);

void setLed(byte num,int red,int green,int blue){

if(global_dim){
red=red/global_dim;
green=green/global_dim;
blue=blue/global_dim;
}

Tlc.set(num*3,red);
Tlc.set(num*3+1,green);
Tlc.set(num*3+2,blue);

void rainbowCycle(uint8_t wait,byte cycle,byte dim) {

int cycles, j, k;

for(cycles=0;cycles<cycle;cycles++){

byte dir=random(0,2);
k=255;

for (j=0; j < 256; j++,k--) { // cycles of all colors in the wheel

if(k<0)k=255;
// Tlc.clear();

for(int i=0; i<NUM_LEDS; i+=1) {

Wheel(((i * 256 / NUM_LEDS) + (dir==0?j:k)) % 256,dim);


setLed(i,rgb.r*16,rgb.g*16,rgb.b*16);

}
Tlc.update();
delay(wait);
}
}
}

void Wheel(byte WheelPos,byte dim){

if (WheelPos < 85) {


rgb.r=0;
rgb.g=WheelPos * 3/dim;
rgb.b=(255 - WheelPos * 3)/dim;;
return;
}
else if (WheelPos < 170) {
WheelPos -= 85;
rgb.r=WheelPos * 3/dim;
rgb.g=(255 - WheelPos * 3)/dim;
rgb.b=0;
return;
}
else {
WheelPos -= 170;
rgb.r=(255 - WheelPos * 3)/dim;
rgb.g=0;
rgb.b=WheelPos * 3/dim;
return;
}
}

171. RGB WHEEL


/*
Rainbow

Take a tricolour LED through the colours of the rainbow using an analogue input.

The circuit:
* TBC

Created 21 April 2012


By Jason Judge

This example code is in the public domain.

*/

// The three primary colour LEDs, driven as analgue outputs (actually PWM, but
// close enough for our analogue eyes).

const int ledPinRed = 3; // Red LED connected to analogue out pin


const int ledPinGrn = 5; // Green LED connected to analogue out pin
const int ledPinBlu = 6; // Blue LED connected to analogue out pin

const int modeSwitchPin = 12;

// The Hue potentiometer goes on an analogue pin, taking the pin from
// 0V to 5V.

const int potPinHue = 0;

// Constants to define the ranges.

const int hueRedLow = 0;


const int hueRedHigh = 255;
const int hueBlue = 170;

// The size of the angle of one sector (1/6 of a colour wheel), and of a complete
// cycle of the colour wheel.

const int angleMin = 0;


const int angleSector = 60;
const int angleMax = 360;

const int brightMin = 0;


const int brightMax = 255;

// Work variables.

// The potentiometer value is mapped to the range 0 to 360 (degrees).


int potValueHue;

// The hue is the range 0 (red) to 170 (blue) in rainbow


// mode or 255 (red) in colour wheel mode.
// The brightness ranges from 0 (dark) to 255 (full brightness)

int hue, brightness;

// The saturation is fixed at 255 (full) to remove blead-through of different


// colours.
// It could be linked to another potentiometer if a demonstration of hue
// is desired.

const int saturation = 255;

// The brightess of each LED (0 to 255).

unsigned int r, g, b;

void setup() {
// Still need to set a baud rate, even for USB.
Serial.begin(9600);
// Set LED pins to output.
pinMode(ledPinRed, OUTPUT);
pinMode(ledPinGrn, OUTPUT);
pinMode(ledPinBlu, OUTPUT);

// Poteniometer analogue pin is an input.


pinMode(potPinHue, INPUT);

// TODO: mode switch in a digital input.


pinMode(modeSwitchPin, INPUT);
}

void loop() {
// The Hue potentiometer value is mapped to degrees - 0 to 360 - for convenience.
potValueHue = map(analogRead(potPinHue), 0, 1023, 0, 360);

// Control the mode using a physical switch.

if (digitalRead(modeSwitchPin)) {
// Rainbow colour mode (infra-red to ultra-violet - well invisible to invisible ;-).

// The hue ranges from red (0) at 60 degrees to blue (170) at 300 degrees.
hue = constrain(map(potValueHue, angleSector, angleMax - angleSector, hueRedLow,
hueBlue), hueRedLow, hueBlue);

// Brightness - fade up 0-60 degrees


brightness = constrain(map(potValueHue, angleMin, angleSector, brightMin, brightMax),
brightMin, brightMax);

// Brightness fade down 300-360 degrees


brightness = brightness - constrain(map(potValueHue, angleMax - angleSector, angleMax,
brightMin, brightMax), brightMin, brightMax);
} else {
// Colour wheel mode (red to red, wrapped around in a cycle).

hue = map(potValueHue, angleMin, angleMax, hueRedLow, hueRedHigh);

// The brightness is fixed at full for the colour wheel. This could be
// linked to another poteniometer if that is a concept you wish to
// demonstrate.
brightness = 255;
}

// Do the conversion.
HSBToRGB(hue, saturation, brightness, &r, &g, &b);

analogWrite(ledPinRed, r);
analogWrite(ledPinGrn, g);
analogWrite(ledPinBlu, b);

Serial.print(" bright=");
Serial.print(brightness);
Serial.print(" hue=");
Serial.print(hue);
Serial.print(" red=");
Serial.print(r);
Serial.print(" green=");
Serial.print(g);
Serial.print(" blue=");
Serial.print(b);
Serial.println("");
delay(50);
}

// This function taken from here:


// http://eduardofv.com/read_post/179-Arduino-RGB-LED-HSV-Color-Wheel-

void HSBToRGB(
unsigned int inHue, unsigned int inSaturation, unsigned int inBrightness,
unsigned int *oR, unsigned int *oG, unsigned int *oB )
{
if (inSaturation == 0)
{
// achromatic (grey)
*oR = *oG = *oB = inBrightness;
}
else
{
unsigned int scaledHue = (inHue * 6);
unsigned int sector = scaledHue >> 8; // sector 0 to 5 around the color wheel
unsigned int offsetInSector = scaledHue - (sector << 8); // position within the sector
unsigned int p = (inBrightness * ( 255 - inSaturation )) >> 8;
unsigned int q = (inBrightness * ( 255 - ((inSaturation * offsetInSector) >> 8) )) >> 8;
unsigned int t = (inBrightness * ( 255 - ((inSaturation * ( 255 - offsetInSector )) >> 8) )) >> 8;

switch( sector ) {
case 0:
*oR = inBrightness;
*oG = t;
*oB = p;
break;
case 1:
*oR = q;
*oG = inBrightness;
*oB = p;
break;
case 2:
*oR = p;
*oG = inBrightness;
*oB = t;
break;
case 3:
*oR = p;
*oG = q;
*oB = inBrightness;
break;
case 4:
*oR = t;
*oG = p;
*oB = inBrightness;
break;
default: // case 5:
*oR = inBrightness;
*oG = p;
*oB = q;
break;
}
}
}

172. SEVEN SEGMENT MODULE 4 DIGIT COMMON ANODE


/*
6-13-2011
Spark Fun Electronics 2011
Nathan Seidle

This code is public domain but you buy me a beer if you use this and we meet
someday (Beerware license).
4 digit 7 segment display:
http://www.sparkfun.com/products/9483
Datasheet:
http://www.sparkfun.com/datasheets/Components/LED/7-Segment/YSD-439AR6B-35.pdf

This is an example of how to drive a 7 segment LED display from an ATmega


without the use of current limiting resistors. This technique is very common
but requires some knowledge of electronics - you do run the risk of dumping
too much current through the segments and burning out parts of the display.
If you use the stock code you should be ok, but be careful editing the
brightness values.

This code should work with all colors (red, blue, yellow, green) but the
brightness will vary from one color to the next because the forward voltage
drop of each color is different. This code was written and calibrated for the
red color.

This code will work with most Arduinos but you may want to re-route some of
the pins.

7 segments
4 digits
1 colon
=
12 pins required for full control
This sketch for common anode

*/

int digit1 = 11; //PWM Display pin 1


int digit2 = 10; //PWM Display pin 2
int digit3 = 9; //PWM Display pin 6
int digit4 = 6; //PWM Display pin 8

//Pin mapping from Arduino to the ATmega DIP28 if you need it


//http://www.arduino.cc/en/Hacking/PinMapping
int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

void setup() {
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);
pinMode(digit1, OUTPUT);
pinMode(digit2, OUTPUT);
pinMode(digit3, OUTPUT);
pinMode(digit4, OUTPUT);

pinMode(13, OUTPUT);
}

void loop() {

//long startTime = millis();

displayNumber(millis()/1000);

//while( (millis() - startTime) < 2000) {


//displayNumber(1217);
//}
//delay(1000);
}

//Given a number, we display 10:22


//After running through the 4 numbers, the display is left turned off

//Display brightness
//Each digit is on for a certain amount of microseconds
//Then it is off until we have reached a total of 20ms for the function call
//Let's assume each digit is on for 1000us
//Each digit is on for 1ms, there are 4 digits, so the display is off for 16ms.
//That's a ratio of 1ms to 16ms or 6.25% on time (PWM).
//Let's define a variable called brightness that varies from:
//5000 blindingly bright (15.7mA current draw per digit)
//2000 shockingly bright (11.4mA current draw per digit)
//1000 pretty bright (5.9mA)
//500 normal (3mA)
//200 dim but readable (1.4mA)
//50 dim but readable (0.56mA)
//5 dim but readable (0.31mA)
//1 dim but readable in dark (0.28mA)

void displayNumber(int toDisplay) {


#define DISPLAY_BRIGHTNESS 1000

#define DIGIT_ON HIGH


#define DIGIT_OFF LOW

long beginTime = millis();

for(int digit = 4 ; digit > 0 ; digit--) {

//Turn on a digit for a short amount of time


switch(digit) {
case 1:
digitalWrite(digit1, DIGIT_OFF);
break;
case 2:
digitalWrite(digit2, DIGIT_OFF);
break;
case 3:
digitalWrite(digit3, DIGIT_OFF);
break;
case 4:
digitalWrite(digit4, DIGIT_OFF);
break;
}

//Turn on the right segments for this digit


lightNumber(toDisplay % 10);
toDisplay /= 10;

delayMicroseconds(DISPLAY_BRIGHTNESS);
//Display digit for fraction of a second (1us to 5000us, 500 is pretty good)

//Turn off all segments


lightNumber(10);

//Turn off all digits


digitalWrite(digit1, DIGIT_ON);
digitalWrite(digit2, DIGIT_ON);
digitalWrite(digit3, DIGIT_ON);
digitalWrite(digit4, DIGIT_ON);
}

while( (millis() - beginTime) < 10) ;


//Wait for 20ms to pass before we paint the display again
}

//Given a number, turns on those segments


//If number == 10, then turn off number
void lightNumber(int numberToDisplay) {

#define SEGMENT_ON LOW


#define SEGMENT_OFF HIGH

switch (numberToDisplay){

case 0:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_OFF);
break;

case 1:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 2:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 3:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 4:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 5:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 6:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 7:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 8:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 9:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 10:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
}
}
173. ANALOG ON SEVEN SEGMENT
/*
6-13-2011
Spark Fun Electronics 2011
Nathan Seidle

This code is public domain but you buy me a beer if you use this and we meet
someday (Beerware license).
4 digit 7 segment display:
http://www.sparkfun.com/products/9483
Datasheet:
http://www.sparkfun.com/datasheets/Components/LED/7-Segment/YSD-439AR6B-35.pdf

This is an example of how to drive a 7 segment LED display from an ATmega


without the use of current limiting resistors. This technique is very common
but requires some knowledge of electronics - you do run the risk of dumping
too much current through the segments and burning out parts of the display.
If you use the stock code you should be ok, but be careful editing the
brightness values.

This code should work with all colors (red, blue, yellow, green) but the
brightness will vary from one color to the next because the forward voltage
drop of each color is different. This code was written and calibrated for the
red color.

This code will work with most Arduinos but you may want to re-route some of
the pins.

7 segments
4 digits
1 colon
=
12 pins required for full control
This sketch for common anode

*/

int digit1 = 11; //PWM Display pin 1


int digit2 = 10; //PWM Display pin 2
int digit3 = 9; //PWM Display pin 6
int digit4 = 6; //PWM Display pin 8

//Pin mapping from Arduino to the ATmega DIP28 if you need it


//http://www.arduino.cc/en/Hacking/PinMapping
int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

void setup() {
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);
pinMode(digit1, OUTPUT);
pinMode(digit2, OUTPUT);
pinMode(digit3, OUTPUT);
pinMode(digit4, OUTPUT);

pinMode(13, OUTPUT);
}

void loop() {
int sensorValue = analogRead(A3);
//long startTime = millis();

displayNumber(sensorValue);

//while( (millis() - startTime) < 2000) {


//displayNumber(1217);
//}
//delay(1000);
}

//Given a number, we display 10:22


//After running through the 4 numbers, the display is left turned off

//Display brightness
//Each digit is on for a certain amount of microseconds
//Then it is off until we have reached a total of 20ms for the function call
//Let's assume each digit is on for 1000us
//Each digit is on for 1ms, there are 4 digits, so the display is off for 16ms.
//That's a ratio of 1ms to 16ms or 6.25% on time (PWM).
//Let's define a variable called brightness that varies from:
//5000 blindingly bright (15.7mA current draw per digit)
//2000 shockingly bright (11.4mA current draw per digit)
//1000 pretty bright (5.9mA)
//500 normal (3mA)
//200 dim but readable (1.4mA)
//50 dim but readable (0.56mA)
//5 dim but readable (0.31mA)
//1 dim but readable in dark (0.28mA)

void displayNumber(int toDisplay) {


#define DISPLAY_BRIGHTNESS 1000

#define DIGIT_ON HIGH


#define DIGIT_OFF LOW

long beginTime = millis();

for(int digit = 4 ; digit > 0 ; digit--) {

//Turn on a digit for a short amount of time


switch(digit) {
case 1:
digitalWrite(digit1, DIGIT_OFF);
break;
case 2:
digitalWrite(digit2, DIGIT_OFF);
break;
case 3:
digitalWrite(digit3, DIGIT_OFF);
break;
case 4:
digitalWrite(digit4, DIGIT_OFF);
break;
}

//Turn on the right segments for this digit


lightNumber(toDisplay % 10);
toDisplay /= 10;

delayMicroseconds(DISPLAY_BRIGHTNESS);
//Display digit for fraction of a second (1us to 5000us, 500 is pretty good)

//Turn off all segments


lightNumber(10);

//Turn off all digits


digitalWrite(digit1, DIGIT_ON);
digitalWrite(digit2, DIGIT_ON);
digitalWrite(digit3, DIGIT_ON);
digitalWrite(digit4, DIGIT_ON);
}

while( (millis() - beginTime) < 10) ;


//Wait for 20ms to pass before we paint the display again
}

//Given a number, turns on those segments


//If number == 10, then turn off number
void lightNumber(int numberToDisplay) {

#define SEGMENT_ON LOW


#define SEGMENT_OFF HIGH

switch (numberToDisplay){

case 0:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_OFF);
break;

case 1:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 2:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 3:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 4:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 5:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 6:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 7:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 8:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 9:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 10:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
}
}
174. LIGHTNING COUNTER
/*
State change detection (edge detection)

Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.

This example shows how to detect when a button or button changes from off to on
and on to off.

The circuit:
* pushbutton attached to pin 7 from +5V
* 10M resistor attached to pin 7 from ground
* LED attached from pin 8 to ground (or use the built-in LED on
most Arduino boards)

created 27 Sep 2005


modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/ButtonStateChange

*/
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to

// Variables will change:


int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}

void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state


if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == LOW) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
//Serial.println("on");
Serial.print("number of lightning: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button
// wend from on to off:
//Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(1);
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;

/*
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
*/
}

175. LIGHTNING COUNTER WITH LED DISPLAY


/*
6-13-2011
Spark Fun Electronics 2011
Nathan Seidle

This code is public domain but you buy me a beer if you use this and we meet
someday (Beerware license).

4 digit 7 segment display:


http://www.sparkfun.com/products/9483
Datasheet:
http://www.sparkfun.com/datasheets/Components/LED/7-Segment/YSD-439AR6B-35.pdf

This is an example of how to drive a 7 segment LED display from an ATmega


without the use of current limiting resistors. This technique is very common
but requires some knowledge of electronics - you do run the risk of dumping
too much current through the segments and burning out parts of the display.
If you use the stock code you should be ok, but be careful editing the
brightness values.
This code should work with all colors (red, blue, yellow, green) but the
brightness will vary from one color to the next because the forward voltage
drop of each color is different. This code was written and calibrated for the
red color.

This code will work with most Arduinos but you may want to re-route some of
the pins.

7 segments
4 digits
1 colon
=
12 pins required for full control
This sketch for common anode

*/
const int buttonPin = 2;
int digit1 = 11; //PWM Display pin 1
int digit2 = 10; //PWM Display pin 2
int digit3 = 9; //PWM Display pin 6
int digit4 = 6; //PWM Display pin 8

int buttonPushCounter = 0; // counter for the number of button presses


int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

//Pin mapping from Arduino to the ATmega DIP28 if you need it


//http://www.arduino.cc/en/Hacking/PinMapping
int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

void setup() {
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);

pinMode(digit1, OUTPUT);
pinMode(digit2, OUTPUT);
pinMode(digit3, OUTPUT);
pinMode(digit4, OUTPUT);

pinMode(13, OUTPUT);
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);

// initialize serial communication:


Serial.begin(9600);
}

void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state


if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == LOW) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
//Serial.println("on");
Serial.print("number of lightning: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button
// wend from on to off:
//Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(1);
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;

/*
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
*/

//long startTime = millis();

displayNumber(buttonPushCounter);

//while( (millis() - startTime) < 2000) {


//displayNumber(1217);
//}
//delay(1000);
}

//Given a number, we display 10:22


//After running through the 4 numbers, the display is left turned off

//Display brightness
//Each digit is on for a certain amount of microseconds
//Then it is off until we have reached a total of 20ms for the function call
//Let's assume each digit is on for 1000us
//Each digit is on for 1ms, there are 4 digits, so the display is off for 16ms.
//That's a ratio of 1ms to 16ms or 6.25% on time (PWM).
//Let's define a variable called brightness that varies from:
//5000 blindingly bright (15.7mA current draw per digit)
//2000 shockingly bright (11.4mA current draw per digit)
//1000 pretty bright (5.9mA)
//500 normal (3mA)
//200 dim but readable (1.4mA)
//50 dim but readable (0.56mA)
//5 dim but readable (0.31mA)
//1 dim but readable in dark (0.28mA)

void displayNumber(int toDisplay) {


#define DISPLAY_BRIGHTNESS 1000

#define DIGIT_ON HIGH


#define DIGIT_OFF LOW

long beginTime = millis();

for(int digit = 4 ; digit > 0 ; digit--) {

//Turn on a digit for a short amount of time


switch(digit) {
case 1:
digitalWrite(digit1, DIGIT_OFF);
break;
case 2:
digitalWrite(digit2, DIGIT_OFF);
break;
case 3:
digitalWrite(digit3, DIGIT_OFF);
break;
case 4:
digitalWrite(digit4, DIGIT_OFF);
break;
}

//Turn on the right segments for this digit


lightNumber(toDisplay % 10);
toDisplay /= 10;
delayMicroseconds(DISPLAY_BRIGHTNESS);
//Display digit for fraction of a second (1us to 5000us, 500 is pretty good)

//Turn off all segments


lightNumber(10);

//Turn off all digits


digitalWrite(digit1, DIGIT_ON);
digitalWrite(digit2, DIGIT_ON);
digitalWrite(digit3, DIGIT_ON);
digitalWrite(digit4, DIGIT_ON);
}

while( (millis() - beginTime) < 10) ;


//Wait for 20ms to pass before we paint the display again
}

//Given a number, turns on those segments


//If number == 10, then turn off number
void lightNumber(int numberToDisplay) {

#define SEGMENT_ON LOW


#define SEGMENT_OFF HIGH

switch (numberToDisplay){

case 0:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_OFF);
break;

case 1:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 2:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 3:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 4:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 5:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 6:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 7:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 8:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 9:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 10:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
}
}

176. CALL WITH A6 GSM MODULE


//remove RX and TX jumper from arduino when uploading sketch
char phone_no[]="+97433187702";

void setup()
{
Serial.begin(9600);
delay(200);
Serial.println("AT");
delay(1000);
Serial.print("ATD");
Serial.println(phone_no);
delay(10000);
Serial.println("ATH");
}
void loop()
{
}

177. PIR ALARM WITH A6 GSM MODULE


//remove RX and TX jumper from arduino when uploading sketch
int pirPin = 5;
int statePir = 0;
char phone_no[]="+97433187702";
void setup()
{
pinMode(pirPin,INPUT);
Serial.begin(9600);

}
void loop()
{
statePir = digitalRead(pirPin);
if (statePir == HIGH)
{
call();
}
if (statePir == LOW)
{

}
}

void call(){
Serial.println("AT");
delay(1000);
Serial.print("ATD");
Serial.println(phone_no);
delay(10000);
Serial.println("ATH");
}

178. PIR ALARM WITH A6 SERIAL SOFTWARE


int pirPin = 5;
int statePir = 0;
//char phone_no[]="+97433187702";
#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
// Tx of A6 linked to pin 7
const int pinRxNano = 7;
// Rx of A6 linked to pin 8
const int pinTxNano = 8;
const String phoneNumber= "+97433187702";
const String messageInit = "A6 ready";
SoftwareSerial A6GSM(pinRxNano, pinTxNano);
int numring=0;
int comring=3;
int onoff=0; // 0 = off, 1 = on
void Response(){
int a = 0;
Serial.println();
while(1){
if(A6GSM.available()){
String dataFromA6 =A6GSM.readString();
dataFromA6.trim();
Serial.println(dataFromA6);
a++;
if(dataFromA6.indexOf("OK")>0){break;}
}
if(a>500){a=0;break;}
delay(200);
}
}
void startAT(){
int nbAT = 0;
while(1){
if (nbAT==0){A6GSM.println("AT");Serial.print(".");}
if(A6GSM.available()){
String dataFromA6 =A6GSM.readString();
dataFromA6.trim();
Serial.println(dataFromA6);
if(dataFromA6.indexOf("OK")>0){break;}
}
delay(200);
nbAT++;
if(nbAT++>10){nbAT=0;}
}
}
void envoieSMS(String numeroEnvoi, String messageEnvoi) {
delay(200);
Serial.println("Selection format message SMS");
A6GSM.println("AT+CMGF=1");
Response();
delay(200);
Serial.println("Envoi message SMS");
A6GSM.print("AT+CMGS=\"");
A6GSM.print(numeroEnvoi);
A6GSM.println("\"");
delay(200);
A6GSM.print(messageEnvoi);
delay(200);
A6GSM.println (char(26));
Response();
}
void setup()
{
pinMode(pirPin,INPUT);
//Serial.begin(9600);
A6GSM.begin(9600);
Serial.begin(9600);
delay(200);
Serial.println("Init");
//AT
startAT();
//envoieSMS(phoneNumber,messageInit);

void loop()
{
statePir = digitalRead(pirPin);
if (statePir == HIGH)
{
call();
}
if (statePir == LOW)
{

}
}

void call(){
A6GSM.println("AT");
delay(1000);
A6GSM.print("ATD");
A6GSM.println(phoneNumber);
delay(10000);
A6GSM.println("ATH");
}
179. LED SWITCH WITH GSM CALL

#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
// Tx of A6 linked to pin 7
const int pinRxNano = 7;
// Rx of A6 linked to pin 8
const int pinTxNano = 8;
const String phoneNumber= "+97433187702";
const String messageInit = "A6 ready";
SoftwareSerial A6GSM(pinRxNano, pinTxNano);
int numring=0;
int comring=3;
int onoff=0; // 0 = off, 1 = on
void Response(){
int a = 0;
Serial.println();
while(1){
if(A6GSM.available()){
String dataFromA6 =A6GSM.readString();
dataFromA6.trim();
Serial.println(dataFromA6);
a++;
if(dataFromA6.indexOf("OK")>0){break;}
}
if(a>500){a=0;break;}
delay(200);
}
}
void startAT(){
int nbAT = 0;
while(1){
if (nbAT==0){A6GSM.println("AT");Serial.print(".");}
if(A6GSM.available()){
String dataFromA6 =A6GSM.readString();
dataFromA6.trim();
Serial.println(dataFromA6);
if(dataFromA6.indexOf("OK")>0){break;}
}
delay(200);
nbAT++;
if(nbAT++>10){nbAT=0;}
}
}
void envoieSMS(String numeroEnvoi, String messageEnvoi) {
delay(200);
Serial.println("Selection format message SMS");
A6GSM.println("AT+CMGF=1");
Response();
delay(200);
Serial.println("Envoi message SMS");
A6GSM.print("AT+CMGS=\"");
A6GSM.print(numeroEnvoi);
A6GSM.println("\"");
delay(200);
A6GSM.print(messageEnvoi);
delay(200);
A6GSM.println (char(26));
Response();
}
void setup()
{
pinMode(12, OUTPUT);
digitalWrite(12, LOW);
A6GSM.begin(9600);
Serial.begin(9600);
delay(200);
Serial.println("Init");
//AT
startAT();
//envoieSMS(phoneNumber,messageInit);
}
void doSomething()
{
if (onoff==0)
{
onoff=1;
digitalWrite(12, HIGH);
}
else
if (onoff==1)
{
onoff=0;
digitalWrite(12, LOW);
}
}
void loop()
{
if(A6GSM.available() >0)
{
inchar=A6GSM.read();
if (inchar=='R')
{
delay(10);
inchar=A6GSM.read();
if (inchar=='I')
{
delay(10);
inchar=A6GSM.read();
if (inchar=='N')
{
delay(10);
inchar=A6GSM.read();
if (inchar=='G')
{
delay(10);
numring++;
Serial.println("ring!");
if (numring==comring)
{
numring=0; // reset ring counter
doSomething();
}
}
}
}
}
}
}
180. POWER LOCK BY GSM

Pada proyek ini kita coba gabungkan beberapa module untuk membuat power lock untuk mobil.
Penerapan ini berguna saat mobil kita dirampok orang, maka kira serahkan saja mobil itu dan semua
penumpang dikeluarkan. Ketika mobil sudah dibawa kabur oleh si perampok, ketika jarak mobil
sudah aman (red: jika perampok kembali ke TKP kita sudah tidak berada di situ dan sudah lari ke
pos polisi terdekat atau minta pertolongan penduduk) , maka kita miss call ke nomer tang terpasang
pada module GSM, maka mobil akan mati secara otomatis. Ketika mobil mati karena kita miss call
maka tidak dapat dinyalakan lagi, untuk menyalakan lagi harus mamakai RFID.

const int ledPin = 5;//this signal go to relay or mosfet or for drive triac
#include <EEPROM.h>
int addr = 0;
byte value;

#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
//SoftwareSerial SIM900(7, 8);//RX,TX
const int pinRxNano = 7;
// Rx of A6 linked to pin 8
const int pinTxNano = 8;
const String phoneNumber= "+97433187702";
const String messageInit = "A6 ready";
SoftwareSerial A6GSM(pinRxNano, pinTxNano);
int numring=0;
int comring=1;
void Response(){
int a = 0;
Serial.println();
while(1){
if(A6GSM.available()){
String dataFromA6 =A6GSM.readString();
dataFromA6.trim();
Serial.println(dataFromA6);
a++;
if(dataFromA6.indexOf("OK")>0){break;}
}
if(a>500){a=0;break;}
delay(200);
}
}
void startAT(){
int nbAT = 0;
while(1){
if (nbAT==0){A6GSM.println("AT");Serial.print(".");}
if(A6GSM.available()){
String dataFromA6 =A6GSM.readString();
dataFromA6.trim();
Serial.println(dataFromA6);
if(dataFromA6.indexOf("OK")>0){break;}
}
delay(200);
nbAT++;
if(nbAT++>10){nbAT=0;}
}
}
void envoieSMS(String numeroEnvoi, String messageEnvoi) {
delay(200);
Serial.println("Selection format message SMS");
A6GSM.println("AT+CMGF=1");
Response();
delay(200);
Serial.println("Envoi message SMS");
A6GSM.print("AT+CMGS=\"");
A6GSM.print(numeroEnvoi);
A6GSM.println("\"");
delay(200);
A6GSM.print(messageEnvoi);
delay(200);
A6GSM.println (char(26));
Response();
}

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
MFRC522::MIFARE_Key key;

void setup() {
Serial.begin(9600);
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
//RFID.begin(9600);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
A6GSM.begin(9600);
Serial.begin(9600);
delay(200);
Serial.println("Init");
//AT
startAT();
//envoieSMS(phoneNumber,messageInit);
}
void(* resetFunc) (void) = 0;
void doSomething()
{
value = EEPROM.read(addr);
if (value==0)
{
digitalWrite(ledPin, HIGH);
delay(10000); //delay 10 minutes
EEPROM.write(addr, 1);
}
//resetFunc();
}
void loop(){
value = EEPROM.read(addr);
if(A6GSM.available() >0)
{
inchar=A6GSM.read();
if (inchar=='R')
{
delay(10);
inchar=A6GSM.read();
if (inchar=='I')
{
delay(10);
inchar=A6GSM.read();
if (inchar=='N')
{
delay(10);
inchar=A6GSM.read();
if (inchar=='G')
{
delay(10);
numring++;
Serial.println("ring!");
if (numring==comring)
{
numring=0; // reset ring counter
doSomething();
}
}
}
}
}
}

else {
value = EEPROM.read(addr);
if (value==1){
digitalWrite(ledPin, LOW);
}
Serial.println(value);
}
//===========================================================

if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("UID tag :");
String content= "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.print("Message : ");
content.toUpperCase();
//if ((content.substring(1) == "76 5C A8 BB") || (content.substring(1) == "A0 D1 39 83" ))
//change here the UID of the card/cards that you want to give access
if (content.substring(1) == "76 5C A8 BB")// single card
{
Serial.println("Authorized access");
EEPROM.write(addr, 0);
//Stored_Tag_ID="";
//Parsed_Tag_ID="";
resetFunc(); //call reset
}

}
181. FLAME DETECTOR WITH RF24

Transmitter
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int DataMsg[1];

RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;

void setup()
{
Serial.begin(9600);
Serial.println("NRF24L01 Transmitter");
radio.begin();
radio.openWritingPipe(pipe);
}

void loop()
{
int sensorValue0 = analogRead(A0);
if (sensorValue0 < 100)
{
DataMsg[0] = 1;
radio.write(DataMsg, 1);
}
else
{
DataMsg[0] = 2;
radio.write(DataMsg, 1);
}
}

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

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;
int Relay1 = 5;
void setup()
{
pinMode(Relay1, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}

void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
Serial.print("NRF24L01 Receiver: ");
Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#1

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#2

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#3

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#4

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#5

if (DataMgs[0] == 2)
{
digitalWrite(Relay1, LOW);

}
delay(100);
}
}
else
{
Serial.println("Waiting for signal...");
}
}

182. ALARM GEMPA BUMI ADXL355


Pada proyek ini memanfaatkan akselerometer ADXL355 sebagai sensor getaran. Ketika terdeteksi
getaran yang melewati ambang batas maka RF24 akan mengirim signal ke unit alarm (receiver).

Transmitter
const int groundpin = 18; // analog input pin 4 -- ground
const int powerpin = 19; // analog input pin 5 -- voltage
const int xpin = A3; // x-axis of the accelerometer
const int ypin = A2; // y-axis
const int zpin = A1;// z-axis (only on 3-axis models)
float cx=0;
float cy=0;
float cz=0;
float a;
float b;
float c;
float d;
float x;
float y;
float z;

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

int DataMsg[1];

RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;


void setup()
{
//pinMode(13, OUTPUT);
// initialize the serial communications:
Serial.begin(9600);
//=======================radio
radio.begin();
radio.openWritingPipe(pipe);

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

pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
delay(6000);
x=analogRead(xpin);
y=analogRead(ypin);
z=analogRead(zpin);
if ((x >= cx)||(x < cx)) {
cx = x;
}
if ((y >= cy)||(y < cy)) {
cy = y;
}
if ((z >= cz)||(z < cz)) {
cz = z;
}
delay(2000);
}

void loop()
{
a=analogRead(xpin)-cx;
b=analogRead(ypin)-cy;
c=analogRead(zpin)-cz;
d=sqrt(sq(a)+sq(b)+sq(c));

// print the sensor values:

if (d > 2.5){
DataMsg[0] = 1;
radio.write(DataMsg, 1);

//delay(2000);
}

else {
DataMsg[0] = 2;
radio.write(DataMsg, 1);
Serial.print(a);
// print a tab between values:
Serial.print("\t");
Serial.print(b);
// print a tab between values:
Serial.print("\t");
Serial.print(c);
Serial.print("\t");
Serial.print(d);
Serial.println();

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

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;
int Relay1 = 5;
void setup()
{
pinMode(Relay1, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}

void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
Serial.print("NRF24L01 Receiver: ");
Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#1

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#2

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#3

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#4

digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(30);
digitalWrite(Relay1, HIGH);
delay(30);
digitalWrite(Relay1, LOW);
delay(2000); //#5

if (DataMgs[0] == 2)
{
digitalWrite(Relay1, LOW);

}
delay(100);
}
}
else
{
Serial.println("Waiting for signal...");
}
}

183. IR DISTANCE SENSOR


int sensorpin = 0;
int val = 0;

void setup()
{
Serial.begin(9600);
}

void loop()
{
val = analogRead(sensorpin);
Serial.println(val);
delay(100);
}

184. STEPPER MOTOR WITH ULN2003


#include <AccelStepper.h>
#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);

void setup() {
stepper1.setMaxSpeed(1000.0);
stepper1.setAcceleration(1000.0);
stepper1.setSpeed(600);
}//--(end setup )---
void loop() {
stepper1.moveTo(-10000);
stepper1.run();
}

185. CONTINUES STEPPER MOTOR WITH ULN2003


#include <AccelStepper.h>
#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
void setup() {
stepper1.setMaxSpeed(10000.0);
stepper1.setAcceleration(1000.0);
stepper1.setSpeed(10000);
stepper1.moveTo(2000);

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

void loop() {

stepper1.moveTo(stepper1.currentPosition()+500);
stepper1.run();
}
=================Other sketch
#include <AccelStepper.h>
#define HALFSTEP 8

// Motor pin definitions


#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);

void setup() {
stepper1.setMaxSpeed(1000);
stepper1.setSpeed(800);

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

void loop() {

stepper1.runSpeed();
}

186. CONTINUES TWO STEPPER MOTOR WITH ULN2003


#include <AccelStepper.h>
#define HALFSTEP 8

// Motor pin definitions


#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1
#define motorPin5 8 // IN1 on the ULN2003 driver 2
#define motorPin6 7 // IN2 on the ULN2003 driver 2
#define motorPin7 6 // IN3 on the ULN2003 driver 2
#define motorPin8 5 // IN4 on the ULN2003 driver 2

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(HALFSTEP, motorPin5, motorPin7, motorPin6, motorPin8);
void setup() {
stepper1.setMaxSpeed(1000.0);
stepper1.setAcceleration(1000.0);
stepper1.setSpeed(1000);
stepper2.setMaxSpeed(1000.0);
stepper2.setAcceleration(1000.0);
stepper2.setSpeed(1000);

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

void loop() {
stepper1.moveTo(stepper1.currentPosition()+500);
stepper2.moveTo(stepper2.currentPosition()-500);
stepper1.run();
stepper2.run();
}

187. TWO STEPPER MOTOR COTROLLED BY IR DISTANCE


#include <AccelStepper.h>
#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

#define motorPin5 8 // IN1 on the ULN2003 driver 2


#define motorPin6 7 // IN2 on the ULN2003 driver 2
#define motorPin7 6 // IN3 on the ULN2003 driver 2
#define motorPin8 5 // IN4 on the ULN2003 driver 2

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(HALFSTEP, motorPin5, motorPin7, motorPin6, motorPin8);
int sensorpin = 0;
int val = 0;
void setup() {
Serial.begin(9600);
stepper1.setMaxSpeed(1000.0);
stepper1.setAcceleration(10000.0);
stepper1.setSpeed(1000);
stepper2.setMaxSpeed(1000.0);
stepper2.setAcceleration(10000.0);
stepper2.setSpeed(1000);
}//--(end setup )---
void loop() {
val = analogRead(sensorpin);
//Serial.println(val);
if (val > 400) {
right();
}
else {
forward();
}
}

void forward(){
stepper1.moveTo(stepper1.currentPosition()+500);
stepper2.moveTo(stepper2.currentPosition()-500);
stepper1.run();
stepper2.run();
}
void right(){

stepper1.moveTo(stepper1.currentPosition()+500);
stepper2.moveTo(stepper2.currentPosition()+500);
stepper1.run();
stepper2.run();

}
188. PROPORTIONAL CONTROL STEPPER BY IR DISTANCE
#include <AccelStepper.h>

#define HALFSTEP 8

// Motor pin definitions


#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
#define ANALOG_IN A0

void setup()
{
stepper.setMaxSpeed(1000);
}

void loop()
{
// Read new position
int analog_in = analogRead(ANALOG_IN);
stepper.moveTo(analog_in*5);
stepper.setSpeed(2000);
stepper.runSpeedToPosition();
}

189. CONTROL STEPPER BY ROTARY ENCODER


#include <AccelStepper.h>

const unsigned char ttable[7][4] = {


{0x0, 0x2, 0x4, 0x0}, {0x3, 0x0, 0x1, 0x10},
{0x3, 0x2, 0x0, 0x0}, {0x3, 0x2, 0x1, 0x0},
{0x6, 0x0, 0x4, 0x0}, {0x6, 0x5, 0x0, 0x20},
{0x6, 0x5, 0x4, 0x0},
};

#define DT 2
#define CLK 3
#define SW 4
#define DIR_CCW 0x10
#define DIR_CW 0x20

#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);

volatile unsigned char state = 0;

void setup(){
stepper.setMaxSpeed(1000.0);
stepper.setAcceleration(10000.0);
stepper.setSpeed(1000);
Serial.begin(9600);
pinMode(DT, INPUT);
pinMode(CLK, INPUT);
pinMode(SW, INPUT);
digitalWrite(SW, HIGH);
}

void loop(){
int counter;
unsigned char result;
/* Reset the counter */
counter = 0;

while(1)
{
/* Read the status of the dial */
unsigned char pinstate = (digitalRead(CLK) << 1) | digitalRead(DT);
state = ttable[state & 0xf][pinstate];
result=state&0x30;
if(result==DIR_CCW) counter++;
if(result==DIR_CW) counter--;
// put some magnification here about 100 times
stepper.moveTo(counter*100);
stepper.run();
}
}

190. CONTROL STEPPER BY SERIAL


// Arduino stepper motor control code
#include <Stepper.h> // Include the header file
// change this to the number of steps on your motor
#define STEPS 32 // 2048 for 1 roration
// create an instance of the stepper class using the steps and pins
Stepper stepper(STEPS, 12, 10, 11, 9); //1-3-2-4
int val = 0;
void setup() {
Serial.begin(9600);
stepper.setSpeed(600);
}
void loop() {
if (Serial.available()>0)
{
val = Serial.parseInt();
stepper.step(val);
Serial.println(val); //for debugging
}

191. CONTROL STEPPER IR REMOTE


#include "Stepper.h"
#include "IRremote.h"
#define STEPS 32 // Number of steps per revolution of Internal shaft
int Steps2Take; // 2048 = 1 Revolution
int receiver = 3; // Signal Pin of IR receiver to Arduino Digital Pin 6

// In1, In2, In3, In4 in the sequence 1-3-2-4


Stepper small_stepper(STEPS, 12, 10, 11, 9);
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
void setup()
{
irrecv.enableIRIn(); // Start the receiver
}
void loop()
{
if (irrecv.decode(&results)) // have we received an IR signal?

{
switch(results.value)
{
case 0x20F0E01F: // RIGHT button pressed
small_stepper.setSpeed(500); //Max seems to be 700
Steps2Take = 2048; // Rotate CW 360 deg
small_stepper.step(Steps2Take);
break;

case 0x20F0609F: // LEFT button pressed


small_stepper.setSpeed(500);
Steps2Take = -1024; // Rotate CCW 180 deg
small_stepper.step(Steps2Take);
break;
}
irrecv.resume(); // receive the next value
}
}

192. STEPPER ROTATION SQUENCE


#include <AccelStepper.h>
#define HALFSTEP 8

// Motor pin definitions


#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);

void setup()
{
stepper.setMaxSpeed(1000);
stepper.setAcceleration(10000);
stepper.moveTo(0);
delay(2000);

void loop()
{
stepper.runToNewPosition(0);
delay(2000);
stepper.runToNewPosition(-4096); // 360 deg
stepper.stop();
delay(1000);
stepper.runToNewPosition(2048);
stepper.stop();
delay(2000);
stepper.runToNewPosition(0);
delay(2000);
stepper.runToNewPosition(8192);
stepper.stop();
delay(3000);
}

193. LIGHTNING COUNTER WITH 595 LED DISPLAY


#include "Four7Seg74hc595.h"

esl::Four7Seg74hc595 display( 5,6,7 ); // SCLK, RCL, DIO pins, respectively

int reading;
int lm35Pin = 1;
char sbuf[5];
uint16_t count;
uint32_t ts1, ts2;
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to

// Variables will change:


int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
for (uint8_t i=0; i < 100; i++) {
display.setDigits( "----", 4 );
display.update();
delay(10);
}
delay(1000);
count = 0;
sprintf( sbuf, "%04u",count);
display.setDigits( sbuf, 4 );
display.update();
ts1 = ts2 = millis();
}

uint32_t ts;
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == LOW) {
buttonPushCounter++;

} else {
}
// Delay a little bit to avoid bouncing
delay(1);
}
lastButtonState = buttonState;
//Serial.print("number of lightning: ");
//Serial.println(buttonPushCounter);
ts = millis();
if ( ts - ts1 >= 10 ) {
sprintf( sbuf, "%04u", buttonPushCounter );
ts1 += 10;
}
display.setDigits( sbuf, 4 );
display.update();
}

194. PUSH BUTTON COUNTER WITH 595 LED DISPLAY


#include "Four7Seg74hc595.h"
esl::Four7Seg74hc595 display( 5,6,7 ); // SCLK, RCL, DIO pins, respectively
int reading;
int lm35Pin = 1;
char sbuf[5];
uint16_t count;
uint32_t ts1, ts2;

// this constant won't change:


const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
for (uint8_t i=0; i < 100; i++) {
display.setDigits( "----", 4 );
display.update();
delay(10);
}
delay(1000);
count = 0;
sprintf( sbuf, "%04u", count );
display.setDigits( sbuf, 4 );
display.update();
ts1 = ts2 = millis();
}

uint32_t ts;
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

if (buttonState != lastButtonState) {

if (buttonState == HIGH) {

buttonPushCounter++;
//Serial.println("on");

} else {

}
// Delay a little bit to avoid bouncing
delay(1);
}

lastButtonState = buttonState;
//Serial.print("number of lightning: ");
//Serial.println(buttonPushCounter);
ts = millis();
if ( ts - ts1 >= 10 ) {
sprintf( sbuf, "%04u", buttonPushCounter );

ts1 += 10; // increment counter by 1 every 1sec


}
display.setDigits( sbuf, 4 );
display.update();
}

195. CONTROL STEPPER BY POTENSIOMETER


#include <AccelStepper.h>
const int analogPin = A0;
#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1

// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
void setup() {
stepper1.setMaxSpeed(1000);
stepper1.setAcceleration(10000);
stepper1.runToNewPosition(4096);//move 360 deg
delay(5000);

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

void loop() {
int analogValue = analogRead(analogPin);
stepper1.runToNewPosition(analogValue*4.17);

196. LIGHT SOURCE FOLLOWER


#include <AccelStepper.h>
#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1
int d;
// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
void setup() {
stepper1.setMaxSpeed(200);
stepper1.setAcceleration(10000);
stepper1.runToNewPosition(0);
delay(3000);

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

void loop() {
int sensorValue0 = analogRead(A0);
int sensorValue1 = analogRead(A1);
d=sensorValue0-sensorValue1;

if (d > 15) {
stepper1.moveTo(stepper1.currentPosition()+1);
stepper1.run();
}
if (d < -15) {
stepper1.moveTo(stepper1.currentPosition()-1);
stepper1.run();
}
if ((d <= 15)&&(d >= -15)) {
stepper1.stop();
}
if ((sensorValue0 <= 50 )&&(sensorValue0 <= 50 )) {
stepper1.runToNewPosition(0);

}
}

197. SOLAR PANEL ALIGNMENT


/*
This demonstrate solar panel alignment, the program make solar panel always face the solar
direction.
By press the button SET together with button UP or button DOWN we adjust to get 0 deg position,
then with
still press button SET and press the reset button the 0 deg position will got.
*/

#include <AccelStepper.h>
#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 12 // IN1 on the ULN2003 driver 1
#define motorPin2 11 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 9 // IN4 on the ULN2003 driver 1
int d;
const int buttonSet = 2;
const int buttonUp = 3;
const int buttonDown = 4;
int buttonSetState = 0;
int buttonUpState = 0;
int buttonDownState = 0;
// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
void setup() {
pinMode(buttonSet, INPUT);
pinMode(buttonUp, INPUT);
pinMode(buttonDown, INPUT);
stepper1.setMaxSpeed(200);
stepper1.setAcceleration(10000);
stepper1.runToNewPosition(0);
delay(3000);

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

void loop() {
buttonSetState = digitalRead(buttonSet);
buttonUpState = digitalRead(buttonUp);
buttonDownState = digitalRead(buttonDown);
int sensorValue0 = analogRead(A0);
int sensorValue1 = analogRead(A1);
d=sensorValue0-sensorValue1;
if (buttonSetState == LOW) {
//+++++++++++++++++++++++++++++++++++++++++++++++++
if (d > 15) {
stepper1.moveTo(stepper1.currentPosition()+1);
stepper1.run();
}
if (d < -15) {
stepper1.moveTo(stepper1.currentPosition()-1);
stepper1.run();
}
if ((d <= 15)&&(d >= -15)) {
stepper1.stop();
}
if ((sensorValue0 <= 50 )&&(sensorValue0 <= 50 )) {
stepper1.runToNewPosition(0);

//+++++++++++++++++++++++++++++++++++++++++++++++++
}

//===============================
if (buttonSetState == HIGH) {
//-----------------------------
if (buttonUpState == HIGH) {
stepper1.moveTo(stepper1.currentPosition()+500);
stepper1.run();
}
//---------------------------------
if (buttonDownState == HIGH) {
stepper1.moveTo(stepper1.currentPosition()-500);
stepper1.run();
}
//---------------------------------------
if ((buttonDownState == LOW)&&(buttonUpState == LOW)) {
stepper1.stop();
}
//------------------------------------------------
}
//==============================================
}

198. TOUCHLESS LAMP SWITCH


Transmitter

//this device utilise IR proximity sensor module for trigger switching


#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int DataMsg[1];

RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F483LL;

void setup()
{
Serial.begin(9600);
Serial.println("NRF24L01 Transmitter");
radio.begin();
radio.openWritingPipe(pipe);
}

void loop()
{
int sensorValue0 = analogRead(A1);
if (sensorValue0 < 100)
{
DataMsg[0] = 1;
radio.write(DataMsg, 1);
}
else
{
DataMsg[0] = 2;
radio.write(DataMsg, 1);
}
}

Receiver
Sket 1 : without memory

//This sket mean light status will reset to ON or OFF when power arduino be reset.
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F483LL;
int led = 3;
void setup()
{
pinMode(led, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}
int on = 0;
unsigned long last = millis();
void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
//Serial.print("NRF24L01 Receiver: ");
//Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{

if (millis() - last > 250) {


on = !on;
digitalWrite(led, on ? HIGH : LOW);
}
last = millis();

if (DataMgs[0] == 2)
{

}
//delay(100);
}
}
else
{
//Serial.println("Waiting for signal...");
}
}

---------------------------------------------

Sket 2 : with memory

//This sket mean light status will follow the last status of light when arduino be reset
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include <EEPROM.h>
int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F483LL;
int led = 3;
byte laju;
void setup()
{
pinMode(led, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
}
int on = 0;
unsigned long last = millis();
void loop()
{
if (radio.available())
{
bool done = false;
while (!done)
{
done = radio.read(DataMgs, 1);
//Serial.print("NRF24L01 Receiver: ");
//Serial.println(DataMgs[0]);

if (DataMgs[0] == 1)
{

if (millis() - last > 250) {


on = !on;
//digitalWrite(led, on ? HIGH : LOW);
EEPROM.write(1, on ? 1 : 0);
}
last = millis();

if (DataMgs[0] == 2)
{
//------------------------------
laju = EEPROM.read(1);

if (laju==1){
digitalWrite(led, HIGH);
}

if (laju==0){
digitalWrite(led, LOW);
}
//-------------------------------
}
//delay(100);
}
}
else
{

//-----------------------------------

laju = EEPROM.read(1);

if (laju==1){
digitalWrite(led, HIGH);
}

if (laju==0){
digitalWrite(led, LOW);
}

//----------------------------------

//Serial.println("Waiting for signal...");


}
}

199. VIBRATION SENSOR SW 420


int led = 3;
// the setup routine runs once when you press reset:
void setup() {
pinMode(led, OUTPUT);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
if(sensorValue >10){
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(5000);
}
else{
Serial.println(sensorValue);
digitalWrite(led, LOW);
delay(1); // delay in between reads for stability
}
}

200. KNOCK SWITCH WITH SENSOR SW 420


int led = 3;
// the setup routine runs once when you press reset:
void setup() {
pinMode(led, OUTPUT);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
int on = 0;
unsigned long last = millis();
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1);
if (sensorValue >10) {
// If it's been at least 1/4 second since the last
// IR received, toggle the relay
if (millis() - last > 250) {
on = !on;
digitalWrite(led, on ? HIGH : LOW);
}
last = millis();
}
}

201. SPEED RADIAN WITH HALL SENSOR


const int hallPin = 2; // the number of the hall effect sensor pin
int hallState = 0; // variable for reading the hall sensorstatus
int lasthallState = 0;
int pulses;
unsigned long timeold;
int laju;
int turn;
void setup() {
Serial.begin(9600);
pinMode(hallPin, INPUT);
attachInterrupt(0, counter, FALLING);
pulses = 0;
timeold = 0;
}

void loop(){
// read the state of the hall effect sensor:
hallState = digitalRead(hallPin);

counter();
if (millis() - timeold >= 100) {
detachInterrupt(0);
laju=(pulses)*235.5; //number pulses in 100ms with 16 spots magnet
turn=(pulses)*0.625;
Serial.print(pulses);
Serial.print(" pulses/100ms ");
Serial.print(laju);
Serial.print(" rpm");
Serial.print(" ");
Serial.print(turn);
Serial.println(" turn/second");
timeold = millis();
pulses = 0;
attachInterrupt(0, counter, FALLING);

}
}
void counter()
{
hallState = digitalRead(hallPin);
if (hallState != lasthallState) {
if (hallState == LOW) {
pulses++;
}
lasthallState = hallState;
}

202. ANALOG READ WITH 595 LED DISPLAY


#include "Four7Seg74hc595.h"

esl::Four7Seg74hc595 display( 5,6,7 ); // SCLK, RCL, DIO pins, respectively


char sbuf[5];
uint16_t count;
uint32_t ts1, ts2;

void setup() {
Serial.begin(9600);
for (uint8_t i=0; i < 100; i++) {
display.setDigits( "----", 4 );
display.update();
delay(10);
}
delay(1000);
count = 0;
sprintf( sbuf, "%04u", count );
display.setDigits( sbuf, 4 );
display.update();
ts1 = ts2 = millis();
}

uint32_t ts;

void loop() {
int sensorValue = analogRead(A0);
ts = millis();
if ( ts - ts1 >= 1000 ) {
sprintf( sbuf, "%04u", sensorValue );

ts1 += 1000; // increment counter by 1 every 1sec


}
display.setDigits( sbuf, 4 );
display.update();
}

203. LAMP TIMER WITH RTC


#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
int led1 = 5;
void setup () {
pinMode(led1, OUTPUT);
Serial.begin(9600);
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
}
void loop () {
DateTime now = RTC.now();

Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
if(now.hour() >= 19 || now.hour() < 7){
digitalWrite(led1, HIGH);
}
if(now.hour() >= 7 && now.hour() < 19){
digitalWrite(led1,LOW);
}

204. VIBRATION DETECTOR ADXL355


const int groundpin = 18; // analog input pin 4 -- ground
const int powerpin = 19; // analog input pin 5 -- voltage
const int xpin = A3; // x-axis of the accelerometer
const int ypin = A2; // y-axis
const int zpin = A1;// z-axis (only on 3-axis models)
float cx=0;
float cy=0;
float cz=0;
float a;
float b;
float c;
float d;
float x;
float y;
float z;
void setup()
{
pinMode(13, OUTPUT);
// initialize the serial communications:
Serial.begin(9600);
pinMode(groundpin, OUTPUT);
pinMode(powerpin, OUTPUT);
digitalWrite(groundpin, LOW);
digitalWrite(powerpin, HIGH);
delay(6000);
x=analogRead(xpin);
y=analogRead(ypin);
z=analogRead(zpin);
if ((x >= cx)||(x < cx)) {
cx = x;
}
if ((y >= cy)||(y < cy)) {
cy = y;
}
if ((z >= cz)||(z < cz)) {
cz = z;
}
delay(2000);
}
void loop()
{
a=analogRead(xpin)-cx;
b=analogRead(ypin)-cy;
c=analogRead(zpin)-cz;
d=sqrt(sq(a)+sq(b)+sq(c));

// print the sensor values:

if (d > 2.5){
digitalWrite(13, HIGH);

delay(2000);
}

else {
Serial.print(a);
// print a tab between values:
Serial.print("\t");
Serial.print(b);
// print a tab between values:
Serial.print("\t");
Serial.print(c);
Serial.print("\t");
Serial.print(d);
Serial.println();
digitalWrite(13, LOW);
}
}
205. DIGITAL CLOCK
#include <Wire.h>
#include "TM1637.h"
#define CLK 6
#define DIO 7
#define brightness 6
#define keyHor 5
#define keyMin 4
#define keyPL 3

TM1637 tm1637(CLK,DIO);
#define DS3231_I2C_ADDRESS 0x68

volatile boolean flag;

byte decToBcd(byte val){


return ( (val/10*16) + (val%10) );
}

byte bcdToDec(byte val){


return ( (val/16*10) + (val%16) );
}

void setDateDs3231(byte second,


byte minute, // 0-59
byte hour, // 1-23
byte dayOfWeek, // 1-7
byte dayOfMonth, // 1-28/29/30/31
byte month, // 1-12
byte year) // 0-99
{
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0);
Wire.write(decToBcd(second));
Wire.write(decToBcd(minute));
Wire.write(decToBcd(hour));
Wire.write(decToBcd(dayOfWeek));
Wire.write(decToBcd(dayOfMonth));
Wire.write(decToBcd(month));
Wire.write(decToBcd(year));
Wire.endTransmission();
}

void getDateDs3231(byte *second,


byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{

Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0);
Wire.endTransmission();

Wire.requestFrom(DS3231_I2C_ADDRESS, 7);

*second = bcdToDec(Wire.read() & 0x7f);


*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}

void setINT(){
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0x0E);
Wire.write(0x0);
Wire.endTransmission();
}

void blink() {
digitalWrite(13, !digitalRead(13));
flag = !flag;
tm1637.point(flag);
}
boolean alterna;
void setup() {
// Serial.begin(9600);
Wire.begin();
pinMode(13, OUTPUT);
pinMode(keyHor, INPUT_PULLUP);
pinMode(keyMin, INPUT_PULLUP);
pinMode(keyPL, INPUT_PULLUP);

tm1637.init();
tm1637.set(brightness);

setINT();
attachInterrupt(0, blink, CHANGE);
}

void loop(){

byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;


getDateDs3231(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
int8_t TimeDisp[4];

TimeDisp[0] = hour / 10;


TimeDisp[1] = hour % 10;
TimeDisp[2] = minute / 10;
TimeDisp[3] = minute % 10;

if (!digitalRead(keyHor) && !digitalRead(keyPL)){


second = 0;
hour++;
if (hour > 23) hour = 0;
setDateDs3231(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
delay(200);
}
if (!digitalRead(keyMin) && !digitalRead(keyPL)){ // минуты
second = 0;
minute++;
if (minute > 59) minute = 0;
setDateDs3231(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
delay(200);
}

tm1637.display(TimeDisp);

//tm1637.point(POINT_ON); //Like blink example.


if (alterna)
{
tm1637.point(POINT_OFF);
alterna = false;
}
else
{
tm1637.point(POINT_ON);
alterna = true;
}

delay(500);

206. STAIR LIGHT


sensor 1

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

int DataMgs[1];
RF24 radio(8,7);
const uint64_t pipe = 0xE14BC8F482LL;

#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 RTC;
#include <SoftPWM.h>

int pirPin = 4;
int statePir = 0;
/*
const int RED_PIN = 3;
const int GREEN_PIN = 5;
const int BLUE_PIN = 6;

int DISPLAY_TIME = 50; // In milliseconds


*/
void setup()
{
SoftPWMBegin();
SoftPWMSet(3, 0);
//SoftPWMSet(5, 0);
//SoftPWMSet(6, 0);
SoftPWMSetFadeTime(3, 3000, 2000);
//SoftPWMSetFadeTime(5, 3000, 2000);
//SoftPWMSetFadeTime(6, 3000, 2000);
Serial.begin(9600);
Wire.begin();
RTC.begin();
if (! RTC.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
pinMode(pirPin,INPUT);
/*
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
*/
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
//showSpectrum();
gelap();
}

void loop()
{
action();
}
/*
void showSpectrum()
{
int x; // define an integer variable called "x"

for (x = 0; x < 768; x++)


{
showRGB(x); // Call RGBspectrum() with our new x
delay(DISPLAY_TIME); // Delay for 10 ms (1/100th of a second)
}
}

void showRGB(int color)


{
int redIntensity;
int greenIntensity;
int blueIntensity;

if (color <= 255) // zone 1


{
redIntensity = 255 - color; // red goes from on to off
greenIntensity = color; // green goes from off to on
blueIntensity = 0; // blue is always off
}
else if (color <= 511) // zone 2
{
redIntensity = 0; // red is always off
greenIntensity = 255 - (color - 256); // green on to off
blueIntensity = (color - 256); // blue off to on
}
else // color >= 512 // zone 3
{
redIntensity = (color - 512); // red off to on
greenIntensity = 0; // green is always off
blueIntensity = 255 - (color - 512); // blue on to off
}

analogWrite(RED_PIN, redIntensity);
analogWrite(BLUE_PIN, blueIntensity);
analogWrite(GREEN_PIN, greenIntensity);
}
*/
void gelap(){
SoftPWMSet(3, 0);
//SoftPWMSet(5, 0);
//SoftPWMSet(6, 0);
//delay(4000);
}
void white(){
SoftPWMSet(3, 255);
//SoftPWMSet(5, 255);
//SoftPWMSet(6, 255);
//delay(4000);

}
void action(){
//statePir = digitalRead(pirPin);
if (radio.available())
{
//statePir = digitalRead(pirPin);
bool done = false;
while (!done)
{
DateTime now = RTC.now();
statePir = digitalRead(pirPin);
done = radio.read(DataMgs, 1);

if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 17)||(now.hour() <


6))&&(now.month()==1)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 17)||(now.hour() <
6))&&(now.month()==2)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 17)||(now.hour() <
6))&&(now.month()==3)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 18)||(now.hour() <
5))&&(now.month()==4)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 18)||(now.hour() <
5))&&(now.month()==5)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 18)||(now.hour() <
5))&&(now.month()==6)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 18)||(now.hour() <
5))&&(now.month()==7)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 18)||(now.hour() <
5))&&(now.month()==8)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 17)||(now.hour() <
6))&&(now.month()==9)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 17)||(now.hour() <
6))&&(now.month()==10)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 17)||(now.hour() <
6))&&(now.month()==11)))
{
white();
delay(20000);
}
if (((DataMgs[0] == 1)||(statePir == HIGH))&&(((now.hour() >= 17)||(now.hour() <
6))&&(now.month()==12)))
{
white();
delay(20000);
}

else
{
gelap();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();

}
delay(100);
}
}
else{
DateTime now = RTC.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
}

sensor 2
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int pirPin = 2;
int statePir = 0;
int DataMsg[1];
RF24 radio(8,7);

const uint64_t pipe = 0xE14BC8F482LL;

void setup()
{
pinMode(pirPin,INPUT);
Serial.begin(9600);
Serial.println("NRF24L01 Transmitter");
radio.begin();
radio.openWritingPipe(pipe);
}

void loop()
{
statePir = digitalRead(pirPin);
if (statePir == HIGH)
{
DataMsg[0] = 1;
radio.write(DataMsg, 1);
}
if (statePir == LOW)
{
DataMsg[0] = 2;
radio.write(DataMsg, 1);
}
}

207. DIGITAL CLOCK LED MATRIX


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

Mini Clock v1.0, Jul 2014 by Nick Hall


Distributed under the terms of the GPL.

For help on how to build the clock see my blog:


http://123led.wordpress.com/

Tested on IDE v1.6.5

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

//include libraries:
#include "LedControl.h"
#include <FontLEDClock.h> // Font library
#include <Wire.h> // DS1307 clock
#include "RTClib.h" // DS1307 clock
#include <Button.h> // Button library by Alexander Brevig

// Setup LED Matrix

// pin 12 is connected to the DataIn on the display


// pin 11 is connected to the CLK on the display
// pin 10 is connected to LOAD on the display
LedControl lc = LedControl(12, 11, 10, 4); //sets the 3 pins as 12, 11 & 10 and then sets 4 displays
(max is 8 displays)

//global variables
byte intensity = 5; // Default intensity/brightness (0-15)
byte clock_mode = 0; // Default clock mode. Default = 0 (basic_mode)
bool random_mode = 0; // Define random mode - changes the display type every few
hours. Default = 0 (off)
byte old_mode = clock_mode; // Stores the previous clock mode, so if we go to date or
whatever, we know what mode to go back to after.
bool ampm = 0; // Define 12 or 24 hour time. 0 = 24 hour. 1 = 12 hour
byte change_mode_time = 0; // Holds hour when clock mode will next change if in random
mode.
unsigned long delaytime = 500; // We always wait a bit between updates of the display
int rtc[7]; // Holds real time clock output

char days[7][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
}; //day array - used in slide, basic_mode and jumble modes (The DS1307 outputs 1-7 values for
day of week)
char daysfull[7][9] = {
"Sunday", "Monday", "Tuesday", "Wed", "Thursday", "Friday", "Saturday"
};
char suffix[4][3] = {
"st", "nd", "rd", "th"
}; //date suffix array, used in slide, basic_mode and jumble modes. e,g, 1st 2nd ...

//define constants
#define NUM_DISPLAY_MODES 3 // Number display modes (conting zero as the first
mode)
#define NUM_SETTINGS_MODES 4 // Number settings modes = 6 (conting zero as the
first mode)
#define SLIDE_DELAY 20 // The time in milliseconds for the slide effect per character
in slide mode. Make this higher for a slower effect
#define cls clear_display // Clear display

RTC_DS1307 ds1307; // Create RTC object

Button buttonA = Button(2, BUTTON_PULLUP); // Setup button A (using button library)


Button buttonB = Button(3, BUTTON_PULLUP); // Setup button B (using button library)

void setup() {

digitalWrite(2, HIGH); // turn on pullup resistor for button on pin 2


digitalWrite(3, HIGH); // turn on pullup resistor for button on pin 3
digitalWrite(4, HIGH); // turn on pullup resistor for button on pin 4

Serial.begin(9600); //start serial

//initialize the 4 matrix panels


//we have already set the number of devices when we created the LedControl
int devices = lc.getDeviceCount();
//we have to init all devices in a loop
for (int address = 0; address < devices; address++) {
/*The MAX72XX is in power-saving mode on startup*/
lc.shutdown(address, false);
/* Set the brightness to a medium values */
lc.setIntensity(address, intensity);
/* and clear the display */
lc.clearDisplay(address);
}

//Setup DS1307 RTC


#ifdef AVR
Wire.begin();
#else
Wire1.begin(); // Shield I2C pins connect to alt I2C bus on Arduino
#endif
ds1307.begin(); //start RTC Clock

if (! ds1307.isrunning()) {
Serial.println("RTC is NOT running!");
ds1307.adjust(DateTime(__DATE__, __TIME__)); // sets the RTC to the date & time this sketch
was compiled
}
//Show software version & hello message
//printver();

//enable red led


//digitalWrite(13, HIGH);
}

void loop() {

//run the clock with whatever mode is set by clock_mode - the default is set at top of code.
switch (clock_mode){

case 0:
basic_mode();
break;
case 1:
small_mode();
break;
case 2:
slide();
break;
case 3:
word_clock();
break;
case 4:
setup_menu();
break;
}
}

//plot a point on the display


void plot (byte x, byte y, byte val) {

//select which matrix depending on the x coord


byte address;
if (x >= 0 && x <= 7) {
address = 3;
}
if (x >= 8 && x <= 15) {
address = 2;
x = x - 8;
}
if (x >= 16 && x <= 23) {
address = 1;
x = x - 16;
}
if (x >= 24 && x <= 31) {
address = 0;
x = x - 24;
}

if (val == 1) {
lc.setLed(address, y, x, true);
} else {
lc.setLed(address, y, x, false);
}
}

//clear screen
void clear_display() {
for (byte address = 0; address < 4; address++) {
lc.clearDisplay(address);
}
}

//fade screen down


void fade_down() {

//fade from global intensity to 1


for (byte i = intensity; i > 0; i--) {
for (byte address = 0; address < 4; address++) {
lc.setIntensity(address, i);
}
delay(30); //change this to change fade down speed
}

clear_display(); //clear display completely (off)

//reset intentsity to global val


for (byte address = 0; address < 4; address++) {
lc.setIntensity(address, intensity);
}
}

//power up led test & display software version number


void printver() {

byte i = 0;
char ver_a[9] = "Vers 1.0";
char ver_b[9] = " Hello! ";

//test all leds.


for (byte x = 0; x <= 31; x++) {
for (byte y = 0; y <= 7; y++) {
plot(x, y, 1);
}
}
delay(500);
fade_down();

while (ver_a[i]) {
puttinychar((i * 4), 1, ver_a[i]);
delay(35);
i++;
}
delay(700);
fade_down();
i = 0;
while (ver_b[i]) {
puttinychar((i * 4), 1, ver_b[i]);
delay(35);
i++;
}
delay(700);
fade_down();
}

// puttinychar
// Copy a 3x5 character glyph from the myfont data structure to display memory, with its upper left
at the given coordinate
// This is unoptimized and simply uses plot() to draw each dot.
void puttinychar(byte x, byte y, char c)
{
byte dots;
if (c >= 'A' && c <= 'Z' || (c >= 'a' && c <= 'z') ) {
c &= 0x1F; // A-Z maps to 1-26
}
else if (c >= '0' && c <= '9') {
c = (c - '0') + 32;
}
else if (c == ' ') {
c = 0; // space
}
else if (c == '.') {
c = 27; // full stop
}
else if (c == ':') {
c = 28; // colon
}
else if (c == '\'') {
c = 29; // single quote mark
}
else if (c == '!') {
c = 30; // single quote mark
}
else if (c == '?') {
c = 31; // single quote mark
}

for (byte col = 0; col < 3; col++) {


dots = pgm_read_byte_near(&mytinyfont[c][col]);
for (char row = 0; row < 5; row++) {
if (dots & (16 >> row))
plot(x + col, y + row, 1);
else
plot(x + col, y + row, 0);
}
}
}

void putnormalchar(byte x, byte y, char c)


{

byte dots;
// if (c >= 'A' && c <= 'Z' || (c >= 'a' && c <= 'z') ) {
// c &= 0x1F; // A-Z maps to 1-26
// }
if (c >= 'A' && c <= 'Z' ) {
c &= 0x1F; // A-Z maps to 1-26
}
else if (c >= 'a' && c <= 'z') {
c = (c - 'a') + 41; // A-Z maps to 41-67
}
else if (c >= '0' && c <= '9') {
c = (c - '0') + 31;
}
else if (c == ' ') {
c = 0; // space
}
else if (c == '.') {
c = 27; // full stop
}
else if (c == '\'') {
c = 28; // single quote mark
}
else if (c == ':') {
c = 29; // clock_mode selector arrow
}
else if (c == '>') {
c = 30; // clock_mode selector arrow
}
else if (c >= -80 && c <= -67) {
c *= -1;
}

for (char col = 0; col < 5; col++) {


dots = pgm_read_byte_near(&myfont[c][col]);
for (char row = 0; row < 7; row++) {
//check coords are on screen before trying to plot
//if ((x >= 0) && (x <= 31) && (y >= 0) && (y <= 7)){

if (dots & (64 >> row)) { // only 7 rows.


plot(x + col, y + row, 1);
} else {
plot(x + col, y + row, 0);
}
//}
}
}
}

//small_mode
//show the time in small 3x5 characters with seconds display

void small_mode() {

char textchar[8]; // the 16 characters on the display


byte mins = 100; //mins
byte secs = rtc[0]; //seconds
byte old_secs = secs; //holds old seconds value - from last time seconds were updated o display -
used to check if seconds have changed

cls();

//run clock main loop as long as run_mode returns true


while (run_mode()) {

get_time();

//check for button press


if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
return;
}

//if secs changed then update them on the display


secs = rtc[0];
if (secs != old_secs) {

//secs
char buffer[3];
itoa(secs, buffer, 10);

//fix - as otherwise if num has leading zero, e.g. "03" secs, itoa coverts this to chars with space
"3 ".
if (secs < 10) {
buffer[1] = buffer[0];
buffer[0] = '0';
}

puttinychar( 20, 1, ':'); //seconds colon


puttinychar( 24, 1, buffer[0]); //seconds
puttinychar( 28, 1, buffer[1]); //seconds
old_secs = secs;
}

//if minute changes change time


if (mins != rtc[1]) {

//reset these for comparison next time


mins = rtc[1];
byte hours = rtc[2];
if (hours > 12) {
hours = hours - ampm * 12;
}
if (hours < 1) {
hours = hours + ampm * 12;
}

//byte dow = rtc[3]; // the DS1307 outputs 0 - 6 where 0 = Sunday0 - 6 where 0 = Sunday.
//byte date = rtc[4];

//set characters
char buffer[3];
itoa(hours, buffer, 10);

//fix - as otherwise if num has leading zero, e.g. "03" hours, itoa coverts this to chars with space
"3 ".
if (hours < 10) {
buffer[1] = buffer[0];
//if we are in 12 hour mode blank the leading zero.
if (ampm) {
buffer[0] = ' ';
}
else {
buffer[0] = '0';
}
}
//set hours chars
textchar[0] = buffer[0];
textchar[1] = buffer[1];
textchar[2] = ':';

itoa (mins, buffer, 10);


if (mins < 10) {
buffer[1] = buffer[0];
buffer[0] = '0';
}
//set mins characters
textchar[3] = buffer[0];
textchar[4] = buffer[1];

//do seconds
textchar[5] = ':';
buffer[3];
secs = rtc[0];
itoa(secs, buffer, 10);

//fix - as otherwise if num has leading zero, e.g. "03" secs, itoa coverts this to chars with space
"3 ".
if (secs < 10) {
buffer[1] = buffer[0];
buffer[0] = '0';
}
//set seconds
textchar[6] = buffer[0];
textchar[7] = buffer[1];

byte x = 0;
byte y = 0;

//print each char


for (byte x = 0; x < 6 ; x++) {
puttinychar( x * 4, 1, textchar[x]);
}
}
delay(50);
}
fade_down();
}
// basic_mode()
// show the time in 5x7 characters
void basic_mode()
{
cls();

char buffer[3]; //for int to char conversion to turn rtc values into chars we can print on screen
byte offset = 0; //used to offset the x postition of the digits and centre the display when we are in
12 hour mode and the clock shows only 3 digits. e.g. 3:21
byte x, y; //used to draw a clear box over the left hand "1" of the display when we roll from
12:59 -> 1:00am in 12 hour mode.

//do 12/24 hour conversion if ampm set to 1


byte hours = rtc[2];

if (hours > 12) {


hours = hours - ampm * 12;
}
if (hours < 1) {
hours = hours + ampm * 12;
}

//do offset conversion


if (ampm && hours < 10) {
offset = 2;
}

//set the next minute we show the date at


//set_next_date();

// initially set mins to value 100 - so it wll never equal rtc[1] on the first loop of the clock, meaning
we draw the clock display when we enter the function
byte secs = 100;
byte mins = 100;
int count = 0;

//run clock main loop as long as run_mode returns true


while (run_mode()) {

//get the time from the clock chip


get_time();

//check for button press


if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
return;
}
//check whether it's time to automatically display the date
//check_show_date();

//draw the flashing : as on if the secs have changed.


if (secs != rtc[0]) {

//update secs with new value


secs = rtc[0];

//draw :
plot (15 - offset, 2, 1); //top point
plot (15 - offset, 5, 1); //bottom point
count = 400;
}

//if count has run out, turn off the :


if (count == 0) {
plot (15 - offset, 2, 0); //top point
plot (15 - offset, 5, 0); //bottom point
}
else {
count--;
}

//re draw the display if button pressed or if mins != rtc[1] i.e. if the time has changed from what
we had stored in mins, (also trigggered on first entering function when mins is 100)
if (mins != rtc[1]) {

//update mins and hours with the new values


mins = rtc[1];
hours = rtc[2];

//adjust hours of ampm set to 12 hour mode


if (hours > 12) {
hours = hours - ampm * 12;
}
if (hours < 1) {
hours = hours + ampm * 12;
}

itoa(hours, buffer, 10);

//if hours < 10 the num e.g. "3" hours, itoa coverts this to chars with space "3 " which we dont
want
if (hours < 10) {
buffer[1] = buffer[0];
buffer[0] = '0';
}

//print hours
//if we in 12 hour mode and hours < 10, then don't print the leading zero, and set the offset so
we centre the display with 3 digits.
if (ampm && hours < 10) {
offset = 2;

//if the time is 1:00am clear the entire display as the offset changes at this time and we need to
blank out the old 12:59
if ((hours == 1 && mins == 0) ) {
cls();
}
}
else {
//else no offset and print hours tens digit
offset = 0;

//if the time is 10:00am clear the entire display as the offset changes at this time and we need
to blank out the old 9:59
if (hours == 10 && mins == 0) {
cls();
}

putnormalchar(1, 0, buffer[0]);
}
//print hours ones digit
putnormalchar(7 - offset, 0, buffer[1]);

//print mins
//add leading zero if mins < 10
itoa (mins, buffer, 10);
if (mins < 10) {
buffer[1] = buffer[0];
buffer[0] = '0';
}
//print mins tens and ones digits
putnormalchar(19 - offset, 0, buffer[0]);
putnormalchar(25 - offset, 0, buffer[1]);
}
}
fade_down();
}

//like basic_mode but with slide effect


void slide() {

byte digits_old[4] = {99, 99, 99, 99}; //old values we store time in. Set to somthing that will never
match the time initially so all digits get drawn wnen the mode starts
byte digits_new[4]; //new digits time will slide to reveal
byte digits_x_pos[4] = {25, 19, 7, 1}; //x pos for which to draw each digit at

char old_char[2]; //used when we use itoa to transpose the current digit (type byte) into a char to
pass to the animation function
char new_char[2]; //used when we use itoa to transpose the new digit (type byte) into a char to
pass to the animation function

//old_chars - stores the 5 day and date suffix chars on the display. e.g. "mon" and "st". We feed
these into the slide animation as the current char when these chars are updated.
//We sent them as A initially, which are used when the clocl enters the mode and no last chars are
stored.
//char old_chars[6] = "AAAAA";

//plot the clock colon on the display


cls();
putnormalchar( 13, 0, ':');

byte old_secs = rtc[0]; //store seconds in old_secs. We compare secs and old secs. WHen they are
different we redraw the display

//run clock main loop as long as run_mode returns true


while (run_mode()) {

get_time();

//check for button press


if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
return;
}

//if secs have changed then update the display


if (rtc[0] != old_secs) {
old_secs = rtc[0];

//do 12/24 hour conversion if ampm set to 1


byte hours = rtc[2];
if (hours > 12) {
hours = hours - ampm * 12;
}
if (hours < 1) {
hours = hours + ampm * 12;
}

//split all date and time into individual digits - stick in digits_new array

//rtc[0] = secs //array pos and digit stored


//digits_new[0] = (rtc[0]%10); //0 - secs ones
//digits_new[1] = ((rtc[0]/10)%10); //1 - secs tens
//rtc[1] = mins
digits_new[0] = (rtc[1] % 10); //2 - mins ones
digits_new[1] = ((rtc[1] / 10) % 10); //3 - mins tens
//rtc[2] = hours
digits_new[2] = (hours % 10); //4 - hour ones
digits_new[3] = ((hours / 10) % 10); //5 - hour tens
//rtc[4] = date
//digits_new[6] = (rtc[4]%10); //6 - date ones
//digits_new[7] = ((rtc[4]/10)%10); //7 - date tens

//draw initial screen of all chars. After this we just draw the changes.

//compare digits 0 to 3 (mins and hours)


for (byte i = 0; i <= 3; i++) {
//see if digit has changed...
if (digits_old[i] != digits_new[i]) {

//run 9 step animation sequence for each in turn


for (byte seq = 0; seq <= 8 ; seq++) {

//convert digit to string


itoa(digits_old[i], old_char, 10);
itoa(digits_new[i], new_char, 10);

//if set to 12 hour mode and we're on digit 2 (hours tens mode) then check to see if this is a
zero. If it is, blank it instead so we get 2.00pm not 02.00pm
if (ampm && i == 3) {
if (digits_new[3] == 0) {
new_char[0] = ' ';
}
if (digits_old[3] == 0) {
old_char[0] = ' ';
}
}
//draw the animation frame for each digit
slideanim(digits_x_pos[i], 0, seq, old_char[0], new_char[0]);
delay(SLIDE_DELAY);
}
}
}

/*
//compare date digit 6 (ones) and (7) tens - if either of these change we need to update the date
line. We compare date tens as say from Jan 31 -> Feb 01 then ones digit doesn't change
if ((digits_old[6] != digits_new[6]) || (digits_old[7] != digits_new[7])) {
//change the day shown. Loop below goes through each of the 3 chars in turn e.g. "MON"
for (byte day_char = 0; day_char <=2 ; day_char++){
//run the anim sequence for each char
for (byte seq = 0; seq <=8 ; seq++){
//the day (0 - 6) Read this number into the days char array. the seconds number in the array
0-2 gets the 3 chars of the day name, e.g. m o n
slideanim(6*day_char,8,seq,old_chars[day_char],days[rtc[3]][day_char]); //6 x day_char
gives us the x pos for the char
delay(SLIDE_DELAY);
}
//save the old day chars into the old_chars array at array pos 0-2. We use this next time we
change the day and feed it to the animation as the current char. The updated char is fed in as the new
char.
old_chars[day_char] = days[rtc[3]][day_char];
}

//change the date tens digit (if needed) and ones digit. (the date ones digit wil alwaus change,
but putting this in the 'if' loop makes it a bit neater code wise.)
for (byte i = 7; i >= 6; i--){
if (digits_old[i] != digits_new[i]) {
for (byte seq = 0; seq <=8 ; seq++){
itoa(digits_old[i],old_char,10);
itoa(digits_new[i],new_char,10);
slideanim(digits_x_pos[i],8,seq,old_char[0],new_char[0]);
delay(SLIDE_DELAY);
}
}
}

//print the day suffix "nd" "rd" "th" etc. First work out date 2 letter suffix - eg st, nd, rd, th
byte s = 3; //the pos to read our suffix array from.
byte date = rtc[4];
if(date == 1 || date == 21 || date == 31) {
s = 0;
}
else if (date == 2 || date == 22) {
s = 1;
}
else if (date == 3 || date == 23) {
s = 2;
}

for (byte suffix_char = 0; suffix_char <=1 ; suffix_char++){


for (byte seq = 0; seq <=8 ; seq++){
slideanim((suffix_char*6)+36,8,seq,old_chars[suffix_char+3],suffix[s][suffix_char]); // we
pass in the old_char array char as the current char and the suffix array as the new char
delay(SLIDE_DELAY);
}
//save the suffic char in the old chars array at array pos 3 and 5. We use these chars next time
we change the suffix and feed it to the animation as the current char. The updated char is fed in as
the new char.
old_chars[suffix_char+3] = suffix[s][suffix_char];
}
}//end do date line
*/

//save digita array tol old for comparison next loop


for (byte i = 0; i <= 3; i++) {
digits_old[i] = digits_new[i];
}
}//secs/oldsecs
}//while loop
fade_down();
}

//called by slide
//this draws the animation of one char sliding on and the other sliding off. There are 8 steps in the
animation, we call the function to draw one of the steps from 0-7
//inputs are are char x and y, animation frame sequence (0-7) and the current and new chars being
drawn.
void slideanim(byte x, byte y, byte sequence, char current_c, char new_c) {

// To slide one char off and another on we need 9 steps or frames in sequence...

// seq# 0123456 <-rows of the display


// | |||||||
// seq0 0123456 START - all rows of the display 0-6 show the current characters rows 0-6
// seq1 012345 current char moves down one row on the display. We only see it's rows 0-5. There
are at display positions 1-6 There is a blank row inserted at the top
// seq2 6 01234 current char moves down 2 rows. we now only see rows 0-4 at display rows 2-6
on the display. Row 1 of the display is blank. Row 0 shows row 6 of the new char
// seq3 56 0123
// seq4 456 012 half old / half new char
// seq5 3456 01
// seq6 23456 0
// seq7 123456
// seq8 0123456 END - all rows show the new char

//from above we can see...


//currentchar runs 0-6 then 0-5 then 0-4 all the way to 0. starting Y position increases by 1 row
each time.
//new char runs 6 then 5-6 then 4-6 then 3-6. starting Y position increases by 1 row each time.

//if sequence number is below 7, we need to draw the current char


if (sequence < 7) {
byte dots;
// if (current_c >= 'A' && || (current_c >= 'a' && current_c <= 'z') ) {
// current_c &= 0x1F; // A-Z maps to 1-26
// }
if (current_c >= 'A' && current_c <= 'Z' ) {
current_c &= 0x1F; // A-Z maps to 1-26
}
else if (current_c >= 'a' && current_c <= 'z') {
current_c = (current_c - 'a') + 41; // A-Z maps to 41-67
}
else if (current_c >= '0' && current_c <= '9') {
current_c = (current_c - '0') + 31;
}
else if (current_c == ' ') {
current_c = 0; // space
}
else if (current_c == '.') {
current_c = 27; // full stop
}
else if (current_c == '\'') {
current_c = 28; // single quote mark
}
else if (current_c == ':') {
current_c = 29; //colon
}
else if (current_c == '>') {
current_c = 30; // clock_mode selector arrow
}

byte curr_char_row_max = 7 - sequence; //the maximum number of rows to draw is 6 - sequence


number
byte start_y = sequence; //y position to start at - is same as sequence number. We inc this each
loop

//plot each row up to row maximum (calculated from sequence number)


for (byte curr_char_row = 0; curr_char_row <= curr_char_row_max; curr_char_row++) {
for (byte col = 0; col < 5; col++) {
dots = pgm_read_byte_near(&myfont[current_c][col]);
if (dots & (64 >> curr_char_row))
plot(x + col, y + start_y, 1); //plot led on
else
plot(x + col, y + start_y, 0); //else plot led off
}
start_y++;//add one to y so we draw next row one down
}
}

//draw a blank line between the characters if sequence is between 1 and 7. If we don't do this we
get the remnants of the current chars last position left on the display
if (sequence >= 1 && sequence <= 8) {
for (byte col = 0; col < 5; col++) {
plot(x + col, y + (sequence - 1), 0); //the y position to draw the line is equivalent to the sequence
number - 1
}
}

//if sequence is above 2, we also need to start drawing the new char
if (sequence >= 2) {

//work out char


byte dots;
//if (new_c >= 'A' && new_c <= 'Z' || (new_c >= 'a' && new_c <= 'z') ) {
// new_c &= 0x1F; // A-Z maps to 1-26
//}
if (new_c >= 'A' && new_c <= 'Z' ) {
new_c &= 0x1F; // A-Z maps to 1-26
}
else if (new_c >= 'a' && new_c <= 'z') {
new_c = (new_c - 'a') + 41; // A-Z maps to 41-67
}
else if (new_c >= '0' && new_c <= '9') {
new_c = (new_c - '0') + 31;
}
else if (new_c == ' ') {
new_c = 0; // space
}
else if (new_c == '.') {
new_c = 27; // full stop
}
else if (new_c == '\'') {
new_c = 28; // single quote mark
}
else if (new_c == ':') {
new_c = 29; // clock_mode selector arrow
}
else if (new_c == '>') {
new_c = 30; // clock_mode selector arrow
}

byte newcharrowmin = 6 - (sequence - 2); //minimumm row num to draw for new char - this
generates an output of 6 to 0 when fed sequence numbers 2-8. This is the minimum row to draw for
the new char
byte start_y = 0; //y position to start at - is same as sequence number. we inc it each row

//plot each row up from row minimum (calculated by sequence number) up to 6


for (byte newcharrow = newcharrowmin; newcharrow <= 6; newcharrow++) {
for (byte col = 0; col < 5; col++) {
dots = pgm_read_byte_near(&myfont[new_c][col]);
if (dots & (64 >> newcharrow))
plot(x + col, y + start_y, 1); //plot led on
else
plot(x + col, y + start_y, 0); //else plot led off
}
start_y++;//add one to y so we draw next row one down
}
}
}

//print a clock using words rather than numbers


void word_clock() {

cls();

char numbers[19][10] = {
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"
};
char numberstens[5][7] = {
"ten", "twenty", "thirty", "forty", "fifty"
};

//potentially 3 lines to display


char str_a[8];
char str_b[8];
char str_c[8];

//byte hours_y, mins_y; //hours and mins and positions for hours and mins lines

byte hours = rtc[2];


if (hours > 12) {
hours = hours - ampm * 12;
}
if (hours < 1) {
hours = hours + ampm * 12;
}

get_time(); //get the time from the clock chip


byte old_mins = 100; //store mins in old_mins. We compare mins and old mins & when they are
different we redraw the display. Set this to 100 initially so display is drawn when mode starts.
byte mins;

//run clock main loop as long as run_mode returns true


while (run_mode()) {

//check for button press


if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
}

get_time(); //get the time from the clock chip


mins = rtc[1]; //get mins

//if mins is different from old_mins - redraw display


if (mins != old_mins) {

//update old_mins with current mins value


old_mins = mins;

//reset these for comparison next time


mins = rtc[1];
hours = rtc[2];

//make hours into 12 hour format


if (hours > 12) {
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}

//split mins value up into two separate digits


int minsdigit = rtc[1] % 10;
byte minsdigitten = (rtc[1] / 10) % 10;

//if mins <= 10 , then top line has to read "minsdigti past" and bottom line reads hours
if (mins < 10) {
strcpy (str_a, numbers[minsdigit - 1]);
strcpy (str_b, "PAST");
strcpy (str_c, numbers[hours - 1]);
}

//if mins = 10, cant use minsdigit as above, so soecial case to print 10 past /n hour.
if (mins == 10) {
strcpy (str_a, numbers[9]);
strcpy (str_b, " PAST");
strcpy (str_c, numbers[hours - 1]);
}

//if time is not on the hour - i.e. both mins digits are not zero,
//then make first line read "hours" and 2 & 3rd lines read "minstens" "mins" e.g. "three /n
twenty /n one"
else if (minsdigitten != 0 && minsdigit != 0 ) {

strcpy (str_a, numbers[hours - 1]);

//if mins is in the teens, use teens from the numbers array for the 2nd line, e.g. "fifteen"
//if (mins >= 11 && mins <= 19) {
if (mins <= 19) {
strcpy (str_b, numbers[mins - 1]);
}
else {
strcpy (str_b, numberstens[minsdigitten - 1]);

strcpy (str_c, numbers[minsdigit - 1]);


}
}
// if mins digit is zero, don't print it. read read "hours" "minstens" e.g. "three /n twenty"
else if (minsdigitten != 0 && minsdigit == 0 ) {
strcpy (str_a, numbers[hours - 1]);
strcpy (str_b, numberstens[minsdigitten - 1]);
strcpy (str_c, "");
}

//if both mins are zero, i.e. it is on the hour, the top line reads "hours" and bottom line reads
"o'clock"
else if (minsdigitten == 0 && minsdigit == 0 ) {
strcpy (str_a, numbers[hours - 1]);
strcpy (str_b, "O'CLOCK");
strcpy (str_c, "");
}

}//end worknig out time

//run in a loop
//print line a "twelve"
byte len = 0;
while (str_a[len]) {
len++;
}; //get length of message
byte offset_top = (31 - ((len - 1) * 4)) / 2; //

//plot hours line


byte i = 0;
while (str_a[i]) {
puttinychar((i * 4) + offset_top, 1, str_a[i]);
i++;
}

//hold display but check for button presses


int counter = 1000;
while (counter > 0){
//check for button press
if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
}
delay(1);
counter--;
}
fade_down();

//print line b
len = 0;
while (str_b[len]) {
len++;
}; //get length of message
offset_top = (31 - ((len - 1) * 4)) / 2;

i = 0;
while (str_b[i]) {
puttinychar((i * 4) + offset_top, 1, str_b[i]);
i++;
}
//hold display but check for button presses
counter = 1000;
while (counter > 0){
if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
}
delay(1);
counter--;
}
fade_down();

//print line c if there.


len = 0;
while (str_c[len]) {
len++;
}; //get length of message
offset_top = (31 - ((len - 1) * 4)) / 2;

i = 0;
while (str_c[i]) {
puttinychar((i * 4) + offset_top, 1, str_c[i]);
i++;
}
counter = 1000;
while (counter > 0){
//check for button press
if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
}
delay(1);
counter--;
}
fade_down();

//hold display blank but check for button presses before starting again.
counter = 1000;
while (counter > 0){
//check for button press
if (buttonA.uniquePress()) {
switch_mode();
return;
}
if (buttonB.uniquePress()) {
display_date();
}
delay(1);
counter--;
}
}
fade_down();
}

/// scroll message - not used at present - too slow.


void scroll() {

char message[] = {"Hello There "};

cls();
byte p = 6; //current pos in string
byte chara[] = {0, 1, 2, 3, 4, 5}; //chars from string
int x[] = {0, 6, 12, 18, 24, 30}; //xpos for each char
byte y = 0; //y pos

// clear_buffer();

while (message[p] != '\0') {

//draw all 6 chars


for (byte c = 0; c < 6; c++) {

putnormalchar(x[c],y,message[ chara[c] ]);

//draw a line of pixels turned off after each char,otherwise the gaps between the chars have
pixels left in them from the previous char
for (byte yy = 0 ; yy < 8; yy ++) {
plot(x[c] + 5, yy, 0);
}

//take one off each chars position


x[c] = x[c] - 1;
}

//reset a char if it's gone off screen


for (byte i = 0; i <= 5; i++) {
if (x[i] < -5 ) {
x[i] = 31;
chara[i] = p;
p++;
}
}
}
}
//display_date - print the day of week, date and month with a flashing cursor effect
void display_date()
{

cls();
//read the date from the DS1307

byte dow = rtc[3]; // day of week 0 = Sunday


byte date = rtc[4];
byte month = rtc[5] - 1;

//array of month names to print on the display. Some are shortened as we only have 8 characters
across to play with
char monthnames[12][9] = {
"January", "February", "March", "April", "May", "June", "July", "August", "Sept", "October",
"November", "December"
};

//print the day name

//get length of text in pixels, that way we can centre it on the display by divindin the remaining
pixels b2 and using that as an offset
byte len = 0;
while(daysfull[dow][len]) {
len++;
};
byte offset = (31 - ((len-1)*4)) / 2; //our offset to centre up the text

//print the name


int i = 0;
while(daysfull[dow][i])
{
puttinychar((i*4) + offset , 1, daysfull[dow][i]);
i++;
}
delay(1000);
fade_down();
cls();

// print date numerals


char buffer[3];
itoa(date,buffer,10);
offset = 10; //offset to centre text if 3 chars - e.g. 3rd

// first work out date 2 letter suffix - eg st, nd, rd, th etc
// char suffix[4][3]={"st", "nd", "rd", "th" }; is defined at top of code
byte s = 3;
if(date == 1 || date == 21 || date == 31) {
s = 0;
}
else if (date == 2 || date == 22) {
s = 1;
}
else if (date == 3 || date == 23) {
s = 2;
}

//print the 1st date number


puttinychar(0+offset, 1, buffer[0]);

//if date is under 10 - then we only have 1 digit so set positions of sufix etc one character nearer
byte suffixposx = 4;

//if date over 9 then print second number and set xpos of suffix to be 1 char further away
if (date > 9){
suffixposx = 8;
puttinychar(4+offset, 1, buffer[1]);
offset = 8; //offset to centre text if 4 chars
}

//print the 2 suffix characters


puttinychar(suffixposx+offset, 1, suffix[s][0]);
puttinychar(suffixposx+4+offset, 1, suffix[s][1]);

delay(1000);
fade_down();

//print the month name

//get length of text in pixels, that way we can centre it on the display by divindin the remaining
pixels b2 and using that as an offset
len = 0;
while(monthnames[month][len]) {
len++;
};
offset = (31 - ((len-1)*4)) / 2; //our offset to centre up the text
i = 0;
while(monthnames[month][i])
{
puttinychar((i*4) +offset, 1, monthnames[month][i]);
i++;
}

delay(1000);
fade_down();
}

//dislpay menu to change the clock mode


void switch_mode() {

//remember mode we are in. We use this value if we go into settings mode, so we can change back
from settings mode (6) to whatever mode we were in.
old_mode = clock_mode;

char* modes[] = {
"Basic", "Small", "Slide", "Words", "Setup"
};

byte next_clock_mode;
byte firstrun = 1;

//loop waiting for button (timeout after 35 loops to return to mode X)


for (int count = 0; count < 35 ; count++) {

//if user hits button, change the clock_mode


if (buttonA.uniquePress() || firstrun == 1) {

count = 0;
cls();

if (firstrun == 0) {
clock_mode++;
}
if (clock_mode > NUM_DISPLAY_MODES + 1 ) {
clock_mode = 0;
}

//print arrown and current clock_mode name on line one and print next clock_mode name on
line two
char str_top[9];

//strcpy (str_top, "-");


strcpy (str_top, modes[clock_mode]);

next_clock_mode = clock_mode + 1;
if (next_clock_mode > NUM_DISPLAY_MODES + 1 ) {
next_clock_mode = 0;
}

byte i = 0;
while (str_top[i]) {
putnormalchar(i * 6, 0, str_top[i]);
i++;
}
firstrun = 0;
}
delay(50);
}
}

//run clock main loop as long as run_mode returns true


byte run_mode() {
//if random mode is on... check the hour when we change mode.
if (random_mode) {
//if hour value in change mode time = hours. then reurn false = i.e. exit mode.
if (change_mode_time == rtc[2]) {
//set the next random clock mode and time to change it
set_next_random();
//exit the current mode.
return 0;
}
}
//else return 1 - keep running in this mode
return 1;
}

//set the next hour the clock will change mode when random mode is on
void set_next_random() {

//set the next hour the clock mode will change - current time plus 1 - 4 hours
get_time();
change_mode_time = rtc[2] + random (1, 5);

//if change_mode_time now happens to be over 23, then set it to between 1 and 3am
if (change_mode_time > 23) {
change_mode_time = random (1, 4);
}

//set the new clock mode


clock_mode = random(0, NUM_DISPLAY_MODES + 1); //pick new random clock mode
}

//dislpay menu to change the clock settings


void setup_menu() {

char* set_modes[] = {
"Rndom", "24 Hr","Set", "Brght", "Exit"};
if (ampm == 0) {
set_modes[1] = ("12 Hr");
}

byte setting_mode = 0;
byte next_setting_mode;
byte firstrun = 1;

//loop waiting for button (timeout after 35 loops to return to mode X)


for(int count=0; count < 35 ; count++) {

//if user hits button, change the clock_mode


if(buttonA.uniquePress() || firstrun == 1){

count = 0;
cls();

if (firstrun == 0) {
setting_mode++;
}
if (setting_mode > NUM_SETTINGS_MODES) {
setting_mode = 0;
}

//print arrown and current clock_mode name on line one and print next clock_mode name on
line two
char str_top[9];

strcpy (str_top, set_modes[setting_mode]);

next_setting_mode = setting_mode + 1;
if (next_setting_mode > NUM_SETTINGS_MODES) {
next_setting_mode = 0;
}

byte i = 0;
while(str_top[i]) {
putnormalchar(i*6, 0, str_top[i]);
i++;
}

firstrun = 0;
}
delay(50);
}

//pick the mode


switch(setting_mode){
case 0:
set_random();
break;
case 1:
set_ampm();
break;
case 2:
set_time();
break;
case 3:
set_intensity();
break;
case 4:
//exit menu
break;
}

//change the clock from mode 6 (settings) back to the one it was in before
clock_mode=old_mode;
}

//toggle random mode - pick a different clock mode every few hours
void set_random(){
cls();

char text_a[9] = "Off";


char text_b[9] = "On";
byte i = 0;

//if random mode is on, turn it off


if (random_mode){

//turn random mode off


random_mode = 0;

//print a message on the display


while(text_a[i]) {
putnormalchar((i*6), 0, text_a[i]);
i++;
}
} else {
//turn randome mode on.
random_mode = 1;

//set hour mode will change


set_next_random();

//print a message on the display


while(text_b[i]) {
putnormalchar((i*6), 0, text_b[i]);
i++;
}
}
delay(1500); //leave the message up for a second or so
}

//set 12 or 24 hour clock


void set_ampm() {

// AM/PM or 24 hour clock mode - flip the bit (makes 0 into 1, or 1 into 0 for ampm mode)
ampm = (ampm ^ 1);
cls();
}

//change screen intensityintensity


void set_intensity() {
cls();

byte i = 0;
char text[7] = "Bright";
while(text[i]) {
puttinychar((i*4)+4, 0, text[i]);
i++;
}

//wait for button input


while (!buttonA.uniquePress()) {

levelbar (0,6,(intensity*2)+2,2); //display the intensity level as a bar


while (buttonB.isPressed()) {

if(intensity == 15) {
intensity = 0;
cls ();
}
else {
intensity++;
}
//print the new value
i = 0;
while(text[i]) {
puttinychar((i*4)+4, 0, text[i]);
i++;
}

//display the intensity level as a bar


levelbar (0,6,(intensity*2)+2,2);

//change the brightness setting on the displays


for (byte address = 0; address < 4; address++) {
lc.setIntensity(address, intensity);
}
delay(150);
}
}
}

// display a horizontal bar on the screen at offset xposr by ypos with height and width of xbar, ybar
void levelbar (byte xpos, byte ypos, byte xbar, byte ybar) {
for (byte x = 0; x < xbar; x++) {
for (byte y = 0; y <= ybar; y++) {
plot(x+xpos, y+ypos, 1);
}
}
}
//set time and date routine
void set_time() {

cls();

//fill settings with current clock values read from clock


get_time();
byte set_min = rtc[1];
byte set_hr = rtc[2];
byte set_date = rtc[4];
byte set_mnth = rtc[5];
int set_yr = rtc[6];

//Set function - we pass in: which 'set' message to show at top, current value, reset value, and
rollover limit.
set_date = set_value(2, set_date, 1, 31);
set_mnth = set_value(3, set_mnth, 1, 12);
set_yr = set_value(4, set_yr, 2013, 2099);
set_hr = set_value(1, set_hr, 0, 23);
set_min = set_value(0, set_min, 0, 59);

ds1307.adjust(DateTime(set_yr, set_mnth, set_date, set_hr, set_min));

cls();
}

//used to set min, hr, date, month, year values. pass


//message = which 'set' message to print,
//current value = current value of property we are setting
//reset_value = what to reset value to if to rolls over. E.g. mins roll from 60 to 0, months from 12 to
1
//rollover limit = when value rolls over
int set_value(byte message, int current_value, int reset_value, int rollover_limit){

cls();
char messages[6][17] = {
"Set Mins", "Set Hour", "Set Day", "Set Mnth", "Set Year"};

//Print "set xyz" top line


byte i = 0;
while(messages[message][i])
{
puttinychar(i*4 , 1, messages[message][i]);
i++;
}

delay(2000);
cls();

//print digits bottom line


char buffer[5] = " ";
itoa(current_value,buffer,10);
puttinychar(0 , 1, buffer[0]);
puttinychar(4 , 1, buffer[1]);
puttinychar(8 , 1, buffer[2]);
puttinychar(12, 1, buffer[3]);

delay(300);
//wait for button input
while (!buttonA.uniquePress()) {

while (buttonB.isPressed()){

if(current_value < rollover_limit) {


current_value++;
}
else {
current_value = reset_value;
}
//print the new value
itoa(current_value, buffer ,10);
puttinychar(0 , 1, buffer[0]);
puttinychar(4 , 1, buffer[1]);
puttinychar(8 , 1, buffer[2]);
puttinychar(12, 1, buffer[3]);
delay(150);
}
}
return current_value;
}

void get_time()
{
//get time
DateTime now = ds1307.now();
//save time to array
rtc[6] = now.year();
rtc[5] = now.month();
rtc[4] = now.day();
rtc[3] = now.dayOfWeek(); //returns 0-6 where 0 = Sunday
rtc[2] = now.hour();
rtc[1] = now.minute();
rtc[0] = now.second();

//flash arduino led on pin 13 every second


//if ( (rtc[0] % 2) == 0) {
// digitalWrite(13, HIGH);
//}
//else {
// digitalWrite(13, LOW);
//}

//print the time to the serial port - useful for debuging RTC issues
/*
Serial.print(rtc[2]);
Serial.print(":");
Serial.print(rtc[1]);
Serial.print(":");
Serial.println(rtc[0]);
*/
}

208. GPS RECEIVER


/*
* Rui Santos
The module GND pin is connected to Arduino GND pin
The module RX pin is connected to Arduino pin 3
The module TX pin is connected to Arduino pin 4
The module VCC pin is connected to Arduino 5V pin
* Complete Project Details http://randomnerdtutorials.com
*/

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 4, TXPin = 3;


static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object


TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

//
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
/*
For details about the LCD display with I2C support see
http://www.fasttech.com/reviews/1380909/22072
and
http://dx.com/p/funduino-iic-i2c-1602-lcd-adapter-board-w-2-5-lcd-screen-black-green-red-173588
The reviewer comments by docpayce and particularly JackWP associated with the two product
pages above have been very useful.

Connect the LCD: VCC -> 5V, GND -> GND, SDA -> A4 (PortC4, ADC4), SCL -> A5 (PortC5,
SDA)

The LiquidCrystal_I2C library needs to be downloaded and installed from here:


https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home
*/

#define I2C_ADDR 0x27


#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C
lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin,BACKLIGHT_PIN,POSI
TIVE);
LCD *myLCD = &lcd;

//
const int buttonPin = 2;
int buttonState = 0;
void setup(){
Serial.begin(9600);
ss.begin(GPSBaud);
//
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, LOW);
lcd.begin(16,2); // initialize the lcd
lcd.home (); // go home
lcd.print("GPS ARDUINO");
lcd.setCursor(0, 1);
lcd.print("SIGNAL SEARCH");
delay(100);
//
}

void loop(){
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.


// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
frezze();
}
else {
// turn LED off:
normdisplay();
}
}

void normdisplay(){
while (ss.available() > 0){
gps.encode(ss.read());
if (gps.location.isUpdated()){
Serial.print("Latitude= ");
Serial.print(gps.location.lat(), 6);
Serial.print(" Longitude= ");
Serial.println(gps.location.lng(), 6);
//lcd.clear();
lcd.home ();
lcd.setCursor(0, 0);
lcd.print("LAT=");
lcd.setCursor(4, 0);
lcd.print(gps.location.lat(), 9);
lcd.setCursor(0, 1);
lcd.print("LNG=");
lcd.setCursor(4, 1);
lcd.print(gps.location.lng(), 9);
}
}
}

void frezze(){
while (ss.available() > 0){
gps.encode(ss.read());
if (gps.location.isUpdated()){
Serial.print("Latitude= ");
Serial.print(gps.location.lat(), 6);
Serial.print(" Longitude= ");
Serial.println(gps.location.lng(), 6);
//lcd.clear();
lcd.home ();
lcd.setCursor(0, 0);
lcd.print("LAT=");
lcd.setCursor(4, 0);
lcd.print(gps.location.lat(), 9);
lcd.setCursor(0, 1);
lcd.print("LNG=");
lcd.setCursor(4, 1);
lcd.print(gps.location.lng(), 9);
delay(600000);
}
}
}

Anda mungkin juga menyukai