Proposal Kerja Proyek Teknik Komputer Jaringan SMK Negeri 1 Rembang
Proyek Kalkulus IntegralDeskripsi lengkap
aplikasi arduinoDeskripsi lengkap
Descripción: arduino
controlador electronicoDescripción completa
Placa o una plataforma de hardware para edificios domoticosDescripción completa
Introdução ao arduino, sensores etc
Livro completo sobre arduino
belajar arduinoDeskripsi lengkap
descripcion de arduinoDescripción completa
electronica digitalDescripción completa
electronicaDescripción completa
Descripción completa
el documento muestra que es arduino y sus modelos e HistoriaDescripción completa
ArduinoDescripción completa
Descripción: Livro completo sobre arduino
GUÍA DE LABORATORIODescripción completa
Materiales para realizar un proyecto con arduinoDescripción completa
Descripción completa
programacion con arduinoDescripción completa
arduinoDescrição completa
arduinoDescripción completa
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
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
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 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); }
// 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 #include // 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);
8. STEPPER MOTOR 28BYJ-48 WITH L293D CONTROLLED BY KEYBOARD
/* Adafruit Arduino - Lesson 16. Stepper */ #include 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 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);
} 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 #define led 11 //this pin for drive relay CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2); is sensor pin, add a wire and or foil if desired CapacitiveSensor cs_5_6 = CapacitiveSensor(5,6); is sensor pin, add a wire and or foil void setup() { cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF); 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);
// 10M resistor between pins 4 & 2, pin 2 // 10M resistor between pins 5 & 6, pin 6
// turn off autocalibrate on channel 1 - just as an
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 #include Adafruit_ADS1115 ads(0x48); #include 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 // 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); } ---------------------------------------------------------------------------------------------------------
/* 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 #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(':');
// 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) // {
} 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 /*-----( 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); }
#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 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 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 //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 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 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 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 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, masingmasing 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 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() { Serial.begin(9600); } 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); }
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 #include 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 #include 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 #include 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 #include #include #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 #include #include /* 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
#include /* * 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 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<
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<
} } 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<
//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() {
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<
//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<
//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<
//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
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<
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
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.
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); Write_Max7219(0x0a, 0x03); Write_Max7219(0x0b, 0x07); Write_Max7219(0x0c, 0x01); Write_Max7219(0x0f, 0x00); }
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;
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,
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){
/* ################################################################################ # 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/
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
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. */
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
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. */
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
This code is a public example. */
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
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. */
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); printStringWithShift(string12, 100); */ printString(string13);
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
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.
#include 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 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 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,
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);
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[] = {
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); } ===================================================================
/* In this project we use LM324 chip for amplify signal from RTD PT100, amplified signal than go to ADS1015 for increase digital resolution. */ #include
#include 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); } =====================================================================
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 int pinIncrease = 2; int pinDecrease = 3; int pinLED = 11; int pinSetting = 10; int SpeedFan = 0; byte laju; void setup() { Serial.begin(9600);
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 #include //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 // 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<
// 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 #define MPU6050_I2C_SLV1_LEN1 #define MPU6050_I2C_SLV1_LEN2 #define MPU6050_I2C_SLV1_LEN3
MPU6050_D0 MPU6050_D1 MPU6050_D2 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(", "));
// 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
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
#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;
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
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 // 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<
#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 #define MPU6050_I2C_MST_DLY1 #define MPU6050_I2C_MST_DLY2 #define MPU6050_I2C_MST_DLY3
MPU6050_D0 MPU6050_D1 MPU6050_D2 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"));
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
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-------------------
#include // 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 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() {
#include 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 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 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 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 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 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();
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 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); } } } } //-----------------------------------------------------------------
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 // 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<
#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; dY = (int16_t) y / 64.0; dZ = (int16_t) z / 64.0;
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
// 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 // 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<
// 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
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 //Include the Wire library
#include //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 #include #include #include 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). */
#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 #include #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
// indicates whether MPU interrupt pin has gone high
// ================================================================ // === 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);
70. MENGUKUR SUDUT MEMUTAR DENGAN MPU6050 (IR RESET)
#include #include #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 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; void dmpDataReady() { mpuInterrupt = true; }
// indicates whether MPU interrupt pin has gone high
// ================================================================ // === 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);
71. MENGENDALIKAN CONTINOUS MOTOR SERVO DENGAN IR REMOTE
#include #include 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 #include 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 #include Servo myservo1; // create servo object to control a servo Servo myservo2; #include #include #include int value; int addr0 = 1; int addr1 = 2; int a; byte b; int RECV_PIN = 5; #define code1 #define code2 #define code3 #define code4
4010860575 // code received from button A 4010827935 // code received from button B 4010824875 // code received from button C 4010811615
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; void dmpDataReady() { mpuInterrupt = true; } void setup() { myservo1.attach(10);
// indicates whether MPU interrupt pin has gone high
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;
/* * 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
/* 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);
//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; int inputPin = 7; int pirState = LOW; int val = 0; int pinSpeaker = 11;
// choose the pin for the LED // choose the input pin (for PIR sensor) // we start, assuming no motion detected // variable for reading the pin status //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);
#include 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 {
#include #include // 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(" 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 #include // 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 #include 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 #include #include 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); String readString;
//server port
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(""); client.println(""); client.println("<meta name='apple-mobile-web-app-capable' content='yes' />"); client.println("<meta name='apple-mobile-web-app-status-bar-style' content='blacktranslucent' />"); client.println(""); client.println("Random Nerd Tutorials Project"); client.println(""); client.println(""); client.println("
"); client.println(" "); client.println("Turn On LED"); client.println("Turn Off LED "); client.println(" "); client.println(" "); client.println("Rotate Left"); client.println("Rotate Right "); client.println("
Created by Rui Santos. Visit http://randomnerdtutorials.com for more projects!
"); client.println(" "); client.println(""); client.println(""); 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 #include // 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(""); client.println(""); // 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(" "); } client.println("");
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 #include #include 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.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 #include #include 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(""); client.println(""); /* client.println("<meta name='apple-mobile-web-app-capable' content='yes' />"); client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-
Created by Rui Santos. Visit http://randomnerdtutorials.com for more projects!
"); client.println(" "); client.println(""); client.println(""); 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=""; } } } } }
#include #include #include // 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”. ===========================================================
{ 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 . */ // Reference the I2C Library #include // Reference the HMC5883L Compass Library #include // 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)
/* 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. ===================================================================
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 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
// print leading X to mark the following value as // 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 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 /* 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 #include 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 #include 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); } }
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); }
/* 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 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 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 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();
/* || @version 1.0 || @author Andrew Mascolo || @date May 15, 2013 || || @description || Simple use of keypad and LCD */ #include #include #include
#include //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 //#include #include #include #include #include #include ///////////////////////////////////////////////////////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);
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 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 = "); }
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 servo1; long num; void setup() { servo1.attach(9); Serial.begin(9600); Serial.print("Enter Position = "); } void loop() { while(Serial.available()>0) {
Pada proyek ini kita demonstrasikan pengiriman karakter dari serial monitor ke LCD display. /* // include the library code: #include // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2); */ #include #include #include /* 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 // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2); */ #include #include #include /* 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); //}# }
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
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 #include #include //=============================== const float fVerNum = 0.03; #include #include "RTClib.h" RTC_DS1307 RTC;
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; }
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
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);
/* and press "#" than enter your password and press*. The LED will turn ON and will OFF. */ #include //http://playground.arduino.cc/uploads/Code/Password.zip //tells to use password library #include //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 #include // 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); }
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 #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 #include #include #include /* 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 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 #include 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 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 #include 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); }
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);
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 #include 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++;
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 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]); }
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;
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);
//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); } =========================================================
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
122. ULTRASONIC SENSOR WITH LED MATRIX
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
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 #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 #include #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 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);
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
125. DHT 22 WITH LED MATRIX-RTC