Elif Avcu - 220 Fun Projects With Arduino (2020)
Elif Avcu - 220 Fun Projects With Arduino (2020)
biodegradable straw
× 1
× 1
× 1
USB-A to B Cable
× 1
NECESSARY TOOLS AND MACHINES
scissors
Tape, Clear
ruler
APPS AND ONLINE SERVICES
Microsoft Data Streamer
Arduino IDE
Microsoft Excel
This project aimed to meet the requirements of the science fair that
happened in my city Our electroconductivity sensor was designed as a
simple way to measure the amounts of dissolved substances in different
water samples. It can also be used as a (short-term) soil moisture
sensor!
This sensor is made of two wires separated by an air gap. The air gap
allows us to test how well a material or substance conducts electricity.
Build an Electroconductivity Meter
Mark your straw at 14 cm. Cut at your mark.
Next, mark both of your coffee stir sticks at 13 cm and make cuts.
Using your hot glue gun, run a thin line of glue along the length of one
of your stir sticks.
Quickly press the sticks together until the glue has cooled.
Measure and cut two lengths of 17 cm stainless steel wire. Straighten
out the wires the best you can.
Place the wire on the stir stick so that it is centered and the ends extend
about 1.75 cm beyond the stir stick.
Center your other wire opposite the first. Tape the wires onto the stir
sticks.
Tape the middle and opposite ends of the sticks to hold the wire in
place keeping the wires centered on the sticks.
Measure to make sure your wires stick out of the end of the straw at the
1.5 cm mark.
Dab some hot glue inside both ends of the straw.
Cut the 4cm straw in half, then dab some hot glue on the end and...
... attach to the end of the straw! This will act as a shield guard for the
sensor wire ends.
Bend the longer ends of the wire as shown in the photo above. This
gives the alligator clips a better connection once attached.
SCHEMATICS
CODE
// CONSTANTS / SETTINGS
const byte POWER_PIN = 2; // Digital pin to use for powering pulse circuit
const byte EC_PIN = A0; // Analog pin used to read EC Meter volage
const int READ_DURATION = 100; // Amount of time to take reading for (ms)
const int READ_INTERVAL = 6000; // Amount of time between readings (ms)
// TIMESTAMPS
// SENSORS
float ecMeterReading = 0;
float ecMeterVoltage = 0;
void setup() {
Serial.begin( 9600 );
void loop() {
currentTime = millis();
// Read Sensors
// Check for start read time
if ( currentTime - readStartTime >= READ_INTERVAL ){ // Initialize EC Meter read
sequence
readStartTime = currentTime; // Set start time
}
else if ( currentTime - READ_DURATION <= readStartTime ) // Power Up / Read
{
startPower( POWER_PIN ); // Start charging solution
delay(250); // Delay until fully charged
readSensors(); // Take sensor readings
delay(250);
} else { // Power Down
stopPower( POWER_PIN ); // Stop charging and let solution
depolarize
}
writeToSerial();
}
/*
-------------------------------------------------------------------------------------------------------
SENSOR/ARDUINO PROCESSING
-------------------------------------------------------------------------------------------------------
*/
void readSensors() {
ecMeterReading = analogRead( EC_PIN ); // read the voltage from the EC Meter
ecMeterVoltage = ecMeterReading * 5.0;
ecMeterVoltage = ecMeterVoltage / 1024;
}
/*
-------------------------------------------------------------------------------------------------------
OUTGOING SERIAL DATA TO EXCEL PROCESSING CODE
-------------------------------------------------------------------------------------------------------
*/
void writeToSerial()
{
// Ignore if not within output interval
if ( currentTime - lastOutputTime < SERIAL_OUTPUT_INTERVAL ) {
return;
}
Serial.print( ecMeterVoltage , 4 );
Serial.print( SERIAL_OUTPUT_DELIMITER );
Serial.println();
lastOutputTime = currentTime;
}
2) Arduino Cockroach Laser Killer
Arduino Nano R3
× 1
SG90 Micro-servo motor
× 1
LDR sensor
× 1
× 1
× 1
Breadboard (generic)
The 170 points breadboard
× 1
9V battery (generic)
× 1
9V Battery Clip
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Okay...this is a simple LDR and Servo interaction. Geta laser pen and
"shoot" at the target. LDR activates a servo motor to drop your target
down. 3 seconds later it goes up again for another shot.
The main issue is to set the correct threshold of the LDR sensor and avoid
unwanted movements due to light conditions.
A 7cm x 7cm box.
The inital setup. When energized, the servo lifts the target.
The target arised and the laser gun!
Creepy!
In the box with a smal breadboard.
SCHEMATICS
CODE
/*
Project - Interaction LDR x Servo
*/
#include <Servo.h>
void setup() {
pinMode(pinServo, OUTPUT);
servo1.attach(pinServo); // attaches the servo pin
servo1.write(155);// tell servo to go to "up" position
delay(200);
pinMode(sensor, INPUT);
}
void loop() {
sensorValue = analogRead(sensor);
if (sensorValue > triggerPoint){
servo1.write(75); // tell servo to go to "down" position
delay(3000);
servo1.write(155);
delay(200);
}
}//End loop
× 1
× 1
1Sheeld
× 1
Micro Metal DC motor kit
× 2
Magnetic Disk
× 2
LED (generic)
× 1
NECESSARY TOOLS AND MACHINES
Are you tired of erasing the board every time you use it. Have you ever
thought of erasing the whole board while you are sitting in your place. The
automatic board eraser is a normal magnetic board eraser with motors and
wheels that can easily erase and clean your board using your mobile
phone. Just leave it mounted on the board and use it when you need to
erase.
After connecting all the hardware components and uploading the code to
the arduino and 1sheeld start opening the 1sheeld mobile application and
connect it to the 1sheeld board via Bluetooth. Then you have to select the
shields that we will use; they are the game pad shield and accelerometer
shield. Put the eraser on the board and open the game pad shield and start
using the four arrow directions to move up, down, left or right. An LED
will be high when the magnetic eraser moves on the board to start erasing
words. Another way to control this eraser is to open the accelerometer
shield and hold the phone in your hand. If you want to move up tilt your
hand in the front direction to make the Y < -5, so the eraser will move
up. If you want to move down tilt your hand in the backward direction to
make the Y < 6, so the eraser will move down. Furthermore, if you want to
move right tilt your hand in the right direction to make the x < -6, so the
eraser will move in the right direction and finally If you want to move left
tilt your hand in the left direction to make the x > 6, so the eraser will
move in the left direction. Now your board will be easily controlled to
erase the whole board without doing any effort.
SCHEMATICS
CODE
#define CUSTOM_SETTINGS
#define INCLUDE_GAMEPAD_SHIELD
#define INCLUDE_LED_SHIELD
#define INCLUDE_ACCELEROMETER_SENSOR_SHIELD
float x, y, z;
void setup()
{
/* Start communication. */
OneSheeld.begin();
/* Set the LED pin as output. */
pinMode(ledPin, OUTPUT);
void loop()
{ x=AccelerometerSensor.getX();
y=AccelerometerSensor.getY();
z=AccelerometerSensor.getZ();
}
/* If down is pressed, move the car backwards. */
else if (GamePad.isDownPressed()|| y > 6)
{
analogWrite(motorASpeedPin, 255);
analogWrite(motorBSpeedPin, 255);
digitalWrite(motorAPin1, HIGH);
digitalWrite(motorAPin2, LOW);
digitalWrite(motorBPin1, HIGH);
digitalWrite(motorBPin2, LOW);
digitalWrite(ledPin, HIGH);
}
/* If right is pressed, turn the car to the right. */
else if (GamePad.isRightPressed() || x < -6)
{
analogWrite(motorASpeedPin, 255);
analogWrite(motorBSpeedPin, 255);
digitalWrite(motorAPin1, LOW);
digitalWrite(motorAPin2, HIGH);
digitalWrite(motorBPin1, HIGH);
digitalWrite(motorBPin2, LOW);
digitalWrite(ledPin, HIGH);
}
/* If left is pressed, turn the car to the left. */
else if (GamePad.isLeftPressed()|| x > 6)
{
analogWrite(motorASpeedPin, 255);
analogWrite(motorBSpeedPin, 255);
digitalWrite(motorAPin1, HIGH);
digitalWrite(motorAPin2, LOW);
digitalWrite(motorBPin1, LOW);
digitalWrite(motorBPin2, HIGH);
digitalWrite(ledPin, HIGH);
}
/* If nothing is pressed stop all motors. */
else
{
analogWrite(motorASpeedPin, 0);
analogWrite(motorBSpeedPin, 0);
digitalWrite(ledPin, LOW);
}
}
4) Arduino Automatic Room Light Controller with Bidirectional
Visitor
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
Relay (generic)
× 1
× 1
Infrared Module
× 1
Adafruit Standard LCD - 16x2
White on Blue × 1
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
#include<LiquidCrystal.h>
LiquidCrystal lcd(13,12,11,10,9,8);
#define in 14
#define out 19
#define relay 2
int count=0;
void IN()
{
count++;
if(count>=10)
{
count=10;
}
lcd.clear();
lcd.print("Person In Room:");
lcd.setCursor(0,1);
lcd.print(count);
delay(1000);
}
void OUT()
{
count--;
if(count<=0)
{
count=0;
}
lcd.clear();
lcd.print("Person In Room:");
lcd.setCursor(0,1);
lcd.print(count);
delay(1000);
}
void setup()
{
lcd.begin(16,2);
lcd.print("Visitor Counter");
delay(2000);
pinMode(in, INPUT);
pinMode(out, INPUT);
pinMode(relay, OUTPUT);
lcd.clear();
lcd.print("Person In Room:");
lcd.setCursor(0,1);
lcd.print(count);
}
void loop()
{
if(digitalRead(in))
IN();
if(digitalRead(out))
OUT();
if(count<=0)
{
lcd.clear();
digitalWrite(relay, LOW);
lcd.clear();
lcd.print("Nobody In Room");
lcd.setCursor(0,1);
lcd.print("Light Is Off");
delay(200);
}
else
digitalWrite(relay, HIGH);
}
5) Arduino a Neonate Incubator Approach
Arduino Nano R3
× 1
Here you can see the place in which the air is warmed, a Lm35
temperature sensor is in the top of the box
This project will be divided in several small projects in order to explain
how to build each specific part that need special attention as the power
controller and the button controller.
SCHEMATICS
Simplified diagram
This diagram content the following:
1. 220V cable
2. Power source 220v to 24V @ 4A
3. Arduino Nano
4. I2C 20x4 LCD
5. Power controller for fans and warmer
6. 5-button control
7. Ceramic warmer
8. Lm 35 temperature sensor
9. DHT22 humidity and temperature sensor
10. 12V computer fan
11. Small servo motor.
12. Big plastic box
Arduino diagram
The Arduino connections to peripherals.
Power management
The two independent lines were made experimentally to check if the
helped to avoid some noises, but they did not :) So you can use just
one.
#include <LCD.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SimpleDHT.h>
#include "RTClib.h"
#include <dht.h>
#include <Servo.h>
Servo myservo;
//Digitals
const int pin1DHT22 = 2; //Sensor humedad 1
const int Warmer = 3; //Relay 3
const int Fan_1 = 6; //Relay 6 // Fan High
const int buzzer = 4; //Piezo sounder
const int button1 = 9;
const int button2 = 10;
const int button3 = 11;
const int button4 = 12;
const int button5 = 13;
//Analogs
const int inPinTh_1 = A1; //Termistor 2
const int tempPin_1 = A2; //lm35_1
const int tempPin_2 = A3; //lm35_2
SimpleDHT22 dht22_1;
RTC_DS1307 RTC;
void setup()
{
myservo.attach(1);
myservo.write(122); //Para flujo sobrecalentado
delay(250);
myservo.write(70); //Flujo normal
delay(250);
myservo.write(122);
delay(250);
myservo.write(70);
Wire.begin();
RTC.begin();
pinMode(Fan_1, OUTPUT);
pinMode(Warmer, OUTPUT);
pinMode(back, INPUT);
pinMode(next, INPUT);
pinMode(select, INPUT);
pinMode(up, INPUT);
pinMode(down, INPUT);
pinMode(buzzer, OUTPUT);
digitalWrite(buzzer, LOW);
digitalWrite(Fan_1, LOW);
digitalWrite(Warmer, LOW);
lcd.begin(20, 4); // initialize the lcd for 20 chars 4 lines and turn on backlight
lcd.backlight();
menuScreen_0();
menuScreen_1();
RTC.adjust(DateTime(__DATE__, __TIME__));
// Check to see if the RTC is keeping time. If it is, load the time from your computer.
if (! RTC.isrunning()) {
lcd.print("Change clock battery");
// This will reflect the time that your sketch was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
}
}
void loop()
{
currentMillis = millis();
buttonState();
switch (menuScreen) {
case 0:
menuScreen_UseAlarm();
break;
case 1:
menuScreen_SetAlarm();
break;
case 2:
menuScreen_Mode();
break;
case 3:
Screen_Auto_intro();
break;
case 4:
menuScreen_Temp();
break;
case 5:
Alarms();
currentMillis = millis();
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
Screen_Auto();
}
break;
case 6:
Alarms();
currentMillis = millis();
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
Screen_Manual();
}
break;
}
void mainScreen()
{
currentMillis_1 = millis();
lcd.setCursor(0, 0);
lcd.print("Baby T "); lcd.print(averageTemp(), 1); lcd.print((char)223); //lcd.print("C");
lcd.setCursor(13, 0);
lcd.print("WarmerT");
lcd.setCursor(0, 1);
lcd.print("Case T "); lcd.print(templm35_1(), 1); lcd.print((char)223); // Temp case lm35 1
lcd.setCursor(14, 1);
lcd.print(templm35_2(), 1); lcd.print((char)223); // Temp warmer lm35 2
lcd.setCursor(0, 2);
lcd.print("Cham T ");
if (currentMillis_1 - previousMillis_1 > interval_1) { // Importante para dar ciclo de espera
a los sensores de humidificacion
previousMillis_1 = currentMillis_1; lcd.print(DHT22TempRead_1(), 1);
lcd.print((char)223);
}
lcd.setCursor(0, 3);
lcd.print("Man. mode");
RelojParaPantallaSerial();
void RelojParaPantallaSerial()
{
DateTime now = RTC.now();
lcd.setCursor(12, 3);
if (now.hour() < 10 ) {
lcd.print("0");
lcd.print(now.hour(), DEC);
}
else {
lcd.print(now.hour(), DEC);
}
lcd.print(':');
if (now.minute() < 10) {
lcd.print("0");
lcd.print(now.minute(), DEC);
}
else {
lcd.print(now.minute(), DEC);
}
lcd.print(':');
if (now.second() < 10) {
lcd.print("0");
lcd.print(now.second());
}
else {
lcd.print(now.second(), DEC);
}
}
int DHT22TempRead_1()
{
DHT22Sensor_1();
return DHT22Temp_1;
}
float templm35_1()
{
float val2 = 0;
for (int i = 0; i < 5; i++) {
val2 = val2 + analogRead(tempPin_1);
delay(2);
}
lm35_1 = val2 / 5;
lm35_1 = mapf(lm35_1, 284.5, 323, 30, 37);
return lm35_1;
}
float templm35_2()
{
float val3 = 0;
for (int i = 0; i < 5; i++) {
val3 = val3 + analogRead(tempPin_2);
delay(2);
}
lm35_2 = val3 / 5;
lm35_2 = mapf(lm35_2, 284.5, 323, 30, 37);
return lm35_2;
}
double mapf(double x, double in_min, double in_max, double out_min, double out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
int int_templm35_1()
{
int intlm35_1 = templm35_1();
return intlm35_1;
}
int int_tempcase()
{
int int_templm35_1_0 = templm35_1() * 10;
return int_templm35_1_0;
}
int int_templm35_2()
{
int intlm35_2 = templm35_2();
return intlm35_2;
}
int int_templm35_2_0()
{
int int_templm35_2_0 = templm35_2() * 10;
return int_templm35_2_0;
}
////////////////////////////////////////////////////
void menuScreen_0 ()
{
lcd.setCursor(0, 1);
lcd.print(" The Baby Warmer.");
delay(1000);
lcd.setCursor(0, 3);
lcd.print("Welcome!");
delay(500);
lcd.setCursor(15, 3);
lcd.print("V 1.3");
delay(1000);
lcd.clear();
}
void menuScreen_1()
{
lcd.setCursor(0, 0);
lcd.print("The following menu");
lcd.setCursor(0, 1);
lcd.print("will help you to set");
lcd.setCursor(0, 2);
lcd.print("the incubator system");
delay(3000);
lcd.clear();
}
void menuScreen_UseAlarm()
{
switch (menuScreenUseAlarm) {
case 0:
lcd.setCursor(0, 0);
lcd.print("Activate neonate");
lcd.setCursor(0, 1);
lcd.print("temp. alarm?");
if (modeAlarm == 0) {
lcd.setCursor(0, 2);
lcd.print("->");
}
else if (modeAlarm == 1) {
lcd.setCursor(0, 3);
lcd.print("->");
}
lcd.setCursor(2, 2);
lcd.print("No");
lcd.setCursor(2, 3);
lcd.print("Yes");
if (back) {
back = 0;
}
else if (next) {
if (modeAlarm == 0) {
menuScreen = 2;
}
else if (modeAlarm == 1) {
menuScreen = 1;
}
lcd.clear();
delay(500);
next = 0;
}
else if (select) {
if (modeAlarm == 0) {
menuScreen = 2;
}
else if (modeAlarm == 1) {
menuScreen = 1;
}
lcd.clear();
delay(500);
select = 0;
}
else if (up) {
modeAlarm = modeAlarm - 1;
if (modeAlarm < 0) {
modeAlarm = 1;
}
delay(100);
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
up = 0;
}
else if (down) {
modeAlarm = modeAlarm + 1;
if (modeAlarm > 1) {
modeAlarm = 0;
}
delay(100);
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
down = 0;
}
break;
}
}
void menuScreen_SetAlarm()
{
switch (menuScreenTempAlarm) {
case 0:
lcd.setCursor(0, 0);
lcd.print("Set the upper range");
lcd.setCursor(0, 1);
lcd.print("T=");
lcd.setCursor(3, 1);
lcd.print(upperTempAlarm, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Press select to");
lcd.setCursor(0, 3);
lcd.print("continue...");
if (back) {
back = 0;
lcd.clear();
delay(500);
menuScreen = 0;
}
else if (next) {
lowerTempCompAlarm = upperTempAlarm - 0.5;
lowerTempAlarm = upperTempAlarm - 0.5;
menuScreenTempAlarm = 1;
lcd.clear();
delay(500);
next = 0;
}
else if (select) {
lowerTempCompAlarm = upperTempAlarm - 0.5;
lowerTempAlarm = upperTempAlarm - 0.5;
menuScreenTempAlarm = 1;
lcd.clear();
delay(500);
select = 0;
}
else if (up) {
if (int_upperTempAlarm() >= 375) {
upperTempAlarm = 37.5;
lcd.setCursor(9, 1);
lcd.print(" MAX TEMP");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
upperTempAlarm = upperTempAlarm + 0.1;
lcd.setCursor(3, 1);
lcd.print(upperTempAlarm, 1);
up = 0;
}
else if (down) {
if (int_upperTempAlarm() <= 320) {
upperTempAlarm = 32;
lcd.setCursor(10, 1);
lcd.print("MIN RANGE");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
upperTempAlarm = upperTempAlarm - 0.1;
lcd.setCursor(3, 1);
lcd.print(upperTempAlarm, 1);
down = 0;
}
break;
case 1:
lcd.setCursor(0, 0);
lcd.print("Set the lower range");
lcd.setCursor(0, 1);
lcd.print("T=");
lcd.setCursor(3, 1);
lcd.print(lowerTempAlarm, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Press select to");
lcd.setCursor(0, 3);
lcd.print("continue...");
if (back) {
menuScreenTempAlarm = 0;
lcd.clear();
delay(200);
back = 0;
}
else if (next) {
menuScreenTempAlarm = 2;
next = 0;
lcd.clear();
delay(500);
}
else if (select) {
menuScreenTempAlarm = 2;
select = 0;
lcd.clear();
delay(500);
}
else if (up) {
if (int_lowerTempAlarm() >= (int_upperTempAlarm() - 5)) {
lowerTempAlarm = lowerTempCompAlarm;
lcd.setCursor(9, 1);
lcd.print(" MIN RANGE");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
lowerTempAlarm = lowerTempAlarm + 0.1;
lcd.setCursor(3, 1);
lcd.print(lowerTempAlarm, 1);
up = 0;
}
else if (down) {
if (int_lowerTempAlarm() <= 280) {
lowerTempAlarm = 28;
lcd.setCursor(10, 1);
lcd.print("MIN TEMP");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
lowerTempAlarm = lowerTempAlarm - 0.1;
lcd.setCursor(3, 1);
lcd.print(lowerTempAlarm, 1);
down = 0;
}
break;
case 2:
lcd.setCursor(0, 0);
lcd.print("Upper limit: ");
lcd.setCursor(0, 1);
lcd.print("T=");
lcd.setCursor(3, 1);
lcd.print(upperTempAlarm, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Lower limit:");
lcd.setCursor(0, 3);
lcd.print("T=");
lcd.setCursor(3, 3);
lcd.print(lowerTempAlarm, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(9, 3);
lcd.print(" Continue?");
if (back) {
menuScreenTempAlarm = 1;
lcd.clear();
delay(200);
back = 0;
}
else if (next) {
menuScreen = 2;
next = 0;
lcd.clear();
delay(500);
}
else if (select) {
menuScreen = 2;
select = 0;
lcd.clear();
delay(500);
}
else if (up) {
up = 0;
}
else if (down) {
down = 0;
}
}
void menuScreen_Mode()
{
switch (menuScreenMode) {
case 0:
lcd.setCursor(0, 0);
lcd.print("Select the mode:");
if (mode == 0) {
lcd.setCursor(0, 2);
lcd.print("->");
}
else if (mode == 1) {
lcd.setCursor(0, 3);
lcd.print("->");
}
lcd.setCursor(2, 2);
lcd.print("Skin mode aut.");
lcd.setCursor(2, 3);
lcd.print("Temp setting man.");
if (back) {
back = 0;
lcd.clear();
delay(500);
menuScreenTempAlarm = 0;
menuScreen = 0;
}
else if (next) {
if (mode == 0) {
menuScreen = 3;
}
else if (mode == 1) {
menuScreen = 4;
}
lcd.clear();
delay(500);
next = 0;
}
else if (select) {
if (mode == 0) {
menuScreen = 3;
}
else if (mode == 1) {
menuScreen = 4;
}
lcd.clear();
delay(500);
select = 0;
}
else if (up) {
mode = mode - 1;
if (mode < 0) {
mode = 1;
}
delay(100);
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
up = 0;
}
else if (down) {
mode = mode + 1;
if (mode > 1) {
mode = 0;
}
delay(100);
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
down = 0;
}
break;
}
}
void Screen_Auto_intro()
{
lcd.setCursor(0, 0);
lcd.print("This mode will try");
lcd.setCursor(0, 1);
lcd.print("to stabilize the");
lcd.setCursor(0, 2);
lcd.print("neonate temperature");
lcd.setCursor(0, 3);
lcd.print("between 36.5 & 37.3");
delay(3000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("The supervision of");
lcd.setCursor(0, 1);
lcd.print("the neonate is ");
lcd.setCursor(0, 2);
lcd.print("mandatory at small");
lcd.setCursor(0, 3);
lcd.print("lapses. 5~10 mins");
delay(3000);
lcd.clear();
menuScreen = 5;
}
void menuScreen_Temp()
{
switch (menuScreenTemp) {
case 0:
lcd.setCursor(0, 0);
lcd.print("Set the upper range");
lcd.setCursor(0, 1);
lcd.print("T=");
lcd.setCursor(3, 1);
lcd.print(upperTemp, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Press select to");
lcd.setCursor(0, 3);
lcd.print("continue...");
if (back) {
back = 0;
menuScreen = 0;
}
else if (next) {
lowerTempComp = upperTemp - 1;
lowerTemp = upperTemp - 1;
menuScreenTemp = 1;
lcd.clear();
delay(500);
next = 0;
}
else if (select) {
lowerTempComp = upperTemp - 1;
lowerTemp = upperTemp - 1;
menuScreenTemp = 1;
lcd.clear();
delay(500);
select = 0;
}
else if (up) {
if (int_upperTemp() >= 370) {
upperTemp = 37;
lcd.setCursor(9, 1);
lcd.print(" MAX TEMP");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
upperTemp = upperTemp + 0.1;
lcd.setCursor(3, 1);
lcd.print(upperTemp, 1);
up = 0;
}
else if (down) {
if (int_upperTemp() <= 310) {
upperTemp = 31;
lcd.setCursor(10, 1);
lcd.print("MIN RANGE");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
upperTemp = upperTemp - 0.1;
lcd.setCursor(3, 1);
lcd.print(upperTemp, 1);
down = 0;
}
break;
case 1:
lcd.setCursor(0, 0);
lcd.print("Set the lower range");
lcd.setCursor(0, 1);
lcd.print("T=");
lcd.setCursor(3, 1);
lcd.print(lowerTemp, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Press select to");
lcd.setCursor(0, 3);
lcd.print("continue...");
if (back) {
menuScreenTemp = 0;
lcd.clear();
delay(200);
back = 0;
}
else if (next) {
menuScreenTemp = 2;
next = 0;
lcd.clear();
delay(500);
}
else if (select) {
menuScreenTemp = 2;
select = 0;
lcd.clear();
delay(500);
}
else if (up) {
if (int_lowerTemp() >= (int_upperTemp() - 10)) {
lowerTemp = lowerTempComp;
lcd.setCursor(9, 1);
lcd.print(" MIN RANGE");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
lowerTemp = lowerTemp + 0.1;
lcd.setCursor(3, 1);
lcd.print(lowerTemp, 1);
up = 0;
}
else if (down) {
if (int_lowerTemp() <= 300) {
lowerTemp = 30;
lcd.setCursor(10, 1);
lcd.print("MIN TEMP");
delay(1000);
lcd.setCursor(9, 1);
lcd.print(" ");
return;
}
lowerTemp = lowerTemp - 0.1;
lcd.setCursor(3, 1);
lcd.print(lowerTemp, 1);
down = 0;
}
break;
case 2:
lcd.setCursor(0, 0);
lcd.print("Upper limit: ");
lcd.setCursor(0, 1);
lcd.print("T=");
lcd.setCursor(3, 1);
lcd.print(upperTemp, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Lower limit:");
lcd.setCursor(0, 3);
lcd.print("T=");
lcd.setCursor(3, 3);
lcd.print(lowerTemp, 1);
lcd.print((char)223);
lcd.print("C");
lcd.setCursor(9, 3);
lcd.print(" Continue?");
if (back) {
menuScreenTemp = 1;
lcd.clear();
delay(200);
back = 0;
}
else if (next) {
menuScreen = 6;
next = 0;
lcd.clear();
delay(500);
}
else if (select) {
menuScreen = 6;
select = 0;
lcd.clear();
delay(500);
}
else if (up) {
up = 0;
}
else if (down) {
down = 0;
}
}
void Screen_Auto() {
Screen_Auto_S();
warmerParameters_Auto();
}
void Screen_Auto_S()
{
currentMillis_1 = millis();
lcd.setCursor(0, 0);
lcd.print("Baby T "); lcd.print(averageTemp(), 1); lcd.print((char)223); //lcd.print("C");
lcd.setCursor(13, 0);
lcd.print("WarmerT");
lcd.setCursor(0, 1);
lcd.print("Case T "); lcd.print(templm35_1(), 1); lcd.print((char)223); // Temp case lm35 1
lcd.setCursor(14, 1);
lcd.print(templm35_2(), 1); lcd.print((char)223); // Temp warmer lm35 2
lcd.setCursor(0, 2);
lcd.print("Purs Baby T ");
lcd.print("37.3"); lcd.print((char)223);
lcd.setCursor(0, 3);
lcd.print("Aut. mode");
RelojParaPantallaSerial();
void Screen_Manual()
{
mainScreen();
warmerParameters_Manual();
}
void warmerParameters_Auto()
{
switch (manualSettings) {
case 0:
if (int_tempcase() <= int_lowerTemp()) {
digitalWrite(Warmer, HIGH);
}
else if (int_tempcase() > int_lowerTemp()) {
manualSettings++;
digitalWrite(Warmer, LOW);
}
case 1:
if (int_tempcase() <= pursuedLowerT) {
digitalWrite(Warmer, HIGH);
delay(400);
digitalWrite(Warmer, LOW);
delay(300);
}
else if (int_tempcase() >= pursuedHigherT) {
digitalWrite(Warmer, LOW);
digitalWrite(Fan_1, HIGH);
myservo.write(122); //Para flujo sobrecalentado
delay(2500); //Variable de tiempo de enfriamiento, a
mas tiempo, mas frio
digitalWrite(Fan_1, LOW);
myservo.write(70);
delay(1000);
}
}
}
void warmerParameters_Manual()
{
switch (manualSettings) {
case 0:
if (int_tempcase() <= int_lowerTemp()) {
digitalWrite(Warmer, HIGH);
}
else if (int_tempcase() > int_lowerTemp()) {
manualSettings++;
digitalWrite(Warmer, LOW);
}
case 1:
if (int_tempcase() <= int_upperTemp()) {
digitalWrite(Warmer, HIGH);
delay(400);
digitalWrite(Warmer, LOW);
delay(300);
}
else if (int_tempcase() >= int_upperTemp()) {
digitalWrite(Warmer, LOW);
digitalWrite(Fan_1, HIGH);
myservo.write(122); //Para flujo sobrecalentado
delay(2500); //Variable de tiempo de enfriamiento, a
mas tiempo, mas frio
digitalWrite(Fan_1, LOW);
myservo.write(70);
delay(1000);
}
}
}
void Alarms()
{
if (modeAlarm == 1)
{
if (averageTemp() < lowerTempAlarm || averageTemp() > upperTempAlarm)
{
digitalWrite(buzzer, HIGH);
delay(150);
digitalWrite(buzzer, LOW);
delay(100);
}
}
else {
digitalWrite(buzzer, LOW);
}
}
void buttonState()
{
back = digitalRead(button1);
next = digitalRead(button2);
select = digitalRead(button3);
up = digitalRead(button4);
down = digitalRead(button5);
if (back == HIGH) {
delay(150);
}
if (next == HIGH) {
delay(150);
}
if (select == HIGH) {
delay(150);
}
if (up == HIGH) {
delay(150);
}
if (down == HIGH) {
delay(150);
}
}
int int_upperTemp()
{
int int_upperTemp = upperTemp * 10;
return int_upperTemp;
}
int int_lowerTemp()
{
int int_lowerTemp = lowerTemp * 10;
return int_lowerTemp;
}
int int_midleRangeTemp()
{
int int_midleRangeTemp = midleRangeTemp * 10;
return int_midleRangeTemp;
}
int int_coefWarmer()
{
int int_coefWarmer = coefWarmer * 10;
return int_coefWarmer;
}
int int_upperTempAlarm()
{
int int_upperTempAlarm = upperTempAlarm * 10;
return int_upperTempAlarm;
}
int int_lowerTempAlarm()
{
int int_lowerTempAlarm = lowerTempAlarm * 10;
return int_lowerTempAlarm;
}
6) Arduino Customizable Geiger Muller Counter
COMPONENTS AND SUPPLIES
I have an Arduino uno cited here as what I used, but you could
probably save space in a container by using a nano. I used electrical
tape to attach the GM tube to the circuit board to save space as well as
to cover the terminals on the voltage transformer to improve safety. As
I have limited equipment to play around and drill holes with a plastic
container to make something pretty like what AdNovea had, I used the
cardboard box that I was given when I first purchased my Arduino
circuit kit.
I did cut a hole in the top of the box so the LED display could fit
snugly in there (and I further reinforced this with tape).
I also cut a hole in the side of the box to permit a USB cord to come in
and power the device.
I attempted 9V batteries to start, but as expected, the batteries did not
last long. Finally I put additional electric tape around the box/circuit
board as needed at points where the circuit may come in contact with
the cardboard to protect against fire and losing signal.
The program I have designed for my project takes the counts collected
by the GM tube every 30 seconds multiplied by 2 to provide an
estimated counts per minute (measuring unit of GM tubes). I then used
metric system conversions to report uSv/hr that is a more widely used
reference measurement. As the device continues to run through this
code, I had it report the average of the measurements that progressively
were collected along with the standard error (SD / sqrt(n)). Statistically
I chose standard error as ultimately what is collected is a sample from
the mean background radiation levels making SE the more appropriate
measure. Unfortunately due to the memory limitations of the Arduino, I
was only able to create an array of measurements of 100 items
SCHEMATICS
CODE
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
Serial.println("Avg: " + String(averageCPM) + " +/- " + String(sdCPM) + " ArrayVal: " +
String(CPMArray[currentCPM]));
currentCPM = currentCPM + 1;
displayAverageCPM();
}
}
void impulse() {
counts++;
}
void displayAverageCPM() {
lcd.setCursor(0,1);
lcd.print("Avg: ");
lcd.print(outputSieverts(averageCPM));
lcd.print("+/-");
lcd.print(outputSieverts(sdCPM));
}
float outputSieverts(float x) {
float y = x * 0.0057;
return y;
}
7) Arduino WKR1000 Weather Station
× 1
Sharp GP2Y1010AU0F
× 1
Breadboard (generic)
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
myDevices Cayenne
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_BMP085_U.h>
#include <Adafruit_TSL2561_U.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#define BAROMETER_PIN V1
#define TEMPERATURE_PIN V2
#define LIGHT_PIN V3
#define DUST_PIN V4
#define MOISTURE_PIN V5
float temperature;
float pressure;
float voltage;
int moisture;
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "Username";
char password[] = "Password";
char clientID[] = "ClientID";
unsigned long lastMillis = 0;
void setup()
{
Serial.begin(9600);
Cayenne.begin(username, password, clientID, ssid, wifiPassword);
pinMode(ledPin,OUTPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
if (!bmp.begin())
{
CAYENNE_LOG("No BMP sensor detected");
while (1);
}
if (!tsl.begin())
{
CAYENNE_LOG("No TSL2561 detected");
while (1);
}
tsl.enableAutoRange(true);
/* Changing the integration time gives you better sensor resolution (402ms = 16-bit data) */
tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low
resolution */
// tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution
and speed */
// tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); /* 16-bit data but
slowest conversions */
}
void loop()
{
Cayenne.loop();
//Publish data every 10 seconds (10000 milliseconds). Change this value to publish at a
different interval.
if (millis() - lastMillis > 10000) {
lastMillis = millis();
//Write data to Cayenne here. This example just sends the current uptime in milliseconds.
Cayenne.virtualWrite(0, lastMillis);
sensors_event_t event;
tsl.getEvent(&event);
bmp.getPressure(&pressure);
bmp.getTemperature(&temperature);
digitalWrite(ledPin,LOW);
delayMicroseconds(timeMeasuring);
voltageAnalog = analogRead(measuringPin);
delayMicroseconds(timeStabilization);
digitalWrite(ledPin,HIGH);
delayMicroseconds(timeSleep);
moisture = analogRead(A2);
Cayenne.luxWrite(LIGHT_PIN, event.light);
Cayenne.hectoPascalWrite(BAROMETER_PIN, pressure);
Cayenne.celsiusWrite(TEMPERATURE_PIN, temperature);
Cayenne.virtualWrite(DUST_PIN, dustiness);
Cayenne.virtualWrite(MOISTURE_PIN, map(moisture, 1023, 0, 0, 100));
}
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0, 0);
display.println(temperature);
display.setCursor(40, 0);
display.println("C");
display.setCursor(0, 10);
display.println(pressure);
display.setCursor(55, 10);
display.println("Pa");
display.setCursor(0, 20);
display.println(dustiness);
display.setCursor(45, 20);
display.println("ug/m3");
display.display();
}
8) Arduino Due TIC TAC TOE with Touchscreen
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
About
Hello, I want to share my work on the project from
nickthegreek82: arduino-touch-tic-tac-toe-game.
You need:
the Adafruit Library
the GFX Library
and the URTouch Library
Wiring
The wiring is as following for the touch-screen:
Touch -> Arduino Due
T_IRQ -> 22
T_DO -> 24
T_DIN -> 26
T_CS -> 28
T_CLK -> 30
For the display:
Display -> Arduino Due
SDO -> A.25
LED -> 3.3V
SCK -> A.27
SDI -> A.26
DC -> 9
RESET -> 8
CS -> 10
GND -> GND
VCC -> 3.3V
SCHEMATICS
CODE
/////////////////////////////////////////////
// 2.8" TOUCH SCREEN TIC TAC TOE //
// //
// //
// //
// //
/////////////////////////////////////////////
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <URTouch.h>
#define TFT_RST 8
#define TFT_DC 9
#define TFT_CS 10
#define TOUCH_ORIENTATION LANDSCAPE
Adafruit_GFX_Button buttons[9];
void setup()
{
myTouch.InitTouch();
myTouch.setPrecision(PREC_HI);
tft.begin();
tft.setRotation(3);
}
void loop()
{
int board[9] = {0,0,0,0,0,0,0,0,0};
drawStartScreen();
do{
myTouch.read();
x = myTouch.getX(); //Get touch point
y = myTouch.getY();
delay(100);
}while(!(buttons[0].contains(x,y)));
tft.fillScreen(BLACK);
//Draw white frame
tft.drawRect(0,0,320,240,WHITE);
//Print "Tic Tac Toe" Text
tft.setCursor(30,30);
tft.setTextColor(WHITE);
tft.setTextSize(4);
tft.print("Tic Tac Toe");
//Print "YouTube!" text
tft.setCursor(30,100);
tft.setTextColor(GREEN);
tft.setTextSize(4);
tft.print("Who begins");
//Create Red Button
// create buttons // x, y, w, h, outline, fill, text
buttons[0].initButton(&tft, 100,200,80,40,WHITE, RED, WHITE,
you, 2);
buttons[0].drawButton();
// create buttons // x, y, w, h, outline, fill, text
buttons[1].initButton(&tft, 200,200,80,40,WHITE, RED, WHITE,
cpu, 2);
buttons[1].drawButton();
b=1;
do{
myTouch.read();
x = myTouch.getX(); //Get touch point
y = myTouch.getY();
if (buttons[0].contains(x,y))
{
b=0;
player = 1;
tft.fillScreen(BLACK);
//Draw white frame
tft.drawRect(0,0,320,240,WHITE);
tft.setCursor(30,30);
tft.setTextColor(WHITE);
tft.setTextSize(2);
tft.print("Ok, you begin.");
delay(2000);
}
if(buttons[1].contains(x,y))
{
b=0;
player = 2;
tft.fillScreen(BLACK);
//Draw white frame
tft.drawRect(0,0,320,240,WHITE);
tft.setCursor(30,30);
tft.setTextColor(WHITE);
tft.setTextSize(2);
tft.print("Ok, CPU begins.");
delay(2000);
}
}while(b);
tft.fillScreen(BLACK);
tft.drawRect(0,0,319,240,WHITE);
drawVerticalLine(125);
drawVerticalLine(195);
drawHorizontalLine(80);
drawHorizontalLine(150);
void drawVerticalLine(int x)
{
int i=0;
for(i=0;i<7;i++)
{
tft.drawLine(x+i,20,x+i,220,WHITE);
}
}
void drawStartScreen()
{
tft.fillScreen(BLACK);
int16_t i, j, byteWidth = (w + 7) / 8;
uint8_t byte;
if(board[1]==0)
{
move=1;
b=0;
}
}
else if((x>195&&x<265)&& (y>0 && y<80)) //2
{
if(board[2]==0)
{
move=2;
b=0;
}
}
}
}while(b);
board[move] = -1;
drawPlayerMove(move);
delay(100);
}
int win(const int board[9]) {
//list of possible winning positions
unsigned wins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
int winPos;
for(winPos = 0; winPos < 8; ++winPos) {
if(board[wins[winPos][0]] != 0 && board[wins[winPos][0]] == board[wins[winPos][1]]
&& board[wins[winPos][0]] == board[wins[winPos][2]])
return board[wins[winPos][2]];
}
return 0;
}
if(board[i] == 0) {
board[i] = player;
int thisScore=0;
if (depth<difficulty){
thisScore = -minimax(board, player*-1,depth+1);
}
× 1
OLED 128X64
× 1
× 1
USB-A to B Cable
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Code
Then open Arduino IDE and copy and paste the next code:
#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /*
clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All
Boards without Reset of the Display
int a=0; //variable of value of analog read pin
char taco[4];//variable to send text to the oled display
void setup(void) {
u8g2.begin();// Oled display begins
}
void loop(void) {
a=analogRead(A0); //read potentiometer value
sprintf(taco,"%04d",a); //convert potentiometer value to string
u8g2.clearBuffer(); // clear the internal memory
u8g2.setFont(u8g2_font_inr38_mf); // choose a suitable font
u8g2.drawStr(0,60,taco); // write something to the internal memory
u8g2.sendBuffer(); // transfer internal memory to the display
delay(1000);
For everything to work we must download the library u8g2.
After uploading the code, and having connected the potentiometer to the
Arduino plate, the value of the potentiometer can be seen in the display,
from 0 to 1023, as shown below.
SCHEMATICS
CODE
#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
void loop(void) {
a=analogRead(A0); //read potentiometer value
sprintf(taco,"%04d",a); //convert potentiometer value to string
u8g2.clearBuffer(); // clear the internal memory
u8g2.setFont(u8g2_font_inr38_mf); // choose a suitable font
u8g2.drawStr(0,60,taco); // write something to the internal memory
u8g2.sendBuffer(); // transfer internal memory to the
display
delay(1000);
}
× 2
× 2
× 1
× 1
× 21
× 1
Breadboard (generic)
× 1
× 1
NECESSARY TOOLS AND MACHINES
Arduino Materia 101
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int switchPin = 6;
int switchState = 0;
//declaring the variable for the switch
int reply;
void setup() {
pinMode(0, INPUT);
//power source for switch
lcd.begin(16, 2);
pinMode(switchPin, INPUT);
lcd.print("Ask the Magic");
lcd.setCursor(0,1);
lcd.print("8 ball!");
//welcome message
}
void loop(){
switchState = digitalRead(switchPin);
{
if(switchState == HIGH){
//when the switch is pressed
reply = random(8);
//return a random case
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("");
lcd.setCursor(0,1);
switch(reply){
case 0:
lcd.begin(16, 2);
lcd.print("It is");
lcd.setCursor(0,1);
lcd.print("certain :)");
delay (2500);
//maintain the first message
lcd.clear();
//clear the first message
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
//print the second message
break;
//next case
case 1:
lcd.begin(16, 2);
lcd.print("As I see it,");
lcd.setCursor(0,1);
lcd.print("yes :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 2:
lcd.begin(16, 2);
lcd.print("Reply hazy");
lcd.setCursor(0,1);
lcd.print("try again :/");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 3:
lcd.begin(16, 2);
lcd.print("Don't count");
lcd.setCursor(0,1);
lcd.print("on it :(");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 4:
lcd.begin(16, 2);
lcd.print("It is");
lcd.setCursor(0,1);
lcd.print("decidedly so :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 5:
lcd.begin(16, 2);
lcd.print("Most");
lcd.setCursor(0,1);
lcd.print("likely :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 6:
lcd.begin(16, 2);
lcd.print("Ask again");
lcd.setCursor(0,1);
lcd.print("later :/");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 7:
lcd.begin(16, 2);
lcd.print("My reply is");
lcd.setCursor(0,1);
lcd.print("no :(");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 8:
lcd.begin(16, 2);
lcd.print("Without a");
lcd.setCursor(0,1);
lcd.print("doubt :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 9:
lcd.begin(16, 2);
lcd.print("Outlook good :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 10:
lcd.begin(16, 2);
lcd.print("Better not tell");
lcd.setCursor(0,1);
lcd.print("you now :/");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 11:
lcd.begin(16, 2);
lcd.print("My sources");
lcd.setCursor(0,1);
lcd.print("say no :(");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 12:
lcd.begin(16, 2);
lcd.print("Yes");
lcd.setCursor(0,1);
lcd.print("definitely :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 13:
lcd.begin(16, 2);
lcd.print("Yes :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 14:
lcd.begin(16, 2);
lcd.print("Cannot");
lcd.setCursor(0,1);
lcd.print("predict now :/");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 15:
lcd.begin(16, 2);
lcd.print("Outlook not");
lcd.setCursor(0,1);
lcd.print("so good :(");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 16:
lcd.begin(16, 2);
lcd.print("You may rely");
lcd.setCursor(0,1);
lcd.print("on it :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 17:
lcd.begin(16, 2);
lcd.print("Signs point");
lcd.setCursor(0,1);
lcd.print("to yes :)");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 18:
lcd.begin(16, 2);
lcd.print("Concentrate and");
lcd.setCursor(0,1);
lcd.print("ask again :/");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
case 19:
lcd.begin(16, 2);
lcd.print("Very");
lcd.setCursor(0,1);
lcd.print("doubtful :(");
delay (2500);
lcd.clear();
lcd.print("Ask another");
lcd.setCursor(0,1);
lcd.print("question!");
break;
}
}
}
}
11) Arduino Calculator
× 1
RGB LCD Shield Kit, 16x2
Character Display × 1
× 1
9V battery (generic)
× 1
Breadboard (generic)
× 1
At the end of this project you will know how to use a 16x2 LCD and
Keypad with Arduino and also how easy it is to program for them using
the readily available libraries. You will also understand how to program
your Arduino for accomplishing a particular task.
Materials Required:
Arduino Uno (Any version will work)
16×2 LCD Display
4×4 Keypad
9V Battery
Breadboard and Connecting wires
D0
1st pin of the keyboard
D1
2nd pin of the keyboard
D2
3rd pin of the keyboard
D3
4th pin of the keyboard
D4
5th pin of the keyboard
D5
6th pin of the keyboard
D6
7th pin of the keyboard
D7
8th pin of the keyboard
D8
Register select pin of LCD (pin 4)
D9
Enable pin of LCD (pin 6)
D10
Data pin 4 (pin 11)
D11
Data pin 4 (pin 11)
D12
Data pin 4 (pin 11)
D13
Data pin 4 (pin 11)
+5V
Connected to Vdd pin of LCD (pin 2)
Ground
Connected to Vss, Vee and RW pin of LCD (pin 1, 3 and 5)
Some Arduino boards might show an error while uploading program if
there are anything connected to pin 0 and pin1, so if you experience any
just remove the keypad while uploading the program.
Once your connections are done your hardware will look something like
this below
SCHEMATICS
CODE
*
* Arduino Keypad calculator Program
*/
{'7','8','9','D'},
{'4','5','6','C'},
{'1','2','3','B'},
{'*','0','#','A'}
};
byte rowPins[ROWS] = { 0, 1, 2, 3 };// Connect keypad ROW0, ROW1, ROW2 and ROW3
to these Arduino pins.
byte colPins[COLS] = { 4, 5, 6, 7 }; // Connect keypad COL0, COL1 and COL2 to these
Arduino pins.
long Num1,Num2,Number;
char key,action;
boolean result = false;
void setup() {
lcd.begin(16, 2); //We are using a 16*2 LCD display
lcd.print("DIY Calculator"); //Display a intro message
lcd.setCursor(0, 1); // set the cursor to column 0, line 1
lcd.print("-CircuitDigest"); //Display a intro message
void loop() {
if (key!=NO_KEY)
DetectButtons();
if (result==true)
CalculateResult();
DisplayResult();
}
void DetectButtons()
{
lcd.clear(); //Then clean it
if (key=='*') //If cancel Button is pressed
{Serial.println ("Button Cancel"); Number=Num1=Num2=0; result=false;}
if (key == '0')
{Serial.println ("Button 0"); //Button 0 is Pressed
if (Number==0)
Number=0;
else
Number = (Number*10) + 0; //Pressed twice
}
if (key == '5')
{Serial.println ("Button 5");
if (Number==0)
Number=5;
else
Number = (Number*10) + 5; //Pressed twice
}
if (key == '8')
{Serial.println ("Button 8");
if (Number==0)
Number=8;
else
Number = (Number*10) + 8; //Pressed twice
}
if (key == '#')
{Serial.println ("Button Equal");
Num2=Number;
result = true;
}
if (key == '3')
{Serial.println ("Button 3");
if (Number==0)
Number=3;
else
Number = (Number*10) + 3; //Pressed twice
}
if (key == '6')
{Serial.println ("Button 6");
if (Number==0)
Number=6;
else
Number = (Number*10) + 6; //Pressed twice
}
if (key == '9')
{Serial.println ("Button 9");
if (Number==0)
Number=9;
else
Number = (Number*10) + 9; //Pressed twice
}
if (key == 'A' || key == 'B' || key == 'C' || key == 'D') //Detecting Buttons on Column 4
{
Num1 = Number;
Number =0;
if (key == 'A')
{Serial.println ("Addition"); action = '+';}
if (key == 'B')
{Serial.println ("Subtraction"); action = '-'; }
if (key == 'C')
{Serial.println ("Multiplication"); action = '*';}
if (key == 'D')
{Serial.println ("Devesion"); action = '/';}
delay(100);
}
void CalculateResult()
{
if (action=='+')
Number = Num1+Num2;
if (action=='-')
Number = Num1-Num2;
if (action=='*')
Number = Num1*Num2;
if (action=='/')
Number = Num1/Num2;
}
void DisplayResult()
{
lcd.setCursor(0, 0); // set the cursor to column 0, line 1
lcd.print(Num1); lcd.print(action); lcd.print(Num2);
if (result==true)
{lcd.print(" ="); lcd.print(Number);} //Display the result
× 1
Atlas Scientific Gravity™ Analog
pH Sensor
× 1
158x90x60mm enclosure
× 1
Mini breadboard
× 1
× 1
Resistor 1k ohm
× 1
Datasheets
Gravity pH sensor, pH probe
Step 4: Finalize Assembly
After the wiring has been completed:
a) Put the top and bottom portions of the housing together using the
provided screws.
b) Connect the probe to the BNC connector.
Step 5: Upload Code Onto Arduino Uno
The code for this project makes use of customized libraries and header
files. You will have to add them to your Arduino IDE to use the code.
The steps below include the process of making this addition to the IDE.
a) Connect the Arduino to your computer and open the IDE. The IDE
can be downloaded from this LINK if you do not have it. Go to Tools -
> Board -> Select Arduino/Genuino Uno. Go to Tools -> Port -> select
the port where the Arduino is connected to.
b) Add Liquid Crystal Display library: In the IDE go to Sketch ->
Include library -> Manage libraries. In the search bar of the Library
Manager enter "liquidcrystal". Look for the package titled
"LiquidCrystal Built-in by Arduino, Adafruit". It may or may not be
installed. If not, select the package and click on install.
c) Add Atlas Gravity sensor library: Download the zip file from the
following LINK. The file will be saved as "Atlas_gravity.zip". In the
IDE go to Sketch -> Include library -> Add.ZIP Library. Locate the
"Atlas_gravity.zip" file and select to add.
d) Next, we have to add the code for the pH meter. Copy the code from
this LINK onto the IDE work panel.
e) Compile and upload the code to the Arduino.
f) The pH readings will then be displayed on the LCD. You can also
view the readings on the serial monitor. To open the serial monitor, go
to Tools -> Serial Monitor or press Ctrl+Shift+M on your keyboard. Set
the baud rate to 9600 and select "Carriage return".
Step 6: Calibrate pH Sensor
Note: If you plan on using an external power supply for the Arduino,
connect it to the Arduino before doing the calibration. This will ensure
that the reference levels are appropriately set, which will aid in the
correct calibration.
This pH meter can be calibrated to one, two or three-points calibration.
Standard buffer solutions (pH 4, 7 and 10) are required
The serial monitor is used for the calibration process. The user will be
able to observe the gradual change in readings as they come to
stabilization and send the appropriate commands.
Calibration data are stored in the EEPROM of the Arduino.
Calibration commands
Low-point: cal, 4
Mid-point: cal, 7
High-point: cal, 10
Clear calibration: cal, clear
Steps
a) Remove the soaker bottle and rinse off the pH probe.
b) Pour some of the pH 4 solution into a cup. Ensure that there is
enough to cover the sensing area of the probe.
c) Place the probe in the cup and stir it around to remove trapped air.
Observe the readings on the serial monitor. Let the probe sit in the
solution until the readings stabilize (small movement from one reading
to the next is normal)
d) After the readings stabilize, enter the command cal, 4 into the serial
monitor. Calibration to pH 4 is now complete.
Repeat steps a-d for pH7 and pH10. Remember to rinse the probe as
you proceed to different buffer solutions.
What about temperature compensation?
The sensor used in this project has an accuracy of +/- 0.2%. The pH
meter will operate within this accuracy in the temperature range of 7 -
46°C. Outside of this range, the meter will have to be modified for
temp compensation. Note: The pH probe can be subjected to a range of
1 − 60 °C.
SCHEMATICS
CODE
/*
Once uploaded, open the serial monitor, set the baud rate to 9600 and append "Carriage
return"
The code allows the user to observe real time pH readings as well as calibrate the sensor.
One, two or three-point calibration can be done.
Calibration commands:
low-point: "cal,4"
mid-point: "cal,7"
high-point: "cal,10"
clear calibration: "cal,clear"
*/
String inputstring = ""; //a string to hold incoming data from the PC
boolean input_string_complete = false; //a flag to indicate have we received all
the data from the PC
char inputstring_array[10]; //a char array needed for string parsing
Gravity_pH pH = A0; //assign analog pin A0 of Arduino to class
Gravity_pH. connect output of pH sensor to pin A0
LiquidCrystal pH_lcd(2, 3, 4, 5, 6, 7); //make a variable pH_lcd and assign
arduino digital pins to lcd pins (2 -> RS, 3 -> E, 4 to 7 -> D4 to D7)
void setup() {
Serial.begin(9600); //enable serial port
pH_lcd.begin(20, 4); //start lcd interface and define lcd size (20
columns and 4 rows)
pH_lcd.setCursor(0,0); //place cursor on screen at column 1, row 1
pH_lcd.print("--------------------"); //display characters
pH_lcd.setCursor(0,3); //place cursor on screen at column 1, row 4
pH_lcd.print("--------------------"); //display characters
pH_lcd.setCursor(5, 1); //place cursor on screen at column 6, row 2
pH_lcd.print("pH Reading"); //display "pH Reading"
if (pH.begin()) { Serial.println("Loaded EEPROM");}
Serial.println(F("Use commands \"CAL,4\", \"CAL,7\", and \"CAL,10\" to calibrate the
circuit to those respective values"));
Serial.println(F("Use command \"CAL,CLEAR\" to clear the calibration"));
}
void loop() {
× 2
× 2
× 1
× 2
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
This is how it looks. The BIG button is a hit button and the small red
one on top is "start"
I was able to shrink the system and program only an Atmega328P chip.
Runs on 3 AAA.
Press Start
Round 1 of 5
Round 2 of 5
Average result calculation and showing. The "verdict"
Please do not hesitate to ask me questions if needed.
SCHEMATICS
CODE
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define btnSTART 5
#define btnHIT 7
#define ledTrigger 9
LiquidCrystal_I2C lcd(0x23,20,4);
void setup() {
lcd.init();
lcd.backlight();
pinMode(btnSTART, INPUT_PULLUP);
pinMode(btnHIT, INPUT_PULLUP);
pinMode(ledTrigger, OUTPUT);
digitalWrite(ledTrigger, LOW);
lcd.print("Salut Famille!");
delay(2000);
lcd.clear();
randomSeed(analogRead(0));
}
void loop() {
long timeReaction;
long timeTotal = 0;
lcd.print("Press START!");
while (digitalRead(btnSTART)) {}
delay(10);
while (!digitalRead(btnSTART)) {}
lcd.clear();
lcd.print("Jouez!!!");
delay(1000);
for (int i = 0; i < 5; i++) {
delay(random(500, 5000));
timeReaction = millis();
digitalWrite(ledTrigger, HIGH);
while (digitalRead(btnHIT)) {}
timeReaction = millis() - timeReaction;
timeTotal += timeReaction;
delay(10);
while (!digitalRead(btnHIT)) {}
digitalWrite(ledTrigger, LOW);
lcd.clear();
lcd.print(i + 1);
lcd.print(": ");
lcd.print(timeReaction);
delay(1000);
}
lcd.clear();
lcd.print("Moyenne = ");
lcd.print(timeTotal/5);
delay(10000);
lcd.clear();
}
14) Arduino Quizmo
× 1
Adafruit Standard LCD - 16x2
White on Blue
× 1
#include <Keypad.h>
#include <LiquidCrystal.h>
long rand1,rand2,ans,ans1,opr,score,total;
char selec,selec1;
boolean quiz=false;
String stringTwo;
void setup(){
lcd.begin(16, 2);
mk_menu();
keypad.addEventListener(keypadEvent);
}
void loop(){
selec = keypad.getKey();
while (selec==NO_KEY){
selec = keypad.getKey();
}
lcd.print(selec);
delay(500);
if (selec!=NO_KEY){
switch(selec){
case '1':
quiz=true;
opr=1;
quiz_sum();
break;
case '2':
quiz=true;
opr=2;
quiz_subt();
break;
case '3':
quiz=true;
opr=3;
quiz_mult();
break;
}
}
}
void mk_menu(){
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("1)+ 2)- 3)x");
lcd.setCursor(0, 1);
lcd.print("Choose: ");
}
void quiz_sum(){
lcd.clear();
lcd.setCursor(0, 0);
rand1=random(1,99);
rand2=random(1,99);
lcd.print("Find ");
lcd.print(rand1);
lcd.print("+");
lcd.print(rand2);
lcd.print("?");
ans1=rand1+rand2;
selec1 = keypad.getKey();
while (selec1==NO_KEY){
selec1 = keypad.getKey();
}
while (quiz){
while (selec1==NO_KEY){
selec1 = keypad.getKey();
}
switch(selec1){
case NO_KEY:
break;
default:
lcd.print(selec1);
stringTwo.concat(selec1);
ans=stringTwo.toInt();
//lcd.print(stringTwo);
selec1=NO_KEY;
break;
}
}
}
void quiz_subt(){
lcd.clear();
lcd.setCursor(0, 0);
rand1=random(1,99);
rand2=random(1,99);
lcd.print("Find ");
if(rand1>=rand2){
lcd.print(rand1);
lcd.print("-");
lcd.print(rand2);
ans1=rand1-rand2;
}
else if(rand1<rand2){
lcd.print(rand2);
lcd.print("-");
lcd.print(rand1);
ans1=rand2-rand1;
}
lcd.print("?");
selec1 = keypad.getKey();
while (selec1==NO_KEY){
selec1 = keypad.getKey();
}
while (quiz){
while (selec1==NO_KEY){
selec1 = keypad.getKey();
}
switch(selec1){
case NO_KEY:
break;
default:
lcd.print(selec1);
stringTwo.concat(selec1);
ans=stringTwo.toInt();
//lcd.print(stringTwo);
selec1=NO_KEY;
break;
}
}
}
void quiz_mult(){
lcd.clear();
lcd.setCursor(0, 0);
rand1=random(1,12);
rand2=random(1,12);
lcd.print("Find ");
lcd.print(rand1);
lcd.print("x");
lcd.print(rand2);
lcd.print("?");
ans1=rand1*rand2;
selec1 = keypad.getKey();
while (selec1==NO_KEY){
selec1 = keypad.getKey();
}
while (quiz){
while (selec1==NO_KEY){
selec1 = keypad.getKey();
}
switch(selec1){
case NO_KEY:
break;
default:
lcd.print(selec1);
stringTwo.concat(selec1);
ans=stringTwo.toInt();
//lcd.print(stringTwo);
selec1=NO_KEY;
break;
}
}
}
void chk_ans(){
lcd.clear();
if (ans1==ans){
lcd.clear();
lcd.print("Correct");
score=score+1;
}
else {
lcd.clear();
lcd.print("Incorrect");
}
}
void keypadEvent(KeypadEvent key){
switch (keypad.getState()){
case PRESSED:
if (key == '*') {
chk_ans();
total=total+1;
stringTwo="";
delay(400);
if(opr==1){
quiz_sum();
}
else if(opr==2){
quiz_subt();
}
else if(opr==3){
quiz_mult();
}
}
else if (key == '#') {
quiz=false;
stringTwo="";
lcd.clear();
lcd.print("Your Score: ");
lcd.print(score);
lcd.print("/");
lcd.print(total);
delay(1500);
score=0;
total=0;
mk_menu();
loop();
}
break;
}
}
15) Arduino Model Train Control
LED white
× 2
Photo resistor
× 2
× 2
× 2
Like many people, my wish is a nice model train, therefore I made a nice
layout plan, bought a starter set, made a table etc. It takes a long time, of
course, to build a complicated layout and in the meantime you want to
(test)ride on the track you have so far.
You can of course do so just with your transformer, but if you do not pay
attention you drive off the track. And model trains are fragile, a drop on
the floor will do damage. So the plan is a back and forth automation.
Something like this: Arduino-railroad.
All due respect to the maker but if you pop each time against a fence and
reverse the motor directly, it will damage the train or the gear at some
time.
I figured two gates with an LED and an LDR will sense the train.
SCHEMATICS
CODE
/*
Train control
This code is developed to "test" drive
a model train between two gates made of a LED and LDR.
Parts required:
1 - arduino uno/mega or compatible
1 - arduino motor shield R3
2 - Led brite white (5mm)
2 - Ldr (A 9013 photo resistor 5mm)
2 - 10K resistor
2 - 220 Ohm resistor
1 - model train
int sensLreading = 0; // declare variable and set value for left sensor
reading
int sensRreading = 0; // declare variable and set value for right sensor
reading
int max_Speed = 200; // declare variable and set value for maximum Speed
(0 to 255)
int Speed = 0; // declare variable and set value for current Speed (0 to
255)
boolean direct = HIGH; // declare variable and set value for direction to
HIGH (HIGH = left)
//========================================
void setup() {
Serial.begin(9600);
}
//========================================
void loop() {
case STATE_ACCELERATE:
Accelerate();
break;
case STATE_DECELERATE:
Decelerate();
break;
case STATE_TURN:
Turn();
break;
case STATE_RUN:
break;
}
}
//========================================
void read_sens() {
if (sensLreading > 200 && direct == HIGH) { // if conditions are throu, the
train reached left gate***
digitalWrite(led_L_Pin, LOW); // turn left LED off
digitalWrite(led_R_Pin, HIGH); // turn right LED on
state = STATE_DECELERATE; // set state to "decelerate"
previous_Dec_Millis = currentMillis; // set previous_Dec_Millis to
current time
}
if (sensRreading > 200 && direct == LOW) { // if conditions are throu, the
train reached right gate***
digitalWrite(led_R_Pin, LOW); // turn right LED off
digitalWrite(led_L_Pin, HIGH); // turn left LED on
state = STATE_DECELERATE; // set state to "decelerate"
previous_Dec_Millis = currentMillis; // set previous_Dec_Millis to
current time
}
}
}
//========================================
void Start() {
void Accelerate() {
void Decelerate() {
void Turn() {
On the motor shaft you find the card that is attached Arduino control unit
"MEGA 2650".
On the Arduino Mega little need to connect shield with RGB LEDs.
Shield with RGB LEDs containing 10 LEDs which is connected to a GND
pins are distributed across the board to the contacts that go to pins 24 to 52
in the Arduino Mega
Coupled looks like
SCHEMATICS
CODE
val=analogRead(StartPin);
}
}
void A(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,0,0,0,0,0,0,0);
signal(1,0,1,1,1,1,1,1,1);
signal(0,1,1,1,0,1,1,1,1);
signal(0,1,1,1,0,1,1,1,1);
signal(1,0,1,1,0,1,1,1,1);
signal(1,1,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void B(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,0,0,0,1);
signal(0,0,0,0,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void C(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(1,0,0,0,0,0,0,0,1);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void D(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,0,0,0,0,0,1,1);
signal(1,0,1,1,1,1,1,0,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void E(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void Fa(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(0,1,1,0,1,1,1,1,1);
signal(0,1,1,0,1,1,1,1,1);
signal(0,1,1,0,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void G(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,0,1,1,1);
signal(1,0,1,1,1,0,0,0,1);
signal(0,1,1,1,1,0,1,1,0);
signal(0,1,1,1,1,0,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(1,0,0,0,0,0,0,0,1);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void H(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,0,0,1,1,1,1);
signal(1,1,1,0,0,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void I(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void J(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,0,0,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void K(){//LOW=1 HIGH=0
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,1,1,1,0,0,0);
signal(1,1,1,0,1,0,1,1,1);
signal(1,1,1,1,0,1,1,1,1);
signal(1,1,1,1,0,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void L(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void M(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(1,0,0,0,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void N(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,1,0,1,1);
signal(1,1,1,1,1,0,1,1,1);
signal(1,1,1,1,0,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void O(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void P(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,1,1,1,1);
signal(0,1,1,1,1,0,1,1,1);
signal(0,1,1,1,1,0,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void R(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,0,0,0,0,1,1,0,1);
signal(0,1,1,1,1,0,0,1,1);
signal(0,1,1,1,1,0,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void S(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void T(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,1);
signal(0,0,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void U(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,0,0,1,1);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,0,1);
signal(1,0,0,0,0,0,0,1,1);
signal(1,1,1,1,1,1,1,1,1);
delay(t);
}
void V(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,1,1,1,1,1);
signal(1,1,1,1,1,0,1,1,1);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,0,1,1,1);
signal(0,0,0,0,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
}
void Z(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,0,1);
signal(0,0,1,1,1,1,1,0,1);
signal(0,1,0,1,1,1,1,0,1);
signal(0,1,1,0,1,1,1,0,1);
signal(0,1,1,1,0,1,1,0,1);
signal(0,1,1,1,1,0,0,0,1);
signal(1,1,1,1,1,1,1,1,1);
}
void signal(int a,int b,int c,int d,int e,int f,int p,int k,int n){
/*Napomena 1=LOW 0=HIGH*/
if(a==1)digitalWrite(2,LOW);
else digitalWrite(2,HIGH);
if(b==1)digitalWrite(3,LOW);
else digitalWrite(3,HIGH);
if(c==1)digitalWrite(4,LOW);
else digitalWrite(4,HIGH);
if(d==1)digitalWrite(5,LOW);
else digitalWrite(5,HIGH);
if(e==1)digitalWrite(6,LOW);
else digitalWrite(6,HIGH);
if(f==1)digitalWrite(11,LOW);
else digitalWrite(11,HIGH);
if(p==1)digitalWrite(8,LOW);
else digitalWrite(8,HIGH);
if(k==1)digitalWrite(9,LOW);
else digitalWrite(9,HIGH);
if(n==1)digitalWrite(10,LOW);
else digitalWrite(10,HIGH);
delay(t);
}
val=analogRead(StartPin);
}
}
void A(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,0,0,0,0,0,0,0);
signal(1,0,1,1,1,1,1,1,1);
signal(0,1,1,1,0,1,1,1,1);
signal(0,1,1,1,0,1,1,1,1);
signal(1,0,1,1,0,1,1,1,1);
signal(1,1,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void B(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,0,0,0,1);
signal(0,0,0,0,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void C(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(1,0,0,0,0,0,0,0,1);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void D(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,0,0,0,0,0,1,1);
signal(1,0,1,1,1,1,1,0,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void E(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,1,1,1,0,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void Fa(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(0,1,1,0,1,1,1,1,1);
signal(0,1,1,0,1,1,1,1,1);
signal(0,1,1,0,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void G(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,0,1,1,1);
signal(1,0,1,1,1,0,0,0,1);
signal(0,1,1,1,1,0,1,1,0);
signal(0,1,1,1,1,0,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(1,0,0,0,0,0,0,0,1);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void H(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,0,0,1,1,1,1);
signal(1,1,1,0,0,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void I(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void J(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,0,0,1);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void K(){//LOW=1 HIGH=0
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,1,1,1,0,0,0);
signal(1,1,1,0,1,0,1,1,1);
signal(1,1,1,1,0,1,1,1,1);
signal(1,1,1,1,0,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void L(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void M(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(1,0,0,0,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void N(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,1,0,1,1);
signal(1,1,1,1,1,0,1,1,1);
signal(1,1,1,1,0,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void O(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,1,1,1,1,1,1,1,0);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void P(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,1,1,1,1);
signal(0,1,1,1,1,0,1,1,1);
signal(0,1,1,1,1,0,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void R(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,0,0,0,0,1,1,0,1);
signal(0,1,1,1,1,0,0,1,1);
signal(0,1,1,1,1,0,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void S(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void T(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,1,1);
signal(0,0,0,0,0,0,0,0,0);
signal(0,1,1,1,1,1,1,1,1);
signal(0,0,1,1,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void U(){
signal(1,1,1,1,1,1,1,1,1);
signal(1,0,0,0,0,0,0,1,1);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,0,1);
signal(1,0,0,0,0,0,0,1,1);
signal(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void V(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,0,0,0,1,1,1,1,1);
signal(1,1,1,1,1,0,1,1,1);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,1,1,1,0);
signal(1,1,1,1,1,1,1,0,1);
signal(1,1,1,1,1,0,1,1,1);
signal(0,0,0,0,1,1,1,1,1);
signal(1,1,1,1,1,1,1,1,1);
}
void Z(){
signal(1,1,1,1,1,1,1,1,1);
signal(0,1,1,1,1,1,1,0,1);
signal(0,0,1,1,1,1,1,0,1);
signal(0,1,0,1,1,1,1,0,1);
signal(0,1,1,0,1,1,1,0,1);
signal(0,1,1,1,0,1,1,0,1);
signal(0,1,1,1,1,0,0,0,1);
signal(1,1,1,1,1,1,1,1,1);
}
void AA(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,0,0,0,0,0,0,0);
signal1(1,0,1,1,1,1,1,1,1);
signal1(0,1,1,1,0,1,1,1,1);
signal1(0,1,1,1,0,1,1,1,1);
signal1(1,0,1,1,0,1,1,1,1);
signal1(1,1,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void BB(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,0,0,0,1);
signal1(0,0,0,0,0,1,1,1,0);
signal1(0,1,1,1,0,1,1,1,0);
signal1(0,1,1,1,0,1,1,1,0);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void CC(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(1,0,0,0,0,0,0,0,1);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void DD(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,0,0,0,0,0,1,1);
signal1(1,0,1,1,1,1,1,0,1);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void EE(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,0,1,1,1,0);
signal1(0,1,1,1,0,1,1,1,0);
signal1(0,1,1,1,0,1,1,1,0);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void FF(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,1);
signal1(0,1,1,0,1,1,1,1,1);
signal1(0,1,1,0,1,1,1,1,1);
signal1(0,1,1,0,1,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void GG(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,0,1,1,1);
signal1(1,0,1,1,1,0,0,0,1);
signal1(0,1,1,1,1,0,1,1,0);
signal1(0,1,1,1,1,0,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(1,0,0,0,0,0,0,0,1);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void HH(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,0,0,1,1,1,1);
signal1(1,1,1,0,0,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void II(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,0,0,0,0,0,0,0,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void JJ(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,0,0,1);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void KK(){//LOW=1 HIGH=0
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,0,0,1,1,1,0,0,0);
signal1(1,1,1,0,1,0,1,1,1);
signal1(1,1,1,1,0,1,1,1,1);
signal1(1,1,1,1,0,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void LL(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,0);
signal1(1,1,1,1,1,1,1,1,0);
signal1(1,1,1,1,1,1,1,1,0);
signal1(1,1,1,1,1,1,1,1,0);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void MM(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,0,0,0,0,0,0,0,0);
signal1(0,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,1);
signal1(1,0,0,0,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,1);
signal1(1,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void NN(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,0,1);
signal1(1,1,1,1,1,1,0,1,1);
signal1(1,1,1,1,1,0,1,1,1);
signal1(1,1,1,1,0,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void OO(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,1,1,1,1,1,1,1,0);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void PP(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,0,0,0,0,1,1,1,1);
signal1(0,1,1,1,1,0,1,1,1);
signal1(0,1,1,1,1,0,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void RR(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,0);
signal1(1,0,0,0,0,1,1,0,1);
signal1(0,1,1,1,1,0,0,1,1);
signal1(0,1,1,1,1,0,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
/*void SS(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}*/
void TT(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,0,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,1,1);
signal1(0,0,0,0,0,0,0,0,0);
signal1(0,1,1,1,1,1,1,1,1);
signal1(0,0,1,1,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void UU(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(1,0,0,0,0,0,0,1,1);
signal1(1,1,1,1,1,1,1,0,1);
signal1(1,1,1,1,1,1,1,1,0);
signal1(1,1,1,1,1,1,1,1,0);
signal1(1,1,1,1,1,1,1,0,1);
signal1(1,0,0,0,0,0,0,1,1);
signal1(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void VV(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,0,0,0,1,1,1,1,1);
signal1(1,1,1,1,1,0,1,1,1);
signal1(1,1,1,1,1,1,1,0,1);
signal1(1,1,1,1,1,1,1,1,0);
signal1(1,1,1,1,1,1,1,0,1);
signal1(1,1,1,1,1,0,1,1,1);
signal1(0,0,0,0,1,1,1,1,1);
signal1(1,1,1,1,1,1,1,1,1);
}
void ZZ(){
signal1(1,1,1,1,1,1,1,1,1);
signal1(0,1,1,1,1,1,1,0,1);
signal1(0,0,1,1,1,1,1,0,1);
signal1(0,1,0,1,1,1,1,0,1);
signal1(0,1,1,0,1,1,1,0,1);
signal1(0,1,1,1,0,1,1,0,1);
signal1(0,1,1,1,1,0,0,0,1);
signal1(1,1,1,1,1,1,1,1,1);
}
void AAA(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,0,0,0,0,0,0,0);
signal2(1,0,1,1,1,1,1,1,1);
signal2(0,1,1,1,0,1,1,1,1);
signal2(0,1,1,1,0,1,1,1,1);
signal2(1,0,1,1,0,1,1,1,1);
signal2(1,1,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void BBB(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,0,0,0,1);
signal2(0,0,0,0,0,1,1,1,0);
signal2(0,1,1,1,0,1,1,1,0);
signal2(0,1,1,1,0,1,1,1,0);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void CCC(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(1,0,0,0,0,0,0,0,1);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void DDD(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,0,0,0,0,0,1,1);
signal2(1,0,1,1,1,1,1,0,1);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void EEE(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,0,1,1,1,0);
signal2(0,1,1,1,0,1,1,1,0);
signal2(0,1,1,1,0,1,1,1,0);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void FFF(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,1);
signal2(0,1,1,0,1,1,1,1,1);
signal2(0,1,1,0,1,1,1,1,1);
signal2(0,1,1,0,1,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void GGG(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,0,1,1,1);
signal2(1,0,1,1,1,0,0,0,1);
signal2(0,1,1,1,1,0,1,1,0);
signal2(0,1,1,1,1,0,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(1,0,0,0,0,0,0,0,1);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void HHH(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,0,0,1,1,1,1);
signal2(1,1,1,0,0,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void III(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,0,0,0,0,0,0,0,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void JJJ(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,0,0,1);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void KKK(){//LOW=1 HIGH=0
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,0,0,1,1,1,0,0,0);
signal2(1,1,1,0,1,0,1,1,1);
signal2(1,1,1,1,0,1,1,1,1);
signal2(1,1,1,1,0,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void LLL(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,0);
signal2(1,1,1,1,1,1,1,1,0);
signal2(1,1,1,1,1,1,1,1,0);
signal2(1,1,1,1,1,1,1,1,0);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void MMM(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,0,0,0,0,0,0,0,0);
signal2(0,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,1);
signal2(1,0,0,0,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,1);
signal2(1,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void NNN(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,0,1);
signal2(1,1,1,1,1,1,0,1,1);
signal2(1,1,1,1,1,0,1,1,1);
signal2(1,1,1,1,0,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void OOO(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,1,1,1,1,1,1,1,0);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void PPP(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,0,0,0,0,1,1,1,1);
signal2(0,1,1,1,1,0,1,1,1);
signal2(0,1,1,1,1,0,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void RRR(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,0);
signal2(1,0,0,0,0,1,1,0,1);
signal2(0,1,1,1,1,0,0,1,1);
signal2(0,1,1,1,1,0,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void SSS(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void TTT(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,0,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,1,1);
signal2(0,0,0,0,0,0,0,0,0);
signal2(0,1,1,1,1,1,1,1,1);
signal2(0,0,1,1,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void UUU(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(1,0,0,0,0,0,0,1,1);
signal2(1,1,1,1,1,1,1,0,1);
signal2(1,1,1,1,1,1,1,1,0);
signal2(1,1,1,1,1,1,1,1,0);
signal2(1,1,1,1,1,1,1,0,1);
signal2(1,0,0,0,0,0,0,1,1);
signal2(1,1,1,1,1,1,1,1,1);
delayMicroseconds(t);
}
void VVV(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,0,0,0,1,1,1,1,1);
signal2(1,1,1,1,1,0,1,1,1);
signal2(1,1,1,1,1,1,1,0,1);
signal2(1,1,1,1,1,1,1,1,0);
signal2(1,1,1,1,1,1,1,0,1);
signal2(1,1,1,1,1,0,1,1,1);
signal2(0,0,0,0,1,1,1,1,1);
signal2(1,1,1,1,1,1,1,1,1);
}
void ZZZ(){
signal2(1,1,1,1,1,1,1,1,1);
signal2(0,1,1,1,1,1,1,0,1);
signal2(0,0,1,1,1,1,1,0,1);
signal2(0,1,0,1,1,1,1,0,1);
signal2(0,1,1,0,1,1,1,0,1);
signal2(0,1,1,1,0,1,1,0,1);
signal2(0,1,1,1,1,0,0,0,1);
signal2(1,1,1,1,1,1,1,1,1);
}
void signal(int a,int b,int c,int d,int e,int f,int p,int k,int n){
/*Napomena 1=LOW 0=HIGH*/
if(a==1)digitalWrite(52,LOW);
else digitalWrite(52,HIGH);
if(b==1)digitalWrite(51,LOW);
else digitalWrite(51,HIGH);
if(c==1)digitalWrite(46,LOW);
else digitalWrite(46,HIGH);
if(d==1)digitalWrite(45,LOW);
else digitalWrite(45,HIGH);
if(e==1)digitalWrite(40,LOW);
else digitalWrite(40,HIGH);
if(f==1)digitalWrite(39,LOW);
else digitalWrite(39,HIGH);
if(p==1)digitalWrite(34,LOW);
else digitalWrite(34,HIGH);
if(k==1)digitalWrite(33,LOW);
else digitalWrite(33,HIGH);
if(n==1)digitalWrite(28,LOW);
else digitalWrite(28,HIGH);
delayMicroseconds(t);
}
void signal1(int a,int b,int c,int d,int e,int f,int p,int k,int n){
/*Napomena 1=LOW 0=HIGH*/
if(a==1)digitalWrite(53,LOW);
else digitalWrite(53,HIGH);
if(b==1)digitalWrite(48,LOW);
else digitalWrite(48,HIGH);
if(c==1)digitalWrite(47,LOW);
else digitalWrite(47,HIGH);
if(d==1)digitalWrite(42,LOW);
else digitalWrite(42,HIGH);
if(e==1)digitalWrite(41,LOW);
else digitalWrite(41,HIGH);
if(f==1)digitalWrite(36,LOW);
else digitalWrite(36,HIGH);
if(p==1)digitalWrite(35,LOW);
else digitalWrite(35,HIGH);
if(k==1)digitalWrite(30,LOW);
else digitalWrite(30,HIGH);
if(n==1)digitalWrite(29,LOW);
else digitalWrite(29,HIGH);
delayMicroseconds(t);
}
void signal2(int a,int b,int c,int d,int e,int f,int p,int k,int n){
/*Napomena 1=LOW 0=HIGH*/
if(a==1)digitalWrite(50,LOW);
else digitalWrite(50,HIGH);
if(b==1)digitalWrite(49,LOW);
else digitalWrite(49,HIGH);
if(c==1)digitalWrite(44,LOW);
else digitalWrite(44,HIGH);
if(d==1)digitalWrite(43,LOW);
else digitalWrite(43,HIGH);
if(e==1)digitalWrite(38,LOW);
else digitalWrite(38,HIGH);
if(f==1)digitalWrite(37,LOW);
else digitalWrite(37,HIGH);
if(p==1)digitalWrite(32,LOW);
else digitalWrite(32,HIGH);
if(k==1)digitalWrite(31,LOW);
else digitalWrite(31,HIGH);
if(n==1)digitalWrite(26,LOW);
else digitalWrite(26,HIGH);
delayMicroseconds(t);
}
17) Arduino Fast IR Game with Any Remote Control
IR receiver (generic)
× 1
× 11
I didn't use the IR receiver until this project, so I decided to make the
control via remote control. It was also important for me to make the
program learn which keys you want to use. So you don not have to figure
out what kind of value you need for all the keys you use and put it in the
code. You just teach the game once you started it which key ist up, down,
left and so on. Well, you have to do this every time you reset the board...
You can see a level 3 gameplay. An 'arrow down' coming from the left.
Push the key for 'arrow down'
Everytime you hit a wrong key, the symbol went to the other side of the
screen or you hit the key while the symbol is behind a fence the score gets
less. Otherwise the score goes up.
Left corner shows level, right corner shows Score. Score less then 0 means
'Game Over'
SCHEMATICS
I did not find an LCD with I2C board (LCD 1602 + I2C HD44780
Modul). So I just made a shematic. My IR Diode (VS1838B LIRC) is
connected like in this sheme, but make shure you make the right
connection!! (Data: orange, GND: black, VCC: red). You can use an
Arduino Nano or Uno.
CODE
#include <IRremote.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
char up = 3;
char down = 1;
char ok = 2;
byte down1[8] = {
B00100,
B00100,
B00100,
B00100,
B00100,
B10101,
B01110,
B00100
};
byte ok1[8] = {
B01110,
B01010,
B01110,
B10000,
B10100,
B11000,
B10100,
B10010
};
char* howtoplay[23] = {
"> FAST IR GAME <",
" Press key ",
"You have to", // if you don't want this howToPlay you can delete from here ...
"press the key,",
"that you see on",
"the screen, when",
"it is beetween",
"the fences (#).",
"It ist getting",
"faster and there",
"will be symbols",
"that you do not",
"have to hit!",
"Try to get to",
"Level 10 and win",
"the game. Before",
"you start, you",
"have to define",
"the keys on your",
"remote control",
"to play the game", // ... until here. Leave the last lines for propper work!
" Have fun !!",
""
};
String keyNames[] = {"up", "down", "right", "left", "ok", "+", "-", "#", "*"};
String keySymb[] = {"", "", "", "", "", "", "", "", ""};
long keys[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int keycount = 7;
int lev;
int xpos = 1;
int xadd = 1;
int xleft;
int xright;
int xstart = 0;
int xend = 15;
int actSym = 0;
int score; // All together score
int scorePerLev; // Symbols in actual level
int scoreNextLev = 50; // Symbols until next level
IRrecv irrecv(RECV_PIN);
decode_results results;
LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line
display
void setup()
{
Serial.begin(9600);
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.createChar(up, up1);
lcd.createChar(down, down1);
lcd.createChar(ok, ok1);
keySymb[0] = "\3";
keySymb[1] = "\1";
keySymb[2] = "\176";
keySymb[3] = "\177";
keySymb[4] = "\2";
keySymb[5] = "+";
keySymb[6] = "-";
keySymb[7] = "#";
keySymb[8] = "*";
info(); //howtoplay show once at the start, can be removed when you know how to play
randomSeed(analogRead(1));
}
void loop()
{
// Select Level
// gameState=0
//###########################
if (gameState == 0) {
lev = 1;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Select Level+ok");
lcd.setCursor(0, 1);
lcd.print("Level: ");
lcd.print(lev);
irrecv.resume();
pressed = false;
Serial.println("Level");
Serial.println(pressed);
while (pressed != true) {
if (irrecv.decode(&results)) {
Serial.println(results.value);
if (results.value == keys[0]) lev++;
if (results.value == keys[1]) lev--;
if (results.value == keys[4]) pressed = true;
if (lev < 1) lev = 1;
if (lev > 10) lev = 10;
lcd.setCursor(7, 1);
lcd.print(lev);
lcd.print(" ");
irrecv.resume();
}
delay(250);
}
lcd.setCursor(0, 0);
lcd.print("Ok! Play in ");
delay(2000);
lcd.clear();
gameState = 1; // Main gameplay
score = 0;
scorePerLev = 0;
keycount = 7;
xleft = 4;
xright = 11;
drawField("");
irrecv.resume();
Serial.println("Level Set");
}
// Main Game
// gameState=1
//###############################
if (gameState == 1) {
xpos = 0;
xadd = 1;
int k = 0;
bool rightkey = false;
pressed = false;
actSym = floor(random(0, keycount));
while (pressed != true) {
Serial.println(xpos);
if (irrecv.decode(&results)) {
for (int i = 0; i < keycount; i++) {
if (results.value == keys[i]) {
rightkey = true;
k = i;
}
}
if (rightkey == true) {
scorePerLev++;
if (xpos <= xleft || xpos >= xright) {
score = score - (4 + lev);
// negativ sound
}
if (actSym == k) {
lcd.setCursor(xpos, 1);
lcd.print(" ");
score++;
drawField("");
changeDirection();
} else {
score = score - (2 + lev);
drawField(" :( ");
// negativ sound
}
actSym = floor(random(0, keycount));
rightkey = false;
}
delay(10);
irrecv.resume();
if (scorePerLev == scoreNextLev) {
scorePerLev = 0;
lev++;
drawField("");
if (lev < 11) {
lcd.setCursor(0, 1);
lcd.print("Next level!");
waitForOK();
// Check for score and display message here later
lcd.setCursor(0, 1);
lcd.print(" ");
} else {
gameState = 5;
pressed = true;
}
}
}
lcd.setCursor(xpos, 1);
lcd.print(" ");
xpos = xpos + xadd;
if (xpos == xend + 1 || xpos == xstart - 1) {
if (actSym < 7) {
score = score - (2 * (lev + 5));
drawField(" :( ");
} else {
drawField("");
}
changeDirection();
actSym = floor(random(0, keycount));
// negativ sound
}
lcd.setCursor(xpos, 1);
lcd.print(keySymb[actSym]);
delay(200 - (lev * 10));
if (score < 0) {
gameState = 9;
pressed = true;
}
} // Main Game loop End
// Win
// ##################
if (gameState == 5) {
// positiv sound
lcd.setCursor(0, 1);
lcd.print("You win the Game");
lcd.setCursor(0, 0);
lcd.print("Bravo! ");
waitForOK();
gameState = 0;
}
// Game Over
// ##################
if (gameState == 9) {
// negativ sound
for (int i = 0; i < 5; i++) {
lcd.setCursor(0, 1);
lcd.print(" ");
delay(200);
lcd.setCursor(0, 1);
lcd.print(" Game over! ");
delay(300);
}
waitForOK();
gameState = 0;
}
void info () {
int i = 0;
while (howtoplay[i] != "") {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(howtoplay[i]);
lcd.setCursor(0, 1);
lcd.print(howtoplay[i + 1]);
delay(300);
waitForKey();
i++;
}
irrecv.resume();
}
void changeDirection() {
xpos = xstart;
xadd = 1;
if (lev > 3) {
int dir = floor(random(0, 2));
if (dir == 1) {
xpos = xend;
xadd = -1;
}
}
}
void waitForKey () {
bool press = false;
irrecv.resume();
while (press == false) {
if (irrecv.decode(&results)) {
if (results.value != 0) press = true;
irrecv.resume();
delay(200);
}
}
}
void waitForOK() {
delay(1000);
bool press = false;
irrecv.resume();
while (press == false) {
if (irrecv.decode(&results)) {
if (results.value == keys[4]) press = true;
irrecv.resume();
delay(200);
}
}
}
18) Arduino DIY PH Dosing Pump
× 1
5 pin header
× 2
× 1
Breadboard (generic)
× 1
SCHEMATICS
CODE
/*
void setup() {
Wire.begin(); //start the I2C
Serial.begin(9600); //start the serial
communication to the computer
}
void loop() {
if (reading_request_phase) { //if were in the phase
where we ask for a reading
Serial.println();
reading_request_phase = true; //switch back to asking for
readings
}
}
}
case Ezo_board::FAIL:
Serial.print("Failed "); //means the command has
failed.
break;
case Ezo_board::NOT_READY:
Serial.print("Pending "); //the command has not yet
been finished calculating.
break;
case Ezo_board::NO_DATA:
Serial.print("No Data "); //the sensor has no data to
send.
break;
}
}
19) Arduino Simple Lap Counter for Swimming
COMPONENTS AND SUPPLIES
Magconn Developer Kit
× 1
Arduino Nano R3
× 1
Now the weather here is very hot because it is summer. I went to the
pool with my primary school son to avoid the heat, and I saw people
swimming several times on the swimming track. How many laps did
they turn? When you learn to swim, count how many turns you have
made to measure your momentum. But most people forget the count.
There is a wrist watch or a finger counter, but it is a little
uncomfortable when swimming. When swimming, it is better not to do
anything. I made an intuitively waterproof lap-counter. Simply press it
to go up once. I would like to implement many functions, but step by
step.
Materials
There are some great conditions. The first is battery use, the second is
waterproof, and the third is convenience. The battery should be
rechargeable. Because you do not have to open the case when it's
completely discharged. So I found connectors and switches that are
waterproof. The case recycled the phone accessary case. I think that it
was good to recycle when I finished.
Assembling the Case
The lap-counter has a waterproof toggle switch and a waterproof
Magconn connector. I bought the Lithium-Polymer battery and
Lithium-rechargeable PCBA that I had inexpensively. The back side of
the Samsung mobile phone case was machined to match the Magconn
connector, and the magnet was attached and closed with epoxy. I added
four more because I think one magnet is not enough. The connector is
closed with epoxy and glue.
Build Circuit
I built a circuit on the breadboard and implemented the behavior. The
counter is fine. The four corners of the switch are for height
adjustment. After confirming that it works well, I put it in the case and
finished it with silicon. When using glue gun, be careful because case
may melt at high temperature.
Waterproofing should be good. It was made better than I thought. I was
worried about the phone case, but the recycle case became the key
point.
Waterproof Test
I tried the waterproof test in the water of the pool. There is a magnet on
the back of the case, and if there is an iron plate on the outside, it
attaches unconditionally. When there is no iron plate, a sucker plate can
be used.
SCHEMATICS
CODE
// dp, G, F, E, D, C, B, A
const int segmentPins[8] = { 9,8,7,6,5,4,3,2 };
const int nbrDigits = 2;
const int digitPins[nbrDigits] = { 12,13 };
const int buttonPin = 11;
int buttonState; // the current reading from the input pin
int lastButtonState = HIGH; // the previous reading from the input pin
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
int value = -1;
void setup()
{
for(int i=0; i<8; i++)
{
pinMode(segmentPins[i], OUTPUT);
}
for(int i=0; i<nbrDigits; i++)
{
pinMode(digitPins[i], OUTPUT);
digitalWrite(digitPins[i], 1);
}
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH); //
}
void loop()
{
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) { // reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
value = value + 1;
}
}
}
lastButtonState = reading;
showNumber(value);
}
Arduino Nano R3
× 1
NeoPixel strip
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Short Setup
Hardware: Solder three wires from the Arduino Nano to the NeoPixel
strip: 5V, digital signal (I chose pin 2 on the Arduino) and ground.
Tip: Use a piece of heat shrink to tie the cables together, especially the
led strip (make sure the solder connections are covered). This will
prevent the solder connections from coming loose.
Code: Set the number of LEDs of the connected strip in the sketch
code, upload it to the Arduino and test it. I used a 'walking', flashing
and pulsing animation in the sketch, only using the color white. You
can adjust the code to do all sorts of animations and use many colors.
Or just use simple a backlight, whatever you prefer.
The build: I cut 2 pieces of cardboard which fit snugly in my cabinet.
One piece is used as the background to glue the neopixel strip on. The
other strip is placed flat behind the bottom of the marquee to prevent
light from the neopixels shining down directly. Afterward I had to cut
off some small edges to make it fit my cabinet.
I put a few pieces of gaffa tape on the cardboard to make them black. I
glued the neopixel strip on the cardboard and taped the wires and nano
to the back of the cardboard.
Put the 2 parts in the cabinet and attach a USB cable from the nano to a
5V power source. In my cabinet it is connected to a USB port of a
Raspberry Pi.
Then place the stock marquee back or create your own to customize
your build. I created a simple one, printed it on photo paper and cut it
to fit the marquee.
Tip: The end result will be even better if you have your design printed
on film by a professional printing company.
Libraries
The sketch needs one library:
Adafruit NeoPixel library
SCHEMATICS
CODE
/*
**********************************************************************
* Marquee lighting with Neopixels by ericBcreator
* simple script for lighting an (arcade) marquee
**********************************************************************
*
* components:
* - Neopixel strip
* - Arduino Nano
*
* This code is free for personal use, not for commercial purposes.
* Please leave this header intact.
*/
//
// include the libraries
//
#include <Adafruit_NeoPixel.h>
#define PIN
2
// define the pin the strip is connected to
//
// setup variables and initialize the neopixel strip
//
int numOfLeds =
11;
the numbers of leds on the strip
int minBrightness =
80; // the
minimum brightness of the pulsing and flashing (0-255)
int maxBrightness =
255; // the
maximum brightness of the pulsing and flashing (0-255)
int walkingLedsDelay =
250; // the delay in ms
for the walking leds
int flashDelay =
250;
the delay in ms for the flashing leds
int numOfFlashLoops =
3; // the
number of times the leds flash
int numOfPulseLoops =
10; // the
number of times the leds puls from min to max
int pulseDelay =
20;
the delay in ms when pulsing from min to max and vice verse
//
// setup
//
void setup() {
strip.begin();
}
//
// main loop
//
void loop() {
walkingLeds();
show the walking leds
flashLeds();
// flash the leds
//
// functions
//
void walkingLeds() {
setLedColorsToZero();
strip.setBrightness(maxBrightness);
strip.show();
strip.setBrightness(minBrightness);
strip.show();
delay(flashDelay );
}
}
void pulseBrightness() {
setLedColors();
void setLedColors() {
for (int x = 0; x < numOfLeds; x++)
strip.setPixelColor(x, strip.Color(255, 255, 255));
}
void setLedColorsToZero() {
for (int x = 0; x < numOfLeds; x++)
strip.setPixelColor(x, strip.Color(0, 0, 0));
}
× 1
× 1
× 1
/***************************************************
This is a library for our I2C LED Backpacks
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_LEDBackpack.h>
#include "SPI.h"
#include "Phpoc.h"
PhpocServer server(80);
// LED face
static const uint8_t PROGMEM
smile_bmp[] =
{ B00111100,
B01000010,
B10100101,
B10000001,
B10100101,
B10011001,
B01000010,
B00111100 },
frown_bmp[] =
{ B00111100,
B01000010,
B10100101,
B10000001,
B10011001,
B10100101,
B01000010,
B00111100 };
// direction
const int TOP = 0;
const int RIGHT = 1;
const int BOTTOM = 2;
const int LEFT = 3;
// Snake
const int MAX_SNAKE_LENGTH = 15;
// Variables
Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix(); // Display
int direction = TOP; // direction of movement
int snakeX[MAX_SNAKE_LENGTH]; // X-coordinates of snake
int snakeY[MAX_SNAKE_LENGTH]; // Y-coordinates of snake
int snakeLength = 1; // nr of parts of snake
unsigned long prevTime = 0; // for gamedelay (ms)
unsigned long delayTime = 500; // Game step in ms
void setup(){
Serial.begin(9600);
while(!Serial)
;
Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
server.beginWebSocket("snake");
Serial.println("Game is started.");
randomSeed(analogRead(0));
// init snake
snakeX[0] = 4;
snakeY[0] = 7;
for(int i=1; i<MAX_SNAKE_LENGTH; i++)
snakeX[i] = snakeY[i] = -1;
makeFruit();
printString("S");
}
void loop(){
checkButtons();
draw();
}
void checkButtons(){
if (client)
{
if (client.available() > 0)
{
// read the bytes incoming from the client:
char thisChar = client.read();
if(thisChar == '0')
direction = TOP;
if(thisChar == '1')
direction = LEFT;
if(thisChar == '2')
direction = RIGHT;
if(thisChar == '3')
direction = BOTTOM;
}
}
}
void draw(){
matrix.clear();
drawSnake();
drawFruit();
matrix.writeDisplay();
}
void drawSnake(){
for(int i=0; i<snakeLength; i++)
matrix.drawPixel(snakeX[i], snakeY[i], LED_GREEN);
}
void drawFruit(){
if(inPlayField(fruitX, fruitY)){
unsigned long currenttime = millis();
if(currenttime - fruitPrevTime >= fruitBlinkTime)
{
fruitLed = (fruitLed == LED_RED) ? LED_OFF : LED_RED;
fruitPrevTime = currenttime;
}
matrix.drawPixel(fruitX, fruitY, fruitLed);
}
}
void nextstep(){
for(int i = snakeLength; i > 0; i--)
{
if((direction == RIGHT) && (snakeX[0]-snakeLength == 7))
snakeX[0] = -1;
else if((direction == LEFT) && (snakeX[0]+ snakeLength == 0))
snakeX[0] = 8;
else
snakeX[i] = snakeX[i-1];
switch(direction)
{
case TOP:
snakeY[0] = snakeY[0]-1;
break;
case RIGHT:
snakeX[0] = snakeX[0]+1;
break;
case BOTTOM:
snakeY[0] = snakeY[0]+1;
break;
case LEFT:
snakeX[0]=snakeX[0]-1;
break;
}
}
snakeCheck();
}
void makeFruit(){
int x, y;
x = random(0, 8);
y = random(0, 8);
while(isPartOfSnake(x, y)){
x = random(0, 8);
y = random(0, 8);
}
fruitX = x;
fruitY = y;
}
void snakeCheck(){
for(int i=1; i<snakeLength; i++)
{
// snake touches itself
if((snakeX[0] == snakeX[i]) && (snakeY[0] == snakeY[i]))
userLose();
}
if (snakeLength == MAX_SNAKE_LENGTH)
userWin();
}
void userLose(){
Serial.println("Game Over");
printString("O");
matrix.clear();
matrix.drawBitmap(0, 0, frown_bmp, 8, 8, LED_RED);
matrix.writeDisplay();
delay(1000);
snakeLength = 1;
setup();
loop();
}
void userWin(){
Serial.println("You Win");
printString("W");
matrix.clear();
matrix.drawBitmap(0, 0, smile_bmp, 8, 8, LED_GREEN);
matrix.writeDisplay();
delay(1000);
snakeLength = 1;
setup();
loop();
}
if (str == "O")
{
matrixComment = "Game Over!";
matrixColor = LED_RED;
}
else if (str == "W")
{
matrixComment = "You Win!";
matrixColor = LED_GREEN;
}
else if (str == "S")
{
matrixComment = "Go!";
matrixColor = LED_YELLOW;
}
else
matrixColor = LED_YELLOW;
matrix.setTextColor(matrixColor);
<!DOCTYPE html>
<html>
<head>
<title>PHPoC Shield - Snake Game</title>
<meta name="viewport" content="width=device-width, initial-scale=0.7,
maximum-scale=0.7">
<style>
body { font-family: verdana, Helvetica, Arial, sans-serif, gulim; font-
weight: bold; text-align: center; }
h1 { font-size: 25pt; }
h2 { font-size: 15pt; }
#remote { margin:0 auto; width: 500px; background: #333; border-radius:
2%; }
.direct {
display: inline-block; width: 100px; height: 100px;
font-size: 50px; color: white; line-height: 90px;
background: #eee; margin: 8px; border-radius: 10%;
text-align: center; font-weight: bold;
margin: 10px 60px;
}
</style>
<script>
var ws;
var button;
function init()
{
if(ws == null)
{
ws = new WebSocket("ws://<?echo _SERVER("HTTP_HOST")?
>/snake", "text.phpoc");
document.getElementById("ws_state").innerHTML = "CONNECTING";
ws.onopen = ws_onopen;
ws.onclose = ws_onclose;
ws.onmessage = ws_onmessage;
}
else
ws.close();
}
function connect_onclick()
{
if(ws == null)
{
var ws_host_addr = "<?echo _SERVER("HTTP_HOST")?>";
//var debug = document.getElementById("debug");
document.getElementById("ws_state").innerHTML = "CONNECTING";
ws.onopen = ws_onopen;
ws.onclose = ws_onclose;
ws.onmessage = ws_onmessage;
}
else
ws.close();
}
function ws_onopen()
{
document.getElementById("ws_state").innerHTML = "<font
color='blue'>CONNECTED</font>";
document.getElementById("bt_connect").innerHTML = "Disconnect";
}
function ws_onclose()
{
document.getElementById("ws_state").innerHTML = "<font
color='gray'>CLOSED</font>";
document.getElementById("bt_connect").innerHTML = "Connect";
ws.onopen = null;
ws.onclose = null;
ws.onmessage = null;
ws = null;
}
function ws_onmessage(e_msg)
{
e_msg = e_msg || window.event; // MessageEvent
var beta = 0;
var gamma = 0;
var resolution = 2;
if (window.DeviceOrientationEvent)
{
window.addEventListener('deviceorientation', orientationUpdate, true);
}
function orientationUpdate(event)
{
}
window.onload = init;
</script>
</head>
<body>
<h1>Snake Game</h1>
<br /><br />
<div id="remote">
<div class="direct" id="0">↑</div><br />
<div class="direct" id="1">←</div>
<div class="direct" id="2">→</div><br />
<div class="direct" id="3">↓</div>
</div>
<br /><br />
<h2>WebSocket <font id="ws_state" color="gray">CLOSED</font>
</h2>
<button id="bt_connect" type="button"
onclick="connect_onclick();">Connect</button>
<span id="debug"></span>
</body>
</html>
22) Arduino Eco Smart Container
× 1
× 1
× 1
Breadboard (generic)
× 1
× 1
USB-A to B Cable
× 1
× 1
NECESSARY TOOLS AND MACHINES
Hot glue gun (generic)
APPS AND ONLINE SERVICES
Blynk
Arduino IDE
This board has all the advantages of raspberry pi zero but with the
addition of bluetooth 4.0 connectivity and wi-fi, use it to receive
arduino sensor values by means of bluetooth. Programming in Node Js
was a very enjoyable, intuitive and effective experience.
5. DHT22
This digital sensor of humidity and temperature is very used and has
good results, this one uses it to measure the temperature and humidity
near the central device that is the raspberry pi zero w.
6. Ultrasonic sensor
This sensor I used to measure the level of trash in the trash can, had
good results, but probably in an update can be changed by a sensor or
infrared sensor in my opinion seem more reliable but in my country it
is difficult to achieve components as sensors.
7. Moisture sensor
This sensor used it to measure the level of humidity in the earth, any
high reading of humidity means that there could be rain or some flood
and that could be a problem for the garbage of that place, sends a
warning to the application.
8. Solar battery bank
Any project needs power, my prototype I put this power bank of
12000mAh, which also recharges solar, ideally would have a panel
built especially for my prototype. But this device worked great. I used
2 for raspberry pi zero w and arduino 101 in my smart trash can.
9. Arduino 101 6-Axis Acelerometer and Gyroscope
Below is the finished prototype, on the outside only the LCD is visible
on the top and on the back you can see the power bank with its solar
panel, so this device is autonomous and sustainable with the
environment.
To prove that the arduino data was reaching the raspberry pi zero, I
made the latter by programming in node JS, print the value of each
sensor per console in Putty and below my results.
To implement the SMS notifications for my project I had to investigate
on the internet a lot and everything I gathered in the tutorial in which I
leave the link below.
https://www.hackster.io/alexis-santiago-allende/sms-alerts-for-arduino-
101-ble-e7184d
Also to connect arduino 101 with the raspberry pi zero w by bluetooth
of low energy carry out the following tutorial, in which I leave to
information that I found and as I did the process. In this final project
was to unite these two previous examples and make slight
modifications to obtain the desired operation.
https://www.hackster.io/alexis-santiago-allende/arduino-101-connects-
with-raspberry-pi-zero-w-63adc0
Blynk App
Below you can see how the application looks aesthetically, at the top of
the application you can see small boxes that are widgets, two of which
enable notifications, one of them is the one that activates the events of
the Blynk application and the Last is a bin viewer at the moment. In the
central part you can see 4 very beautiful displays of temperature and
humidity. One pair is from the arduino 101 and the other are from the
raspberry pi zero w, with my prototype you can add more visualization
widgets and more sensors but only use the ones that had available.
In the lower part you can see the trash level display next to 2 general
purpose buttons. That could be used to control any item at a distance as
lights from the central unit. The use of this hardware together with
Blynk gives many possibilities.
Notifications examples:
There are two types of notifications implemented, notifications specific
to the application and those that are through the Twilio SMS service.
Here below we have the temperature notification, when the temperature
is higher than a threshold, this sends a notification. In the project
notification is also given when the trash can is full.
Temperature notification
Notifications are also given when the central device is disconnected or
there is a connection failure.
Offline notifications
Apart from the notifications of the app, under the same cases, or if the
previous notifications do not work, we have the notifications by SMS
that in my opinion are more effective, below I leave the example of
when the trash can is full.
SMS notification
SCHEMATICS
CODE
#include <CurieBLE.h>
#include "CurieIMU.h"
#include <Wire.h>
#include "rgb_lcd.h"
#include <CurieTime.h>
void setup() {
Serial.begin(9600);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.setRGB(colorR, colorG, colorB);
// Print a message to the LCD.
setTime(16, 56, 24, 3, 07, 2017);
lcd.print("Have a nice day!");
lcd.setCursor(12, 1);
lcd.print("Off");
pinMode(green, OUTPUT); // use the LED on pin 13 as an output
pinMode(red, OUTPUT);
pinMode(9, OUTPUT); /*activación del pin 9 como salida: para el pulso ultrasónico*/
pinMode(8, INPUT);
CurieIMU.begin();
CurieIMU.setAccelerometerRange(2);
// set the local name peripheral advertises
blePeripheral.setLocalName("Demo111");
// set the UUID for the service this peripheral advertises
blePeripheral.setAdvertisedServiceUuid(demo111.uuid());
// sensors.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
buttons.setValue(0);
sensor1.setValue(0);
sensor2.setValue(0);
sensor3.setValue(0);
sensor4.setValue(0);
// advertise the service
blePeripheral.begin();
Serial.println(("Bluetooth device active, waiting for connections..."));
}
void loop() {
// poll peripheral
blePeripheral.poll();
digitalWrite(9,LOW); /* Por cuestión de estabilización del sensor*/
delayMicroseconds(5);
digitalWrite(9, HIGH); /* envío del pulso ultrasónico*/
delayMicroseconds(10);
tiempo=pulseIn(8, HIGH); /* Función para medir la longitud del pulso entrante. Mide el
tiempo que transcurrido entre el envío
del pulso ultrasónico y cuando el sensor recibe el rebote, es decir: desde que el pin 12
empieza a recibir el rebote, HIGH, hasta que
deja de hacerlo, LOW, la longitud del pulso entrante*/
distancia= int(0.017*tiempo); /*fórmula para calcular la distancia obteniendo un valor
entero*/
char clockTime[8];
//use sprintf to create a time string of the hour, minte and seconds
sprintf(clockTime, "%02d:%02d:%02d", hour(), minute(), second());
//set cursor to column 0, row 0
lcd.setCursor(2, 1);
//print the date string over lcd
lcd.print(clockTime);
// read accelerometer:
int x = CurieIMU.readAccelerometer(X_AXIS);
int y = CurieIMU.readAccelerometer(Y_AXIS);
int z = CurieIMU.readAccelerometer(Z_AXIS);
Serial.print("LED on");
digitalWrite(green, HIGH); // will turn the LED on
a = HIGH;
} else if (buttons.value() == 1 && a == HIGH) { //when 1 was read again (second time)
Serial.println("LED off");
digitalWrite(green, LOW); // will turn the LED off
a = LOW;
}
else if (buttons.value() == 2 && b == LOW) { // 1 in ASCII
Serial.print("LED on");
digitalWrite(red, HIGH); // will turn the LED on
b = HIGH;
} else if (buttons.value() == 2 && b == HIGH) { //when 1 was read again (second time)
Serial.println("LED off");
digitalWrite(red, LOW); // will turn the LED off
b = LOW;
}
}
void updateSensor() {
temp=analogRead(A0);//dht.readTemperature();//read temperature
valor=analogRead(A1);
nivel = map(valor, 0, 1023, 100, 0);
ndistancia = map(distancia, 38, 2, 0, 100);
float sensorLevel = temp*(3.3/1023);
int temp1=(sensorLevel-0.5)*100;
sensor1.setValue(temp1);//send temperature value
sensor2.setValue(distancia);//send distance value
sensor3.setValue(orientation);//send orientation value
sensor4.setValue(nivel);//send percentage of hummidity value
Serial.println(temp1);
Serial.println(distancia);
Serial.println(orientation);
Serial.println(nivel);
}
Main code Node JS
//Blynk
var Blynk = require('blynk-library');
// Search only for the Service UUID of the device (remove dashes)
var serviceUuids = ['19b10000e8f2537e4f6cd104768a1214'];
var sensor1=0;
var sensor2=0;
var sensor3=0;
var sensor4=0;
var temperatura=0;
var humedad=0;
var boton=0;
var contador1=0,contador2=0,contador3=0,contador4=0;
//Twilio
const twilio = require('twilio')
var accountSid = 'AC4c3a664e0475a08a4e0fdbd016555a70';
var authToken = '22ee6e5fe596967997a2d1a57d6d73eb';
//Final
v1.on('write', function(param) {
boton=param[0];
});
v9.on('read', function() {
v9.write(new Date().getSeconds());
});
v8.on('read', function() {
v8.write(sensor1);
});
v7.on('read', function() {
v7.write(humedad);
});
v6.on('read', function() {
v6.write(temperatura);
});
v5.on('read', function() {
v5.write(sensor2);
});
v4.on('read', function() {
v4.write(sensor3);
});
v4.on('read', function() {
v4.write(sensor4);
});
}
});
}, 1000);
service.discoverCharacteristics(characteristicUuids, function(error,
characteristics) {
console.log('discovered characteristics');
// Assign Characteristic
var sensor1Characteristic = characteristics[1];
var sensor2Characteristic = characteristics[2];
var sensor3Characteristic = characteristics[3];
var sensor4Characteristic = characteristics[4];
//var botonCharacteristic = characteristics[4];
setInterval(function() {
sensor1Characteristic.read(function(error, data) {
// data is a buffer
console.log('Temperature is: ' + data.readUInt8(0));
sensor1=data.readUInt8(0);
if (data.readUInt8(0)>=32 && contador1===0) {
sendMessage();
contador1=1;
}
else if(data.readUInt8(0)<=30 && contador1==1){
contador1=0;
});
sensor2Characteristic.read(function(error, data) {
// data is a buffer
console.log('Trash percent is: ' + data.readUInt8(0));
sensor2=data.readUInt8(0);
if (data.readUInt8(0)<=4 && contador2===0) {
sendMessage();
contador2=1;
}
else if(data.readUInt8(0)>=30 && contador2==1){
contador2=0;
}
});
sensor3Characteristic.read(function(error, data) {
// data is a buffer
console.log('Orientation: ' + data.readUInt8(0));
sensor3=data.readUInt8(0);
if (data.readUInt8(0)!=2 && contador3===0) {
sendMessage();
contador3=1;
}
else if(data.readUInt8(0)==2 && contador3==1){
contador3=0;
}
});
sensor4Characteristic.read(function(error, data) {
// data is a buffer
console.log('Humidity: ' + data.readUInt8(0));
sensor4=data.readUInt8(0);
if (data.readUInt8(0)>=90 && contador4===0) {
sendMessage();
contador4=1;
}
else if(data.readUInt8(0)<=30 && contador4==1){
contador4=0;
}
});
}, 1000);
Microchip Atmega328
× 1
Breadboard (generic)
× 1
× 1
SCHEMATICS
#include "Arduino.h"
#undef SERIAL
#if defined(ARDUINO_ARCH_AVR)
#endif
#ifdef USE_OLD_STYLE_WIRING
#define PIN_MOSI 11
#define PIN_MISO 12
#define PIN_SCK 13
#endif
#define RESET 4
#define LED_HB 7
#define LED_ERR 6
#define LED_PMODE 5
#endif
#ifndef PIN_MISO
#define PIN_MISO MISO
#endif
#ifndef PIN_SCK
#define PIN_SCK SCK
#endif
#ifdef SERIAL_PORT_USBVIRTUAL
#define SERIAL SERIAL_PORT_USBVIRTUAL
#else
#define SERIAL Serial
#endif
// STK Definitions
#define STK_OK 0x10
#define STK_FAILED 0x11
#define STK_UNKNOWN 0x12
#define STK_INSYNC 0x14
#define STK_NOSYNC 0x15
#define CRC_EOP 0x20 //ok it is a space...
#ifdef USE_HARDWARE_SPI
#include "SPI.h"
#else
class SPISettings {
public:
// clock is in Hz
SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) :
clock(clock){
(void) bitOrder;
(void) dataMode;
};
private:
uint32_t clock;
friend class BitBangedSPI;
};
class BitBangedSPI {
public:
void begin() {
digitalWrite(PIN_SCK, LOW);
digitalWrite(PIN_MOSI, LOW);
pinMode(PIN_SCK, OUTPUT);
pinMode(PIN_MOSI, OUTPUT);
pinMode(PIN_MISO, INPUT);
}
void end() {}
private:
unsigned long pulseWidth; // in microseconds
};
#endif
void setup() {
SERIAL.begin(BAUDRATE);
pinMode(LED_PMODE, OUTPUT);
pulse(LED_PMODE, 2);
pinMode(LED_ERR, OUTPUT);
pulse(LED_ERR, 2);
pinMode(LED_HB, OUTPUT);
pulse(LED_HB, 2);
int error = 0;
int pmode = 0;
// address for reading and writing, set by 'U' command
unsigned int here;
uint8_t buff[256]; // global block storage
parameter param;
uint8_t getch() {
while (!SERIAL.available());
return SERIAL.read();
}
void fill(int n) {
for (int x = 0; x < n; x++) {
buff[x] = getch();
}
}
#define PTIME 30
void pulse(int pin, int times) {
do {
digitalWrite(pin, HIGH);
delay(PTIME);
digitalWrite(pin, LOW);
delay(PTIME);
} while (times--);
}
void empty_reply() {
if (CRC_EOP == getch()) {
SERIAL.print((char)STK_INSYNC);
SERIAL.print((char)STK_OK);
} else {
error++;
SERIAL.print((char)STK_NOSYNC);
}
}
void breply(uint8_t b) {
if (CRC_EOP == getch()) {
SERIAL.print((char)STK_INSYNC);
SERIAL.print((char)b);
SERIAL.print((char)STK_OK);
} else {
error++;
SERIAL.print((char)STK_NOSYNC);
}
}
void get_version(uint8_t c) {
switch (c) {
case 0x80:
breply(HWVER);
break;
case 0x81:
breply(SWMAJ);
break;
case 0x82:
breply(SWMIN);
break;
case 0x93:
breply('S'); // serial programmer
break;
default:
breply(0);
}
}
void set_parameters() {
// call this after reading paramter packet into buff[]
param.devicecode = buff[0];
param.revision = buff[1];
param.progtype = buff[2];
param.parmode = buff[3];
param.polling = buff[4];
param.selftimed = buff[5];
param.lockbytes = buff[6];
param.fusebytes = buff[7];
param.flashpoll = buff[8];
// ignore buff[9] (= buff[8])
// following are 16 bits (big endian)
param.eeprompoll = beget16(&buff[10]);
param.pagesize = beget16(&buff[12]);
param.eepromsize = beget16(&buff[14]);
// avr devices have active low reset, at89sx are active high
rst_active_high = (param.devicecode >= 0xe0);
}
void start_pmode() {
void end_pmode() {
SPI.end();
// We're about to take the target out of reset
// so configure SPI pins as input
pinMode(PIN_MOSI, INPUT);
pinMode(PIN_SCK, INPUT);
reset_target(false);
pinMode(RESET, INPUT);
pmode = 0;
}
void universal() {
uint8_t ch;
fill(4);
ch = spi_transaction(buff[0], buff[1], buff[2], buff[3]);
breply(ch);
}
commit(page);
return STK_OK;
}
void program_page() {
char result = (char) STK_FAILED;
unsigned int length = 256 * getch();
length += getch();
char memtype = getch();
// flash memory @here, (length) bytes
if (memtype == 'F') {
write_flash(length);
return;
}
if (memtype == 'E') {
result = (char)write_eeprom(length);
if (CRC_EOP == getch()) {
SERIAL.print((char) STK_INSYNC);
SERIAL.print(result);
} else {
error++;
SERIAL.print((char) STK_NOSYNC);
}
return;
}
SERIAL.print((char)STK_FAILED);
return;
}
void read_page() {
char result = (char)STK_FAILED;
int length = 256 * getch();
length += getch();
char memtype = getch();
if (CRC_EOP != getch()) {
error++;
SERIAL.print((char) STK_NOSYNC);
return;
}
SERIAL.print((char) STK_INSYNC);
if (memtype == 'F') result = flash_read_page(length);
if (memtype == 'E') result = eeprom_read_page(length);
SERIAL.print(result);
}
void read_signature() {
if (CRC_EOP != getch()) {
error++;
SERIAL.print((char) STK_NOSYNC);
return;
}
SERIAL.print((char) STK_INSYNC);
uint8_t high = spi_transaction(0x30, 0x00, 0x00, 0x00);
SERIAL.print((char) high);
uint8_t middle = spi_transaction(0x30, 0x00, 0x01, 0x00);
SERIAL.print((char) middle);
uint8_t low = spi_transaction(0x30, 0x00, 0x02, 0x00);
SERIAL.print((char) low);
SERIAL.print((char) STK_OK);
}
//////////////////////////////////////////
//////////////////////////////////////////
////////////////////////////////////
////////////////////////////////////
void avrisp() {
uint8_t ch = getch();
switch (ch) {
case '0': // signon
error = 0;
empty_reply();
break;
case '1':
if (getch() == CRC_EOP) {
SERIAL.print((char) STK_INSYNC);
SERIAL.print("AVR ISP");
SERIAL.print((char) STK_OK);
}
else {
error++;
SERIAL.print((char) STK_NOSYNC);
}
break;
case 'A':
get_version(getch());
break;
case 'B':
fill(20);
set_parameters();
empty_reply();
break;
case 'E': // extended parameters - ignore for now
fill(5);
empty_reply();
break;
case 'P':
if (!pmode)
start_pmode();
empty_reply();
break;
case 'U': // set address (word)
here = getch();
here += 256 * getch();
empty_reply();
break;
× 1
× 1
solar panel
× 1
× 2
× 1
Resistor 1k ohm
× 4
APPS AND ONLINE SERVICES
Arduino IDE
void setup()
{
s.attach(9); //connect vertical servo to pin 9 of arduino
sh.attach(10); //connect horizontal servo to pin 10 of arduino
pinMode(L1, INPUT); //define LDR as input
pinMode(L2, INPUT);
pinMode(L3, INPUT);
pinMode(L4, INPUT);
s.write(start1); //it will start servo from 90 when we reset system
sh.write(start2);
delay(2000);
}
void loop()
{
int LDR1 = analogRead(L1); //read value from LDR
int LDR2 = analogRead(L2);
int LDR3 = analogRead(L3);
int LDR4 = analogRead(L4);
int plus14 =(LDR1+LDR4); //average of two corner LDR
int plus23 =(LDR2+LDR3);
int plus12 =(LDR1+LDR2);
int plus34 =(LDR3+LDR4);
int diff1= abs(plus14 - plus23); // difference to take proper value
int diff2= abs(plus23 - plus14);
int diff3= abs(plus12 - plus34);
int diff4= abs(plus34 - plus12);
Arduino Nano R3
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
/*
Optical Heart Rate Detection (PBA Algorithm) using the MAX30105 Breakout
This is a demo to show the reading of heart rate or beats per minute (BPM) using
a Penpheral Beat Amplitude (PBA) algorithm.
It is best to attach the sensor to your finger using a rubber band or other tightening
device. Humans are generally bad at applying constant pressure to a thing. When you
press your finger against the sensor it varies enough to cause the blood in your
finger to flow differently which causes the sensor readings to go wonky.
The MAX30105 Breakout can handle 5V or 3.3V I2C logic. We recommend powering the
board with 5V
but it will also run at 3.3V.
*/
#include <Wire.h>
#include "MAX30105.h"
#include <LiquidCrystal.h>
#include "heartRate.h"
MAX30105 particleSensor;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
float beatsPerMinute;
int beatAvg;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
Serial.println("Initializing...");
// Initialize sensor
if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed
{
Serial.println("MAX30105 was not found. Please check wiring/power. ");
while (1);
}
Serial.println("Place your index finger on the sensor with steady pressure.");
void loop()
{
long irValue = particleSensor.getIR();
if (checkForBeat(irValue) == true)
{
//We sensed a beat!
long delta = millis() - lastBeat;
lastBeat = millis();
Serial.print("IR=");
Serial.print(irValue);
Serial.print(", BPM=");
Serial.print(beatsPerMinute);
Serial.print(", Avg BPM=");
Serial.print(beatAvg);
Serial.println();
lcd.setCursor(0,0);
lcd.print("BPM: ");
lcd.print(beatAvg);
lcd.setCursor(0,1);
lcd.print(" IR: ");
lcd.print(irValue);
}
26) Rainfall Measured Using Arduino
water sensor
× 1
× 1
ABOUT THIS PROJECT
SCHEMATICS
CODE
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup () {
// initialize serial communication at 9600 bits per second:
Serial.begin (9600);}
void loop() {
// read the input on analog pin 0:
int value = analogRead(A0);
lcd.setCursor(0, 7);
if (value > 500) {
Serial.println("Very heavy Rain");
lcd.print("Very heavy rain");}
else if ((value > 300) && (value <= 500)) {
Serial.println("AVERAGE Rain");
lcd.print("Average Rain");
lcd.print(" "); }
else{
Serial.println("Dry Weather");
lcd.print("Dry Wather");
lcd.print(" ");}
delay(100);}
× 1
Arduino Leonardo
× 1
#include "Bitcraze_PMW3901.h"
#include <Wire.h>
#include <VL53L0X.h>
#include <Mouse.h>
VL53L0X rangeSensor;
void setup() {
Serial.begin(9600);
// Initialize flow sensor
if (!flow.begin()) {
Serial.println("Initialization of the flow sensor failed");
while(1) { }
}
// Initialize range sensor
Wire.begin();
rangeSensor.init();
rangeSensor.setTimeout(500);
// Initialize Mouse
Mouse.begin();
}
int16_t deltaX,deltaY;
void loop() {
// Get motion count since last call
flow.readMotionCount(&deltaX, &deltaY);
// Get single range measurement
float range = rangeSensor.readRangeSingleMillimeters();
// Send motion as mouse movement when the hand is between 80 and 200mm
if (range < 200 && range > 80) {
Mouse.move(deltaX, -deltaY, 0);
}
// Press the left mouse button when the hand is bellow 50mm
if (range < 50) {
Mouse.press();
} else {
Mouse.release();
}
}
28) Arduino Ankle Air Guitar Pedal
COMPONENTS AND SUPPLIES
Arduino Nano R3
any arduino is okay, im thinking on using
tinyduino × 1
mpc41010
× 1
digital potenciometer
SparkFun Triple Axis Accelerometer Breakout
- ADXL335
any analogoutput accelerometer is okay × 1
stereo audio jack 6,5 mm female adapter
× 1
#define CS 10 //chipselect
int datarray[18]={0,0,0,0,0,0,1023,1023,1023,0,0,0,0,0,0};
int smoothingarray[15]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int rgb[3];
int i=0,chipvalue=0;
int ResistorValue=0;
void setup() {
//
//pinMode (GREEN, OUTPUT);//GREEN RGB (PWM)
//pinMode (BLUE, OUTPUT);//BLUE
//pinMode (RED, OUTPUT);//RED
//digitalWrite(GREEN, HIGH);//setting the led off at the begining
//digitalWrite (BLUE, HIGH);//
//digitalWrite (RED, HIGH);//
#ifdef debug
Serial.begin(9600);
#endif
}
void loop() {
datarray[0]=analogRead(accelerometerX);
datarray[1]=analogRead(accelerometerY);
datarray[2]=analogRead(accelerometerZ);
comparemaxmin(datarray);
detectRange(datarray);
ResistorValue=map(datarray[datarray[15]],datarray[datarray[15]+6]+20,datarray[datarray[15
to the min and -10 to the max for preventing unreachable edges
chipvalue =constrain(ResistorValue,0,255);
MCP41010Write(smoothing(chipvalue));
#ifdef debug
Serial.print("//RawReadings: ");
Serial.print(datarray[0]);
Serial.print(" ");
Serial.print(datarray[1]);
Serial.print(" ");
Serial.print(datarray[2]);
// Serial.print("/?? ");
// Serial.print(datarray[12]);
// Serial.print(" ");
// Serial.print(datarray[13]);
// Serial.print(" ");
// Serial.print(datarray[14]);
Serial.println();
#endif
delay(100);//delay for stability
}
for(i=0;i<=2;i++)
datarray[i+6]=min(datarray[i],datarray[i+6]);
digitalWrite(CS,LOW);
SPI.transfer(B00010001); // This tells the chip to set the pot
SPI.transfer(value); // This tells it the pot position
digitalWrite(CS,HIGH);
}
for(j=0;j<=14;j++){
smoothingarray[j] = smoothingarray[j+1];
}
smoothingarray[14]= data;
result=
(smoothingarray[0]+smoothingarray[1]+smoothingarray[2]+smoothingarray[3]+smoothingarray
constrain(result,0,255);
return result;
}
× 1
Texas Instruments 74hc595
× 1
shift register
STMicroelectronics uln2803a
× 1
darlington array
led strip
× 1
acrylic board
APPS AND ONLINE SERVICES
Arduino IDE
rtc library
SCHEMATICS
CODE
/*
RTClib information---
SDA pin -----> A4 / D18
SCL pin -----> A5 / D19
*/
#include <string.h>
#include <Wire.h>
#include"RTClib.h"
// hardware constants
int LEDClockPin=8; // Arduino Pin#8 - Shift register 74HC595 Pin 11 clock
int LEDDataPin=9; // Arduino Pin#9 - Shift register 74HC595 pin 14 Data
int LEDLatchPin=10; // Arduino Pin#10 - Shift register 74HC595 pin 12 Latch
// RTC DEFINE-
RTC_DS1307 RTC ;
void setup()
{
// initialise the hardware
// initialize the appropriate pins as outputs:
pinMode(LEDClockPin, OUTPUT);
pinMode(LEDDataPin, OUTPUT);
pinMode(LEDLatchPin, OUTPUT);
if ( RTC.isrunning()) {
Serial.println("RTC is running.....");
DateTime now = RTC.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
}
selftestmode=0;
if ( RTC.isrunning() ) {
// Get the current time and date from the RTC chip
second=now.second();
minute=now.minute();
hour=now.hour();
}
void WriteLEDs(){
// Now we write the actual values to the hardware
shiftOut(LEDDataPin, LEDClockPin, MSBFIRST, Display3);
shiftOut(LEDDataPin, LEDClockPin, MSBFIRST, Display2);
shiftOut(LEDDataPin, LEDClockPin, MSBFIRST, Display1);
digitalWrite(LEDLatchPin,HIGH);
//delay(2);
digitalWrite(LEDLatchPin,LOW);
}
void ledsoff(void) {
Display1=0;
Display2=0;
Display3=0;
void selftest(void){
// start by clearing the display to a known state
ledsoff();
ITIS;
WriteLEDs();
delay(500);
ledsoff();
MTEN;
WriteLEDs();
delay(500);
ledsoff();
HALF;
WriteLEDs();
delay(500);
ledsoff();
TWENTY;
WriteLEDs();
delay(500);
ledsoff();
QUARTER;
WriteLEDs();
delay(500);
ledsoff();
MFIVE;
WriteLEDs();
delay(500);
ledsoff();
MINUTES;
WriteLEDs();
delay(500);
ledsoff();
PAST;
WriteLEDs();
delay(500);
ledsoff();
TO;
WriteLEDs();
delay(500);
ledsoff();
ONE;
WriteLEDs();
delay(500);
ledsoff();
TWO;
WriteLEDs();
delay(500);
ledsoff();
THREE;
WriteLEDs();
delay(500);
ledsoff();
FOUR;
WriteLEDs();
delay(500);
ledsoff();
HFIVE;
WriteLEDs();
delay(500);
ledsoff();
SIX;
WriteLEDs();
delay(500);
ledsoff();
SEVEN;
WriteLEDs();
delay(500);
ledsoff();
EIGHT;
WriteLEDs();
delay(500);
ledsoff();
NINE;
WriteLEDs();
delay(500);
ledsoff();
HTEN;
WriteLEDs();
delay(500);
ledsoff();
ELEVEN;
WriteLEDs();
delay(500);
ledsoff();
TWELVE;
WriteLEDs();
delay(500);
ledsoff();
OCLOCK;
WriteLEDs();
delay(500);
ledsoff();
RBK;
WriteLEDs();
delay(500);
ledsoff();
ARDUINO;
WriteLEDs();
delay(500);
ledsoff();
void displaytime(void){
if ((minute <5))
{
switch (hour) {
case 1:
case 13:
ONE;
Serial.print("One ");
break;
case 2:
case 14:
TWO;
Serial.print("Two ");
break;
case 3:
case 15:
THREE;
Serial.print("Three ");
break;
case 4:
case 16:
FOUR;
Serial.print("Four ");
break;
case 5:
case 17:
HFIVE;
Serial.print("Five ");
break;
case 6:
case 18:
SIX;
Serial.print("Six ");
break;
case 7:
case 19:
SEVEN;
Serial.print("Seven ");
break;
case 8:
case 20:
EIGHT;
Serial.print("Eight ");
break;
case 9:
case 21:
NINE;
Serial.print("Nine ");
break;
case 10:
case 22:
HTEN;
Serial.print("Ten ");
break;
case 11:
case 23:
ELEVEN;
Serial.print("Eleven ");
break;
case 0:
case 12:
TWELVE;
Serial.print("Twelve ");
break;
}
OCLOCK;
Serial.println("O'Clock");
}
else
if ((minute < 35) && (minute >4))
{
PAST;
Serial.print("Past ");
switch (hour) {
case 1:
case 13:
ONE;
Serial.println("One ");
break;
case 2:
case 14:
TWO;
Serial.println("Two ");
break;
case 3:
case 15:
THREE;
Serial.println("Three ");
break;
case 4:
case 16:
FOUR;
Serial.println("Four ");
break;
case 5:
case 17:
HFIVE;
Serial.println("Five ");
break;
case 6:
case 18:
SIX;
Serial.println("Six ");
break;
case 7:
case 19:
SEVEN;
Serial.println("Seven ");
break;
case 8:
case 20:
EIGHT;
Serial.println("Eight ");
break;
case 9:
case 21:
NINE;
Serial.println("Nine ");
break;
case 10:
case 22:
HTEN;
Serial.println("Ten ");
break;
case 11:
case 23:
ELEVEN;
Serial.println("Eleven ");
break;
case 0:
case 12:
TWELVE;
Serial.println("Twelve ");
break;
}
}
else
{
// if we are greater than 34 minutes past the hour then display
// the next hour, as we will be displaying a 'to' sign
TO;
Serial.print("To ");
switch (hour) {
case 1:
case 13:
TWO;
Serial.println("Two ");
break;
case 14:
case 2:
THREE;
Serial.println("Three ");
break;
case 15:
case 3:
FOUR;
Serial.println("Four ");
break;
case 4:
case 16:
HFIVE;
Serial.println("Five ");
break;
case 5:
case 17:
SIX;
Serial.println("Six ");
break;
case 6:
case 18:
SEVEN;
Serial.println("Seven ");
break;
case 7:
case 19:
EIGHT;
Serial.println("Eight ");
break;
case 8:
case 20:
NINE;
Serial.println("Nine ");
break;
case 9:
case 21:
HTEN;
Serial.println("Ten ");
break;
case 10:
case 22:
ELEVEN;
Serial.println("Eleven ");
break;
case 11:
case 23:
TWELVE;
Serial.println("Twelve ");
break;
case 0:
case 12:
ONE;
Serial.println("One ");
break;
}
}
void loop()
{
DateTime now = RTC.now();
second=now.second();
minute=now.minute();
hour=now.hour();
//Serial.println("Loop Started");
// Flash the onboard Pin13 Led every 5 sec so we know something is hapening!
if ( millis() - msTick >5000) {
msTick=millis();
digitalWrite(13,HIGH);
delay(50);
digitalWrite(13,LOW);
delay(50);
digitalWrite(13,HIGH);
delay(50);
digitalWrite(13,LOW);
Serial.print(second);
Serial.print("..");
}
× 1
3 mm LED: Yellow
× 8
3 mm LED: Green
× 1
Pushbutton Switch, Momentary
4 pin, small generaic push button
× 6
× 6
× 1
ControlEverything.com Relay
Shield for Particle Photon I²C 8-
Channel SPDT 10-Amp × 1
#include <EEPROM.h>
int warning_button = A5;
int left_button = 2;
int center_button = 4;
int right_button = 3;
int off_button = A0;
int pattern_button = A2;
int statuslight = 13;
int LEDright[] = {5, 6, 7, 8, 9, 10, 11, 12};
int LEDleft[] = {12, 11, 10, 9, 8, 7, 6, 5};
int centerleft[] = {9, 10, 11, 12};
int centerright[] = {8, 7, 6, 5};
int light = 0;
int counter = 1;
int pattern_count = 0;
int warning_count = EEPROM.read(0);
long lasttimer = 0;
static long timer = 200;
static long timer2 = 300;
static long switch_timer = 4000;
#define LEFTside 0x0
#define RIGHTside 0x1
byte whichLED = LEFTside;
byte LEFT_state = LOW;
byte RIGHT_state = LOW;
unsigned long switchDelay = 1000;
unsigned long switchDelay2 = 500;
unsigned long strobeDelay = 75;
unsigned long strobeWait = strobeDelay;
unsigned long waitUntilSwitch = switchDelay;
unsigned long sequenceStartTime;
//----------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
for (int i = 0; i < 8; i++) {
pinMode(LEDright[i], OUTPUT);
}
pinMode(statuslight, OUTPUT);
pinMode(warning_button, INPUT_PULLUP);
pinMode(left_button, INPUT_PULLUP);
pinMode(center_button, INPUT_PULLUP);
pinMode(right_button, INPUT_PULLUP);
pinMode(off_button, INPUT_PULLUP);
pinMode(pattern_button, INPUT_PULLUP);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
}
//------------------------------------------------------------------------
void loop() {
digitalWrite(13, HIGH);
delayMicroseconds(10); // Approximately 10% duty cycle @ 1KHz
digitalWrite(13, LOW);
delayMicroseconds(1000 - 10);
if (digitalRead(pattern_button) == HIGH)
{
delay(500);
warning_count++;
if (warning_count > 10) {
warning_count = 1;
}
}
if (digitalRead(warning_button) == HIGH)
{
delay(50);
pattern_count = 1;
}
if (digitalRead(left_button) == HIGH)
{
delay(50);
pattern_count = 2;
}
if (digitalRead(center_button) == HIGH)
{
delay(50);
pattern_count = 3;
}
if (digitalRead(right_button) == HIGH)
{
delay(50);
pattern_count = 4;
}
if (digitalRead(off_button) == HIGH)
{
delay(50);
pattern_count = 0;
EEPROM.update(0,warning_count);
}
switch (pattern_count) {
case 0:
pattern_off();
break;
case 1:
traffic_left();
break;
case 2:
traffic_center();
break;
case 3:
traffic_right();
break;
case 4:
traffic_warning();
break;
}
}
void pattern_off() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
}
void traffic_left() {
unsigned long currenttimer = millis();
if (currenttimer - lasttimer >= timer) {
lasttimer = currenttimer;
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
digitalWrite(LEDleft[light], LOW);
light = light + counter;
if (light > 7) {
light = 0;
counter = 1;
}
digitalWrite(LEDleft[light], HIGH);
}
}
void traffic_center() {
unsigned long currenttimer = millis();
if (currenttimer - lasttimer >= timer2) {
lasttimer = currenttimer;
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
digitalWrite(centerright[light], LOW);
digitalWrite(centerleft[light], LOW);
light = light + counter;
if (light > 3) {
light = 0;
counter = 1;
}
digitalWrite(centerright[light], HIGH);
digitalWrite(centerleft[light], HIGH);
}
}
void traffic_right() {
unsigned long currenttimer = millis();
if (currenttimer - lasttimer >= timer) {
lasttimer = currenttimer;
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
digitalWrite(LEDright[light], LOW);
light = light + counter;
if (light > 7) {
light = 0;
counter = 1;
}
digitalWrite(LEDright[light], HIGH);
}
}
void traffic_warning() {
switch (warning_count) {
case 1:
even_odd_flash();
break;
case 2:
half_half();
break;
case 3:
half_half_flash();
break;
case 4:
two_by_two();
break;
case 5:
two_by_two_parallel();
break;
case 6:
out_flash();
break;
case 7:
one_center();
break;
case 8:
outboard();
break;
case 9:
inboard();
break;
case 10:
even_odd();
break;
}
}
void even_odd_flash() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
digitalWrite(12, LEFT_state);
digitalWrite(11, RIGHT_state);
digitalWrite(10, LEFT_state);
digitalWrite(9, RIGHT_state);
digitalWrite(8, LEFT_state);
digitalWrite(7, RIGHT_state);
digitalWrite(6, LEFT_state);
digitalWrite(5, RIGHT_state);
if ((long)(millis() - waitUntilSwitch) >= 0) {
LEFT_state = LOW;
RIGHT_state = LOW;
whichLED = !whichLED;
waitUntilSwitch += switchDelay;
}
if ((long)(millis() - strobeWait) >= 0) {
if (whichLED == LEFTside)
LEFT_state = !LEFT_state;
if (whichLED == RIGHTside)
RIGHT_state = !RIGHT_state;
strobeWait += strobeDelay;
}
}
void half_half_flash() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
digitalWrite(12, LEFT_state);
digitalWrite(11, LEFT_state);
digitalWrite(10, LEFT_state);
digitalWrite(9, LEFT_state);
digitalWrite(8, RIGHT_state);
digitalWrite(7, RIGHT_state);
digitalWrite(6, RIGHT_state);
digitalWrite(5, RIGHT_state);
if ((long)(millis() - waitUntilSwitch) >= 0) {
LEFT_state = LOW;
RIGHT_state = LOW;
whichLED = !whichLED;
waitUntilSwitch += switchDelay2;
}
if ((long)(millis() - strobeWait) >= 0) {
if (whichLED == LEFTside)
LEFT_state = !LEFT_state;
if (whichLED == RIGHTside)
RIGHT_state = !RIGHT_state;
strobeWait += strobeDelay;
}
}
void half_half() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 250)
{
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, HIGH);
digitalWrite(8, LOW);
digitalWrite(7, LOW);
digitalWrite(6, LOW);
digitalWrite(5, LOW);
}
else if (time < 500)
{
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
digitalWrite(8, HIGH);
digitalWrite(7, HIGH);
digitalWrite(6, HIGH);
digitalWrite(5, HIGH);
}
else sequenceStartTime = millis();
}
void out_flash() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 150)
{
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
digitalWrite(8, LOW);
digitalWrite(7, LOW);
digitalWrite(6, HIGH);
digitalWrite(5, HIGH);
}
else if (time < 300)
{
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
digitalWrite(8, LOW);
digitalWrite(7, HIGH);
digitalWrite(6, HIGH);
digitalWrite(5, LOW);
}
else sequenceStartTime = millis();
}
void two_by_two() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 150)
{
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
digitalWrite(8, LOW);
digitalWrite(7, LOW);
digitalWrite(6, HIGH);
digitalWrite(5, HIGH);
}
else if (time < 300)
{
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
digitalWrite(9, HIGH);
digitalWrite(8, HIGH);
digitalWrite(7, HIGH);
digitalWrite(6, LOW);
digitalWrite(5, LOW);
}
else sequenceStartTime = millis();
}
void two_by_two_parallel() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 150)
{
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
digitalWrite(8, HIGH);
digitalWrite(7, HIGH);
digitalWrite(6, LOW);
digitalWrite(5, LOW);
}
else if (time < 300)
{
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
digitalWrite(9, HIGH);
digitalWrite(8, LOW);
digitalWrite(7, LOW);
digitalWrite(6, HIGH);
digitalWrite(5, HIGH);
}
else sequenceStartTime = millis();
}
void one_center() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 500)
{
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
digitalWrite(6, LOW);
digitalWrite(5, LOW);
}
else if (time < 1000)
{
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
digitalWrite(8, LOW);
digitalWrite(7, HIGH);
digitalWrite(6, HIGH);
digitalWrite(5, HIGH);
}
else sequenceStartTime = millis();
}
void outboard() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 200)
{
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(6, LOW);
digitalWrite(5, LOW);
}
else if (time < 400)
{
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(6, HIGH);
digitalWrite(5, HIGH);
}
else sequenceStartTime = millis();
}
void inboard() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 200)
{
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
digitalWrite(8, LOW);
digitalWrite(7, HIGH);
digitalWrite(6, HIGH);
}
else if (time < 400)
{
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
digitalWrite(6, LOW);
}
else sequenceStartTime = millis();
}
void even_odd() {
for (int i = 0; i <= 7; i++) {
digitalWrite(LEDright[i], LOW);
}
long time = millis() - sequenceStartTime;
if (time < 300)
{
digitalWrite(12, HIGH);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
digitalWrite(8, HIGH);
digitalWrite(7, LOW);
digitalWrite(6, HIGH);
digitalWrite(5, LOW);
}
else if (time < 600)
{
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
digitalWrite(8, LOW);
digitalWrite(7, HIGH);
digitalWrite(6, LOW);
digitalWrite(5, HIGH);
}
else sequenceStartTime = millis();
}
31) Arduino Word Clock on 8X8 RGB LED Matrix
COMPONENTS AND SUPPLIES
Arduino Nano R3
× 1
× 2
Photo resistor
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
This is probably the best project that can be done with this module.
There are many projects on the Internet that are just pattern generators
and nothing more.
Mark Wilson made an intuitive word clock, and even wrote his own
library "chromaduino" which you can find at GitHub:
https://github.com/funnypolynomial/Chromaduino
It drives the LEDs and receives display information from a master over
I2C.
Now I will try to explain step by step the construction of this device.
First, you have to program the control board. For this purpose we take
Arduino Uno, from which we extract the Atmega chip, and connect
with the control board in the following way:
GND-GND, 5V-VCC, RX(D0)-RXD, TX(D1)-TXD and RESET-DTR
(Arduino-Control board)
#include "arduino.h"
#include <avr/pgmspace.h>
#include <Wire.h>
#include <EEPROM.h>
#include "PINS.h"
#include "RTC.h"
#include "LDR.h"
#include "LEDS.h"
#include "BTN.h"
#include "CFG.h"
#include "CLK.h"
/*
A "word clock" showing the time on one of two 8x8 character grids:
TWENONTY or THRTWONE
FIFVTEEN TWELEVEN
HALFMTOF ENEIGHTI
FOURFIVE SIXSEVEN
SIXSEVEN FOURFIVE
EIGHTHRI THIRTWEN
TWELEVEN MFIFORTY
ONETWOEE EFIVTEEN
//#define _DEBUG
void setup()
{
#ifdef _DEBUG
Serial.begin(38400);
Serial.println("wordclok");
#endif
pins.setup();
digitalWrite(PINS::STD_LED, HIGH);
rtc.setup();
#ifndef _DEBUG
randomSeed(rtc.getSeed());
#endif
ldr.setup();
leds.setup();
cfg.setup();
clk.setup();
digitalWrite(PINS::STD_LED, LOW);
}
void loop()
{
clk.loop();
}
32) Arduino Indoor NeoPixel Thermometer
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
NeoPixel
× 1
LCD readout
× 1
TMP36 sensor
× 1
Resistor 1k ohm
× 1
470 ohm resistor
× 1
× 1
F to M jumper wires
× 1
for the LCD
M to M Jumpers
× 1
for everything else
Breadboard (generic)
× 1
From the fritzing diagram the circuit looks a little confusing but it's
actually relatively simple. What is important to take note is you're
going to want the TMP36 on a separate circuit from the rest of the
project because some noise that's caused by the Pixels messes up the
voltage readout from the TMP36 and in turn the temperature reading.
When it comes to the Pixels a bit a soldering is going to have to
happen. You're going to want to use 4 plain, everyday headers, and
solder them directly onto the NeoPixel stick. It's absolutely imperative
that you get the pin out correct on this otherwise you'll have to de and
resolder the headers and trust me, the copper pads on the NeoPixels do
not like being resoldered and while NeoPixels are not the most
expensive component in the world, several sticks that are rendered
unusable because the copper pads have been taken off add up very
quickly. To solder you will want a good iron and a solder with a thin
gauge. A pair of "third hands" are especially useful in this project as the
headers can be tricky to solder onto the stick straight if the stick is
lying on the table.
How I set up the pixels and header in the Third hand
NeoPixel PinOut
I included a photo with the proper pin order, the side with "DIN" goes
to the breadboard/Arduino and the side "DOUT" goes to other pixels or
just the air. You can use any number of NeoPixels, the one at the Studio
has 4 sticks for an especially prominent read out that would be ideal if
you were to enclose it in a laser cut acrylic display (possibly stay
tuned). On the other hand, and as seen in one of the photos, I have a
smaller one using only one stick that works just fine at home that you
could then also turn into a wall mounted display with a very quick
enclosure. That's one of the things with NeoPixels that make them
great, it doesn't take much code to make them fit almost any size or
form factor.
The pin out from the Arduino goes as follows:
A0 to Vout on TMP36
3.3V to TMP36 PWR Rail
AREF to TMP36 PWR Rail //AREF takes a reference voltage and
gives a more accurate reading than just taking //straight from the
source, you'll see why this is important on the next page
GND to TMP36 GND rail
5V to Primary PWR rail
other GND to Primary GND rail
13 to pin 4 on LCD
12 to momentary switch //while not necessary I included a
momentary switch that, when pressed will switch //between Celsius
and Fahrenheit readout on the LCD
11 to pin 6 on LCD
6 to 470 ohm resistor leading to DIN on NeoPixels //resistor
prevents surges and damage to the pixel stick
5 to pin 11 on LCD
4 to pin 12 on LCD
3 to pin 13 on LCD
2 to pin 14 on LCD
Other pinouts on LCD Screen
LCD pin 1 to one leg of potentiometer leading to Primary GND rail
LCD pin 2 to one leg of potentiometer leading to Primary PWR rail
LCD pin 3 to middle leg or "wiper" of potentiometer //this controls
contrast on the screen
LCD pin 5 to primary GND rail
LCD pin 15 to primary PWR rail
LCD pin 16 to primary GND rail
The rest of the circuit is pretty self explanatory and clear on the
Fritzing Diagram, just remember to keep the TMP36 and Primary
circuits separate.
SCHEMATICS
CODE
#include <LiquidCrystal.h>
#include <Adafruit_NeoPixel.h>
/*
Param 1 == number of pixels
Param 2 == Arduino pin attached to din
Param 3 == pixel type flags, add together as needed
NE0_KHZ800 800 KHZ bitstream (avg neopix)
NE0_GRB wired for GRB bitstream
*/
Adafruit_NeoPixel strip = Adafruit_NeoPixel(32, PIN, NEO_GRB +
NEO_KHZ800); //call Neopixels, 32 pixels in all, on pin 6, RGB system
and 800 KHZ
LiquidCrystal lcd(13, 11, 5, 4, 3, 2); //call LCD display
void setup()
{
lcd.begin(16,2); //initialize LCD screen 16 by 2
strip.begin(); //begin neo pixel strip
strip.show(); //initialize strip
Serial.begin(9600);// serial monitor access
pinMode(button, INPUT); //button for celsius
analogReference(EXTERNAL); //analog reference for use with TMP36
}
void loop()
{
double temperature;
double temp;
double tempF;
}//end loop
double tempMeasure(double temperature)
{
// -----------------
// Read temperature
// -----------------
temperature = (voltage - 0.5) * 100; //converts 10mv per degree with 500
mV offset to (voltage - 500mV) * 100)
}//end tempMeasure
{
int i;
strip.setBrightness(64);
strip.show();
if (tempF >= 90.05)//if above 90 degrees, strip is red and entire strip is lit
{
strip.clear();
for(int i=0;i <= 32;i++)
{
strip.setPixelColor(i, strip.Color(255,0,0));
}
}
else if (tempF < 90.2 && tempF >= 80.05) //if 90 > tempF >= 80 orange
and strip is partially lit up to 29th pixel
{
strip.clear();
for(int i=0;i <= 28;i++)
{
strip.setPixelColor(i, strip.Color(255,128,0));
}
}
else if (tempF < 80.02 && tempF >= 70.5)// if 80 > tempF >= 70 yellow-
green and strip is lit up to 25th pixel
{
strip.clear();
for(int i = 0; i <= 24; i++)
{
strip.setPixelColor(i,strip.Color(204,255,0));
}
}
else if (tempF < 70 && tempF >= 60.5)// if 70 > tempF >= 60 green and
strip is lit up to 21st pixel
{
strip.clear();
for(int i = 0; i<= 20; i++)
{
strip.setPixelColor(i,strip.Color(0,255,0));
}
}
else if (tempF < 60.02 && tempF >= 50.5) //if 60 > tempF >= 50 blue and
strip is lit up to 17th pixel
{
strip.clear();
for(int i = 0; i <= 16; i++)
{
strip.setPixelColor(i,strip.Color(0,0,255));
}
}
else if (tempF < 50.02 && tempF >= 40.5) //if 50 > tempF >= 40 aqua and
strip is lit to 13th pixel
{
strip.clear();
for(int i = 0; i <= 12; i++)
{
strip.setPixelColor(i, strip.Color(0,255,255));
}
}
else if (tempF < 40.02 && tempF >= 32.5) //if 40 > tempF >= 32 fuschia
and strip is lit to 9th pixel
{
strip.clear();
for(int i = 0; i <= 8; i++)
{
strip.setPixelColor(i, strip.Color(153, 51,255));
}
}
else if (tempF < 32.5) //temp < freezing white and strip is lit to 5th pixel
{
strip.clear();
for(i = 0;i <= 4; i++)
{
strip.setPixelColor(i, strip.Color(255,255,255));
}//end for
}
strip.show(); //update color change
}//end pixelCase
Breadboard (generic)
× 1
× 1
USB-A to B Cable
× 1
× 1
Buzzer
× 1
Arduino IDE
#include <LiquidCrystal.h>
#define PIN_BUTTON 2
#define PIN_AUTOPLAY 1
#define PIN_BUZZER 8
#define PIN_READWRITE 10
#define PIN_CONTRAST 12
#define SPRITE_RUN1 1
#define SPRITE_RUN2 2
#define SPRITE_JUMP 3
#define SPRITE_JUMP_UPPER '.' // Use the '.' character for the head
#define SPRITE_JUMP_LOWER 4
#define SPRITE_TERRAIN_EMPTY ' ' // User the ' ' character
#define SPRITE_TERRAIN_SOLID 5
#define SPRITE_TERRAIN_SOLID_RIGHT 6
#define SPRITE_TERRAIN_SOLID_LEFT 7
#define TERRAIN_WIDTH 16
#define TERRAIN_EMPTY 0
#define TERRAIN_LOWER_BLOCK 1
#define TERRAIN_UPPER_BLOCK 2
#define HERO_POSITION_OFF 0 // Hero is invisible
#define HERO_POSITION_RUN_LOWER_1 1 // Hero is running on lower row (pose 1)
#define HERO_POSITION_RUN_LOWER_2 2 // (pose 2)
void initializeGraphics(){
static byte graphics[] = {
// Run position 1
B01100,
B01100,
B00000,
B01110,
B11100,
B01100,
B11010,
B10011,
// Run position 2
B01100,
B01100,
B00000,
B01100,
B01100,
B01100,
B01100,
B01110,
// Jump
B01100,
B01100,
B00000,
B11110,
B01101,
B11111,
B10000,
B00000,
// Jump lower
B11110,
B01101,
B11111,
B10000,
B00000,
B00000,
B00000,
B00000,
// Ground
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
// Ground right
B00011,
B00011,
B00011,
B00011,
B00011,
B00011,
B00011,
B00011,
// Ground left
B11000,
B11000,
B11000,
B11000,
B11000,
B11000,
B11000,
B11000,
};
int i;
// Skip using character 0, this allows lcd.print() to be used to
// quickly draw multiple characters
for (i = 0; i < 7; ++i) {
lcd.createChar(i + 1, &graphics[i * 8]);
}
for (i = 0; i < TERRAIN_WIDTH; ++i) {
terrainUpper[i] = SPRITE_TERRAIN_EMPTY;
terrainLower[i] = SPRITE_TERRAIN_EMPTY;
}
}
bool drawHero(byte position, char* terrainUpper, char* terrainLower, unsigned int score) {
bool collide = false;
char upperSave = terrainUpper[HERO_HORIZONTAL_POSITION];
char lowerSave = terrainLower[HERO_HORIZONTAL_POSITION];
byte upper, lower;
switch (position) {
case HERO_POSITION_OFF:
upper = lower = SPRITE_TERRAIN_EMPTY;
break;
case HERO_POSITION_RUN_LOWER_1:
upper = SPRITE_TERRAIN_EMPTY;
lower = SPRITE_RUN1;
break;
case HERO_POSITION_RUN_LOWER_2:
upper = SPRITE_TERRAIN_EMPTY;
lower = SPRITE_RUN2;
break;
case HERO_POSITION_JUMP_1:
case HERO_POSITION_JUMP_8:
upper = SPRITE_TERRAIN_EMPTY;
lower = SPRITE_JUMP;
break;
case HERO_POSITION_JUMP_2:
case HERO_POSITION_JUMP_7:
upper = SPRITE_JUMP_UPPER;
lower = SPRITE_JUMP_LOWER;
break;
case HERO_POSITION_JUMP_3:
case HERO_POSITION_JUMP_4:
case HERO_POSITION_JUMP_5:
case HERO_POSITION_JUMP_6:
upper = SPRITE_JUMP;
lower = SPRITE_TERRAIN_EMPTY;
break;
case HERO_POSITION_RUN_UPPER_1:
upper = SPRITE_RUN1;
lower = SPRITE_TERRAIN_EMPTY;
break;
case HERO_POSITION_RUN_UPPER_2:
upper = SPRITE_RUN2;
lower = SPRITE_TERRAIN_EMPTY;
break;
}
if (upper != ' ') {
terrainUpper[HERO_HORIZONTAL_POSITION] = upper;
collide = (upperSave == SPRITE_TERRAIN_EMPTY) ? false : true;
}
if (lower != ' ') {
terrainLower[HERO_HORIZONTAL_POSITION] = lower;
collide |= (lowerSave == SPRITE_TERRAIN_EMPTY) ? false : true;
}
byte digits = (score > 9999) ? 5 : (score > 999) ? 4 : (score > 99) ? 3 : (score > 9) ? 2 : 1;
lcd.setCursor(16 - digits,0);
lcd.print(score);
terrainUpper[HERO_HORIZONTAL_POSITION] = upperSave;
terrainLower[HERO_HORIZONTAL_POSITION] = lowerSave;
return collide;
}
void setup(){
pinMode(PIN_READWRITE, OUTPUT);
digitalWrite(PIN_READWRITE, LOW);
pinMode(PIN_CONTRAST, OUTPUT);
digitalWrite(PIN_CONTRAST, LOW);
pinMode(PIN_BUTTON, INPUT);
digitalWrite(PIN_BUTTON, HIGH);
pinMode(PIN_AUTOPLAY, OUTPUT);
digitalWrite(PIN_AUTOPLAY, HIGH);
pinMode(PIN_BUZZER,OUTPUT);//initialize the buzzer pin as an output
digitalWrite(PIN_BUZZER, LOW);
initializeGraphics();
lcd.begin(16, 2);
}
void loop(){
static byte heroPos = HERO_POSITION_RUN_LOWER_1;
static byte newTerrainType = TERRAIN_EMPTY;
static byte newTerrainDuration = 1;
static bool playing = false;
static bool blink = false;
static unsigned int distance = 0;
if (!playing) {
drawHero((blink) ? HERO_POSITION_OFF : heroPos, terrainUpper, terrainLower,
distance >> 3);
if (blink) {
lcd.setCursor(0,0);
lcd.print("Press Start");
}
delay(250);
blink = !blink;
if (buttonPushed) {
initializeGraphics();
heroPos = HERO_POSITION_RUN_LOWER_1;
playing = true;
buttonPushed = false;
distance = 0;
}
return;
}
if (buttonPushed) {
if (heroPos <= HERO_POSITION_RUN_LOWER_2) heroPos =
HERO_POSITION_JUMP_1;
buttonPushed = false;
digitalWrite(PIN_BUZZER,HIGH);
}
digitalWrite(PIN_AUTOPLAY, terrainLower[HERO_HORIZONTAL_POSITION + 2] ==
SPRITE_TERRAIN_EMPTY ? HIGH : LOW);
}
delay(100);
digitalWrite(PIN_BUZZER,LOW);
}
34) Arduino Turn Your RC Car to Bluetooth RV Car
COMPONENTS AND SUPPLIES
SCHEMATICS
CODE
void setup() {
Serial.begin(9600);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(9, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
} if(var=='H')
{ digitalWrite(frled1,HIGH);
}
if(var=='B')
{
analogWrite(speeden,150);
digitalWrite(6,HIGH);
digitalWrite(7,LOW);
digitalWrite(8,HIGH);
digitalWrite(9,LOW);
digitalWrite(bcled1,HIGH);
}
if(var=='X')
{digitalWrite(9,LOW);
digitalWrite(8,LOW);
digitalWrite(7,LOW);
digitalWrite(6,LOW);
digitalWrite(frled1,LOW);
digitalWrite(bcled1,LOW
);
}
if(var=='L')
{digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,HIGH);
digitalWrite(9,LOW);
}
if(var=='R')
{digitalWrite(6,HIGH);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);;
}
}
35) Arduino Digital Dice
COMPONENTS AND SUPPLIES
Breadboard (generic)
× 1
× 1
USB-A to B Cable
× 1
× 1
× 1
× 1
This project was based on the idea that I had become bored of my
normal standard game dice. So, to fix my boredom, I decided to use my
Arduino LCD and standard push button (with a breakout board) and I
had the Arduino read the state of the signal pin on the button board to
high or low (high if button not depressed) (low if not). Depending on
the state it would either stay on the main screen or show that the dice
are rolling and then print out two random numbers from 1-6 (like a
dice).
SCHEMATICS
CODE
#include <LiquidCrystal.h>
long randNumber;
int Led = 13; //define LED port
int Shock = 2; //define shock port
int val;//define digital variable val
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12 );
byte customChar[] = {
B00000,
B00000,
B11111,
B11001,
B10101,
B10011,
B11111,
B00000
};
void setup()
{
lcd.begin(16, 2);
lcd.createChar(0, customChar);
lcd.home();
pinMode(Led, OUTPUT); //define LED as a output port
randomSeed(analogRead(0));
pinMode(Shock, INPUT); //define shock sensor as a output port
lcd.write(byte( 0));
lcd.print("Digital dice");
lcd.write(byte( 0));
delay(1000);
}
void loop()
{
val = digitalRead(Shock); //read the value of the digital interface 3 assigned to val
if (val == LOW) //when the shock sensor have signal do the following
{
lcd.clear();
lcd.print("Rolling dice...");
delay(4000);
lcd.clear();
lcd.setCursor(0, 0);
randNumber = random(1,7);
lcd.print("Dice 1 = ");
lcd.print(randNumber);
lcd.setCursor(0, 1);
randNumber = random(1,7);
lcd.print("Dice 2 = ");
lcd.print(randNumber);
delay(150);
}
36)Arduino I2S Theremin
COMPONENTS AND SUPPLIES
Arduino MKR Zero
× 1
Breadboard (generic)
× 1
× 1
Adafruit MAX98357A
× 1
× 1
RobotGeek Slider
× 2
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
*
This code is based on Adafruit's work
https://github.com/adafruit/Adafruit_ZeroI2S/blob/master/examples/tone_generator/tone_generator.ino
Make an I2S Theremin using an Arduino MKRZero, an I2S DAC and two slider
potentiometers!
*/
#include <I2S.h>
const int frequencyPin = A0; //pin connected to the pot who determines the frequency of the
signal
const int amplitudePin = A1; //pin connected to the pot who determines the amplitude of the
signal
const int button = 6; //pin connected to the button to put the frequency as output
void setup() {
Serial.begin(9600); //configue the serial ort
// Initialize the I2S transmitter.
if (!I2S.begin(I2S_PHILIPS_MODE, sampleRate, 16)) {
Serial.println("Failed to initialize I2S!");
while (1);
}
generateSine(); // fill buffer with sine values
pinMode(button, INPUT_PULLUP); //put the button pin in input pullup
}
void loop() {
if (digitalRead(button) == LOW) {
float frequency = map(analogRead(frequencyPin), 0, 1023, minFrequency, maxFrequency);
//map frequency
int amplitude = map(analogRead(amplitudePin), 0, 1023, minVolume, maxVolume); //map
amplitude
playWave(frequency, 0.1, amplitude); //play sound
//print values on serial
Serial.print("Frequency = ");
Serial.println(frequency);
Serial.print("Amplitude = ");
Serial.println(amplitude);
}
}
void generateSine() {
for (int i = 0; i < wavSize; ++i) {
sine[i] = ushort(float(100) * sin(2.0 * PI * (1.0 / wavSize) * i)); //100 is used to not have
small numbers
}
}
I2S.write(sample);
I2S.write(sample);
}
}
37) Voice Control Home Automation System Using Arduino and HC-
05
× 1
× 1
Two AC Bulbs(Red,Yellow)
× 1
Relay (generic)
× 1
Using 4 Channel Relay
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
String voice;
int RED = 2;
int YELLOW = 3;
void RedOn(){
digitalWrite (RED, LOW);
}
void RedOff(){
digitalWrite (RED, HIGH);
}
void YellowOn(){
digitalWrite (YELLOW, LOW);
}
void YellowOff(){
digitalWrite (YELLOW, HIGH);
}
void allon() {
digitalWrite (RED, LOW);
digitalWrite (YELLOW, LOW);
}
void alloff() {
digitalWrite (RED, HIGH);
digitalWrite (YELLOW, HIGH);
}
void setup() {
Serial.begin(9600);
pinMode(RED, OUTPUT);
pinMode(YELLOW, OUTPUT);
digitalWrite (RED, HIGH);
digitalWrite (YELLOW, HIGH);
}
void loop() {
while(Serial.available()) {
delay(10);
char c=Serial.read();
if(c=='#')
{
break;
}
voice += c;
}
if (voice.length() > 0) {
Serial.println(voice);
if (voice == "on" || voice== "all on")
{
allon() ;
}
else if (voice == "off" || voice=="all off")
{
alloff() ;
}
else if(voice =="red" || voice =="red on"){
RedOn();
}
else if(voice =="red off"){
RedOff();
}
else if(voice =="yellow" || voice =="yellow on"){
YellowOn();
}
else if(voice =="yellow off"){
YellowOff();
}
voice="";
}
}
× 1
Arduino IDE
#define CLIK 8
#define ECHO 2
#define TRIG 3
void setup() {
pinMode(CLIK, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(TRIG, OUTPUT);
digitalWrite(TRIG, LOW);
digitalWrite(CLIK, LOW);
}
void trigger() {
/* trigger the sensor */
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
}
float measure() {
/* measure the distance between the sensor and the obstacle */
float d = 0.;
for (int i = 0; i < 15; i++) {
trigger();
unsigned long T = pulseIn(ECHO, HIGH);
d += c*T/2.;
}
return d;
}
int status = HIGH; // the current status of the relay
void loop() {
float d = measure();
unsigned long trigger = 1000./(d*d);
unsigned long r = random(1000);
if (r < trigger) {
digitalWrite(CLIK, status);
if (status == HIGH) {
status = LOW;
} else {
status = HIGH;
}
}
}
× 1
× 2
Buzzer
× 1
× 2
Please use this pin information. You can change pin number as per
yours but in that case you have to change code also.
Arduino based collision detection warning system
Please follow this schematic to connect hardware to board and pin
numbers.
CODE
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(13, OUTPUT);
pinMode(2, OUTPUT);
Serial.begin(9600);
}
// digitalWrite(13, LOW);
// turn the LED on (HIGH is the voltage level)
else
{
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
// wait for a second
}
tone(buzz, 2000);
delay(100);
noTone(buzz);
delay(100);
tone(buzz, 2000);
delay(100);
noTone(buzz);
delay(100);
tone(buzz, 2000);
delay(100);
noTone(buzz);
tone(buzz, 2000);
delay(100);
noTone(buzz);
delay(100);
}
else
{
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
// wait for a second
}
}
40) Arduino GPS Data Logger Real Time Curve Max Height and Max
Speed
COMPONENTS AND SUPPLIES
× 1
CODE
#define OLED_RESET 5
TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);
int x=80;
int xh=80;
int maxhigh=0;
int maxspeed = 0, speed1 = 0;
int high1 = 0;;
void setup()
{
Serial.begin(9600);
ss.begin(GPSBaud);
tft.initR(INITR_GREENTAB);
tft.fillScreen(ST7735_BLACK);
tft.setCursor(5, 58);
tft.setTextSize(1);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
tft.print("initilisation");
void loop()
{
tft.setTextSize(1);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
tft.setCursor(5, 44);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
tft.print("Latitude :");
tft.setTextColor(ST7735_CYAN,ST7735_BLACK);
tft.print(gps.location.lat(), 6);
tft.setCursor(5, 58);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
tft.print("Longitude :");
tft.setTextColor(ST7735_CYAN,ST7735_BLACK);
tft.print(gps.location.lng(), 6);
smartDelay(400);
}
}
}
// delai pour une bonne recption
static void smartDelay(unsigned long ms)
{
unsigned long start = millis();
do
{
while (ss.available())
gps.encode(ss.read());
} while (millis() - start < ms);
}
void cadre() {
// affichage ecran
//cadre
tft.drawLine(0,0,130,0,ST7735_RED);
tft.drawLine(0,1,130,1,ST7735_RED);
tft.drawLine(0,158,130,158,ST7735_RED);
tft.drawLine(0,142,130,142,ST7735_RED);
tft.drawLine(0,141,130,141,ST7735_RED);
tft.drawLine(0,107,130,107,ST7735_RED);
tft.drawLine(0,108,130,108,ST7735_RED);
tft.drawLine(80,108,80,140,ST7735_RED);
tft.drawLine(81,109,81,140,ST7735_RED);
tft.drawLine(80,70,80,108,ST7735_RED);
tft.drawLine(81,70,81,108,ST7735_RED);
tft.drawLine(0,159,130,159,ST7735_RED);
tft.drawLine(0,0,0,156,ST7735_RED);
tft.drawLine(1,1,1,157,ST7735_RED);
tft.drawLine(127,0,127,156,ST7735_RED);
tft.drawLine(126,0,126,156,ST7735_RED);
tft.drawLine(0,35,130,35,ST7735_RED);
tft.drawLine(0,36,130,36,ST7735_RED);
tft.drawLine(0,70,130,70,ST7735_RED);
tft.drawLine(0,71,130,71,ST7735_RED);
void courbe() {
int nouvelleValeur;
x++;
tft.drawPixel(x,nouvelleValeur,ST7735_CYAN);
if (x>123) {
x=80;
tft.fillRect(82,110,43,30,ST7735_BLACK);
}
}
void courbeh() {
int nouvelleValeurh;
// converison vitesse max (350 km/h) en pixel
nouvelleValeurh = map((gps.altitude.meters()), 0, 1000, 104, 72); // car l'cran a 64 pixels de
haut
xh++;
tft.drawPixel(xh,nouvelleValeurh,ST7735_CYAN);
if (xh>123) {
xh=80;
tft.fillRect(82,72,43,35,ST7735_BLACK);
}
}
void vmax() {
// calcul vitese maximum
speed1 = (gps.speed.kmph());
if ( speed1 > maxspeed) {
maxspeed = speed1;
}
}
void hmax() {
// calcul altitude maximum
high1 = (gps.altitude.meters());
if ( high1 > maxhigh) {
maxhigh = high1;
}
}
sauvegarde SD
#include <SPI.h>
#include<SD.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#define cs 10
#define dc 9
#define rst 8
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, rst);
static const int RXPin = 4, TXPin = 3; //GPS communication
static const uint32_t GPSBaud = 9600;
const int cs_sd=4;
#define OLED_RESET 5
TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);
int x=80;
int xh=80;
int maxhigh=0;
int maxspeed = 0, speed1 = 0;
int high1 = 0;;
void setup()
{
Serial.begin(9600);
ss.begin(GPSBaud);
tft.initR(INITR_GREENTAB);
tft.fillScreen(ST7735_BLACK);
tft.setCursor(5, 58);
tft.setTextSize(1);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
tft.print("initilisation");
tft.setCursor(5, 70);
tft.print("init SD");
delay(1000);
if(!SD.begin(cs_sd)) //Condition vrifiant si la carte SD est prsente dans l'appareil
{
tft.setCursor(5, 82);
tft.print("Defaut SD");
return;
}
tft.setCursor(5, 82);
tft.print("Carte SD OK");
delay(1000);
tft.fillScreen(ST7735_BLACK);
void loop()
{
tft.setTextSize(1);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
cadre();
tft.setCursor(5, 44);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
tft.print("Latitude :");
tft.setTextColor(ST7735_CYAN,ST7735_BLACK);
tft.print(gps.location.lat(), 6);
tft.setCursor(5, 58);
tft.setTextColor(ST7735_GREEN,ST7735_BLACK);
tft.print("Longitude :");
tft.setTextColor(ST7735_CYAN,ST7735_BLACK);
tft.print(gps.location.lng(), 6);
smartDelay(400);
tft.drawLine(80,108,80,140,ST7735_RED);
tft.drawLine(81,109,81,140,ST7735_RED);
tft.drawLine(80,70,80,108,ST7735_RED);
tft.drawLine(81,70,81,108,ST7735_RED);
tft.drawLine(0,159,130,159,ST7735_RED);
tft.drawLine(0,0,0,156,ST7735_RED);
tft.drawLine(1,1,1,157,ST7735_RED);
tft.drawLine(127,0,127,156,ST7735_RED);
tft.drawLine(126,0,126,156,ST7735_RED);
tft.drawLine(0,35,130,35,ST7735_RED);
tft.drawLine(0,36,130,36,ST7735_RED);
tft.drawLine(0,70,130,70,ST7735_RED);
tft.drawLine(0,71,130,71,ST7735_RED);
void courbe() {
int nouvelleValeur;
// converison vitesse max (350 km/h) en pixel
nouvelleValeur = map((gps.speed.kmph()), 0, 150, 137, 110); // car l'cran a 64 pixels de
haut
x++;
tft.drawPixel(x,nouvelleValeur,ST7735_CYAN);
if (x>123) {
x=80;
tft.fillRect(82,110,43,30,ST7735_BLACK);
}
}
void courbeh() {
int nouvelleValeurh;
xh++;
tft.drawPixel(xh,nouvelleValeurh,ST7735_CYAN);
if (xh>123) {
xh=80;
tft.fillRect(82,72,43,35,ST7735_BLACK);
}
}
void vmax() {
// calcul vitese maximum
speed1 = (gps.speed.kmph());
if ( speed1 > maxspeed) {
maxspeed = speed1;
}
}
void hmax() {
// calcul altitude maximum
high1 = (gps.altitude.meters());
if ( high1 > maxhigh) {
maxhigh = high1;
}
}
× 2
NECESSARY TOOLS AND MACHINES
3D Printer (generic)
APPS AND ONLINE SERVICES
Arduino IoT Cloud
In order to make it play we need the AudioZero library. For better quality
the Audio file to store on the SD card must be in the .wav format with
88200 Hz, 8-bit unsigned PCM mono quality. This type of file can be
easily obtained using audio programs like audacity.
The Transmitter
Please note that for this example we presume our door is already
connected to a relay that can lock and unlock the door by switching on and
off.
What remains to do is simply to connect our board to this relay and to the
front door button.
SCHEMATICS
Receiver
Transmitter
CODE
Doorbell Receiver
#include <SPI.h>
#include <WiFi101.h>
#include <WiFiSSLClient.h>
#include <MQTT.h>
#include <SD.h>
#include <AudioZero.h>
MQTTClient client;
WiFiSSLClient net;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, pass);
client.begin("mqtt-dev.arduino.cc", 8883, net);
connect();
client.subscribe("/tommasltrz/DoorbellTransmitter/bell");
// setup SD-card
Serial.print("Initializing SD card...");
if (!SD.begin(6)) {
Serial.println(" failed!");
while (true);
}
Serial.println(" done.");
pinMode(4, INPUT);
attachInterrupt(4, buttonPressedCallback, RISING);
}
void connect() {
Serial.print("checking wifi...");
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, p);
delay(4000);
}
Serial.println("connecting...");
while (!client.connect(deviceName, deviceId, devicePsw)) {
Serial.print(".");
}
Serial.println("connected!");
}
void loop() {
client.loop();
if (buttonPressed) {
client.publish("/tommasltrz/DoorbellReciever/bell", "open");
Serial.println("publishing up");
buttonPressed = false;
delay(1000);
}
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
if (payload.equals("ring")) {
AudioZero.begin(2 * 44100); // 44100kHz stereo => 88200 sample rate
File myFile = SD.open("test.wav"); // open wave file from sdcard
if (!myFile) {
Serial.println("error opening test.wav");
while (true);
}
Serial.print("Playing");
AudioZero.play(myFile);
Serial.println("End");
AudioZero.end();
}
}
void buttonPressedCallback() {
buttonPressed = true;
}
Doorbel Transmitter
#include <SPI.h>
#include <WiFi101.h>
#include <WiFiSSLClient.h>
#include <MQTTClient.h>
MQTTClient client;
WiFiSSLClient net;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
client.begin("mqtt-dev.arduino.cc", 8883, net);
connect();
client.subscribe("/tommasltrz/DoorbellReciever/bell");
pinMode(4, INPUT);
pinMode (6, OUTPUT);
attachInterrupt(4, buttonPressedCallback, RISING);
digitalWrite(6, LOW);
}
void connect() {
Serial.print("checking wifi...");
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, password);
delay(4000);
}
Serial.println("connecting...");
while (!client.connect(deviceName, deviceId, devicePsw)) {
Serial.print(".");
}
Serial.println("connected!");
}
void loop() {
client.loop();
if (buttonPressed) {
client.publish("/tommasltrz/DoorbellTransmitter/bell", "ring");
Serial.println("publishing up");
buttonPressed = false;
delay(1000);
}
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
if (payload.equals("open")) {
digitalWrite(6, HIGH);
delay(1000);
digitalWrite(6, LOW);
buttonPressed = false;
}
}
void buttonPressedCallback() {
buttonPressed = true;
}
× 1
LED (generic)
× 1
Breadboard (generic)
× 1
Step 1
The first thing I made was the wooden housing. Then I decorate the body.
I glued the body of the game table.
Step 2
After that, it was necessary to strengthen the housing wall qualitatively. I
used glue, nails and screws.
This action can be done either now or later, but I did it at first. I glued
down the right side. I measured the height - it was 13 cm, and the lowest
part body - 11 cm. The higher the slope, the more difficult you will run the
iron (or another material ball). The body length received 50 cm.
Invisible player hardware component.
Designing and painting most of the board.
Step 3
Production of some of the details on the 3D printer.
Opening holes on the upper platform. I have made but not yet connected
the first actuator.
The Circuit
Wiring
The sensors
SCHEMATICS
CODE
main game
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C myDisplay(0x27,16,2);
#define greenLED 2
#define yellowLED 3
#define redLED 4
#define sensor1 8
#define sensor2 9
#define sensor3 10
#define sensor4 11
#define sensor5 12
#define sensor6 13
void setup()
{
myDisplay.init();
myDisplay.backlight();
myDisplay.print("PLAY!");
delay(2000);
myDisplay.setCursor(0,0);
myDisplay.print(" ");
myDisplay.setCursor(6,0);
myDisplay.print("GO GO GO");
delay(2000);
myDisplay.setCursor(0,0);
myDisplay.print(" ");
Serial.begin(9600);
pinMode(sensor1, INPUT);
pinMode(sensor2, INPUT);
pinMode(sensor3, INPUT);
pinMode(sensor4, INPUT);
pinMode(sensor5, INPUT);
pinMode(sensor6, INPUT);
pinMode(greenLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(redLED, OUTPUT);
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, LOW);
int i=0;
void loop() {
if (digitalRead(sensor1)==HIGH){
i=i+20;
myDisplay.clear();
myDisplay.setCursor(5,0);
myDisplay.print("+20!");
digitalWrite(greenLED, HIGH);
delay(2000);
digitalWrite(greenLED, LOW);
myDisplay.clear();
}
if (digitalRead(sensor2)==HIGH){
i=i+50;
myDisplay.clear();
myDisplay.setCursor(5,0);
myDisplay.print("+50!");
digitalWrite(greenLED, HIGH);
digitalWrite(yellowLED, HIGH);
delay(2000);
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
myDisplay.clear();
}
if (digitalRead(sensor3)==HIGH){
i=i+100;
myDisplay.clear();
myDisplay.setCursor(5,0);
myDisplay.print("+100!");
digitalWrite(greenLED, HIGH);
digitalWrite(yellowLED, HIGH);
digitalWrite(redLED, HIGH);
delay(2000);
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, LOW);
myDisplay.clear();
}
if (digitalRead(sensor4)==HIGH){
i=i+20;
myDisplay.clear();
myDisplay.setCursor(5,0);
myDisplay.print("+20!");
digitalWrite(greenLED, HIGH);
delay(2000);
digitalWrite(greenLED, LOW);
myDisplay.clear();
}
if (digitalRead(sensor5)==HIGH){
i=i+50;
myDisplay.clear();
myDisplay.setCursor(5,0);
myDisplay.print("+50!");
digitalWrite(greenLED, HIGH);
digitalWrite(yellowLED, HIGH);
delay(2000);
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
myDisplay.clear();
}
if (digitalRead(sensor6)==HIGH){
i=i+100;
myDisplay.clear();
myDisplay.setCursor(5,0);
myDisplay.print("+100!");
digitalWrite(greenLED, HIGH);
digitalWrite(yellowLED, HIGH);
digitalWrite(redLED, HIGH);
delay(2000);
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, LOW);
myDisplay.clear();
}
if (i>=500){
myDisplay.clear();
myDisplay.setCursor(4,0);
myDisplay.print("YOU WIN!");
for (int j=0; j<=15; j=j+1){
digitalWrite(greenLED, HIGH);
digitalWrite(yellowLED, HIGH);
digitalWrite(redLED, HIGH);
delay(100);
digitalWrite(greenLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(redLED, LOW);
delay(100);
}
i=0;
myDisplay.clear();
myDisplay.setCursor(0,0);
myDisplay.print("New Game");
delay(2000);
myDisplay.setCursor(0,0);
myDisplay.print(" ");
myDisplay.setCursor(6,0);
myDisplay.print("GO!");
delay(2000);
myDisplay.setCursor(0,0);
myDisplay.print(" ");
}
myDisplay.setCursor(0,0);
myDisplay.print("Your Score:");
myDisplay.setCursor(0,1);
myDisplay.print(i,DEC);
}
for servo
#include <Servo.h>
#define servopin 5
Servo myservo;
void setup()
{
myservo.attach(servopin);
myservo.write(90);
void loop() {
myservo.write(160);
delay(1000);
myservo.write(30);
delay(1000);
}
Arduino Yun
× 1
Breadboard (generic)
× 1
Adafruit IO
Have you ever wanted a system that keeps track of the time at which your
employees arrive to work, have you ever wanted to check the time at
which a person enters your room (I have), this device aims to make all of
that as simple as possible. RFIDDropboxLogger will keep track of
everyone scanning an RFID card using an RFID module and will write to
Dropbox whenever it happens to keep you updated with all the
information. Thanks to IFTTT, this is all possible and easy to do.
A Single Component
RFID Module
Result
Functionality
This project will require IFTTT to work, to connect to IFTTT we will have
to use another cloud-based platform called Adafruit IO. This platform will
allow us to easily connect our Arduino Yún to the Cloud and then to
IFTTT. Here is an image illustrating the process.
The Arduino Yún will monitor the RFID module searching for a card,
when one is detected, the micro controller will increment the value to send
by 1 and then parse the value to Adafruit IO. Using an IFTTT trigger,
whenever a change in value is detected on Adafruit IO, (in our case, the
variable incrementation) the app will trigger a Dropbox trigger which will
append the time at which an RFID card had been scanned to a text file.
Note that this operation will last approximately 15 minutes. Here is an
image illustrating the code.
Code Overview
If(RFID Card Present) will check if an RFID card is present.
Increase value will increment the value to send by 1.
Send value will send the incremented value to Adafruit IO.
An Adafruit IO and IFTTT accounts are required to create the project, a
guide to creating these is in Constructing the Project below.
Benefits
The user operating this project will benefit in:
Monitoring RFID usage
Monitoring time of RFID usage
Monitoring amount of times the RFID module has been used
Constructing the Project
Step 1: Required Apparatus
The project requires very few things.
Jumper Wires (Male to Male & Male to Female)
1 Arduino Yún
1 RFID Module (RC522)
1 Breadboard
The Schematics
Step 3: Acknowledging the Code
There are three main parts to the code:
connect to MQTT
search for RFID
send value
Each part will be explained below.
Connect to MQTT
void MQTTConnect()
{
int8_t ret;
if(mqtt.connected()) // if already connected
{
return;
}
if(proDebug == 1)
{
Serial.println("Connecting to Server");
}
while((ret = mqtt.connect()) != 0) // attempt to connect
{
if(proDebug == 1)
{
Serial.print(" Error - ");
Serial.println(mqtt.connectErrorString(ret));
Serial.println(" Attempting Reconnection in 5 seconds");
}
mqtt.disconnect();
delay(5000);
}
if(proDebug == 1)
{
Serial.println(" Success - Connection Established");
Serial.println("Scan Card");
Serial.println("");
}
}
This part of the code will connect the Arduino to MQTT services on
Adafruit IO, this will allow the Arduino Yún to write to a Feed on
Adafruit IO.
Search for RFID
if(!mfrc522.PICC_IsNewCardPresent())
{
return;
}
if(!mfrc522.PICC_ReadCardSerial())
{
return;
}
String content = ""; // string to store card id
// store card id
for(byte i = 0; i < mfrc522.uid.size; i++)
{
// store the card id number in a variable
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
This part will search for a new RFID card and continue with the code once
one is found, the card's ID is also collected and stored to a variable though
not essential.
Send Value
valueToSend++; // increase value to trigger write
if(proDebug == 1)
{
Serial.print("Publishing ");
Serial.println(valueToSend);
}
Console.println(valueToSend);
if(!sendToDropbox.publish(valueToSend))
{
if(proDebug == 1)
{
Serial.println(F(" Error - Failed to Send Data"));
}
}
else
{
if(proDebug == 1)
{
Serial.println(F(" Success - Data Sent"));
}
}
This part will increase the send value variable by 1 so that IFTTT can
detect a change. Then the value will be sent to Adafruit IO, after the
variable is parsed, the Arduino will verify that it has been sent.
This loop will repeat continuously allowing cards to be constantly
scanned, it may take about 15 minutes for IFTTT to check if the value on
the Adafruit IO feed has changed.
Setting up the Variables
Ensure that all variables marked TODO are edited to preference. Insert
your Adafruit IO credentials in the appropriate sections (configuration
illustrated below) and set proDebug to 1 or 0. Note that mode 1 will
enable debugging and will require connection to a Mac/PC and the Serial
Monitor open to work. Default set to 1.
Libraries
Bridge & Bridge Client - copyright (c) Arduino LLC under the GNU
Lesser General Public Licence, this library is in the public domain.
Console - copyright (c) 2013 Arduino LLC under the GNU Lesser
General Public Licence, this library is in the public domain.
SPI - copyright (c) 2015 Hristo Gochkov under the GNU Lesser
General Public Licence, this library is in the public domain.
MFRC522 - this library is in the public domain.
Adafruit MQTT & Adafruit MQTT Client - copyright (c) 2015 Adafruit
Industries under the MIT Licence.
Adafruit IO Setup
Step 1: Download libraries
The first thing to do is to open the Arduino Library manager and search
for Adafruit_MQTT_Library, and then download it.
Step 2: Create an Adafruit IO account
Follow the images below illustrating this process.
Step 3: Configure Adafruit IO
Follow these images to configure feeds for the Adafruit IO communication
with IFTTT.
Click on the feeds button in the menu on the left side of the page
Repeat the steps to create another feed called "subscribeA" and you
are done
IFTTT Setup
Nearly there, now we have to configure IFTTT to finish the project off.
Use the following steps to configure IFTTT; if you already have an IFTTT
account, you may skip the first step.
Step 1: Create an IFTTT Account
You can download the IFTTT app for Apple or Android if you want, the
setup in this tutorial will be done on the app, but it can also be done on
the IFTTT Website. Follow the images below to set up your account.
Open ifttt.com, Click the Sign Up button at the top right corner of the page
Choose to Sign Up with Google or Facebook and fallow the steps
provided
Step 2: Create a Trigger
We will use the app for this step as it is slightly easier, follow the images
for the setup.
Open the IFTTT app, Click on My Applets at the bottom of the screen
Click on the + button at the top right corner of the page
select the + button on the page that opens
On the fallowing page, search for "Adafruit" in the search bar and
click on the trigger below, you will be instructed to connect to Adafruit,
fallow the steps
Click on the Feed Name Box and choose sendToDropbox, click next
when you are done.
Set the name, content and folder path of the file, for best experience,
keep content the same as in image, click next
Setup
Follow the images below to get the credentials required for the project.
Now click on the Key icon at the top right of the page
Copy the Active key and paste it in the required location in the
Arduino Sketch
Obtaining your username is easy, just copy your username and paste it in
the required location int the Arduino Sketch. Now connect your Arduino
Yún to your Mac/PC and upload the code.
Background
I was recently thinking of a way to track the number of times an RFID
module has been used, and to monitor the time at which it has. I happened
to think about Dropbox at the same time and decided to create an Arduino
Yun that parses RFID module operation data to a text file on Dropbox.
The Arduino Yun will monitor the amount of times that the RFID module
has been activated and if set up, IFTTT will send the user a notification
with the number of times that the module has been activated for.
RFIDDropboxLogger
SCHEMATICS
CODE
#include <Bridge.h>
#include <Console.h>
#include <BridgeClient.h>
#include <SPI.h>
#include <MFRC522.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define SS_PIN 10
#define RST_PIN 5
BridgeClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER,
AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
MFRC522 mfrc522(SS_PIN, RST_PIN);
// Initialise Feeds
Adafruit_MQTT_Publish sendToDropbox =
Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME
"/feeds/sendToDropbox");
Adafruit_MQTT_Subscribe subscribeA =
Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME
"/feeds/subscribeA");
void MQTTConnect()
{
int8_t ret;
if(proDebug == 1)
{
Serial.println("Connecting to Server");
}
if(proDebug == 1)
{
Serial.println(" Success - Connection Established");
Serial.println("Scan Card");
Serial.println("");
}
}
void setup()
{
Bridge.begin();
Console.begin();
SPI.begin();
if(proDebug == 1)
{
Serial.begin(9600);
while(!Serial) {};
}
mfrc522.PCD_Init();
delay(500);
mqtt.subscribe(&subscribeA); // start subscription
}
void loop()
{
MQTTConnect(); // connect to service
Adafruit_MQTT_Subscribe *subscription;
if(!mfrc522.PICC_IsNewCardPresent())
{
return;
}
if(!mfrc522.PICC_ReadCardSerial())
{
return;
}
// store card id
for(byte i = 0; i < mfrc522.uid.size; i++)
{
// store the card id number in a variable
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
if(proDebug == 1)
{
Serial.print("Publishing ");
Serial.println(valueToSend);
}
Console.println(valueToSend);
if(!sendToDropbox.publish(valueToSend))
{
if(proDebug == 1)
{
Serial.println(F(" Error - Failed to Send Data"));
}
}
else
{
if(proDebug == 1)
{
Serial.println(F(" Success - Data Sent"));
}
}
delay(500);
}
44) How to Make an Ultrasonic Ruller with Arduino and HC-SR04
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
Breadboard (generic)
× 1
**Optional**
USB-A to B Cable
This will help you to connect the
× 1
laptop with Arduino
Laptop or computer
× 1
APPS AND ONLINE SERVICES
Arduino IDE
To program and upload to your arduino
Well I was sitting at home wondering how to measure how far away
things are without getting up of my couch. So I took a look at some
projects. They were pretty lit but they didn't have inches and
millimetres.
SCHEMATICS
Ultrasonic Ruler
Just wire the:
And then just copy and paste the code above in your Arduino IDE. To
see the distance just go to Tools -> Serial Monitor or just put
Ctrl+Shift+M or for mac just Command+Shift+M.
CODE
Arduino MKR1000
× 1
SCHEMATICS
/*
-
CODE
#include <I2CSoilMoistureSensor.h>
#include <Wire.h>
#include <SimpleDHT.h>
int pinDHT22 = 6;
SimpleDHT22 dht22;
int sensorPin = A0; // select the input pin for the ga1a light sensor
I2CSoilMoistureSensor soilMoistureSensor(0x60);
float rawRange = 1024; // 3.3v
float logRange = 5.0; // 3.3v = 10^5 lux
float soilTemperature;
int soilMoisture;
int lightValue;
float airTemperature;
int airHumidity;
void setup() {
Wire.begin();
Serial.begin(9600);
///////////////////////////////////////////////
//get all the data from the soul moisture sensor
///////////////////////////////////////////////
while (soilMoistureSensor.isBusy()) delay(50); // available since FW
2.3
soilMoisture=soilMoistureSensor.getCapacitance();
soilTemperature=soilMoistureSensor.getTemperature()/(float)10;
soilMoistureSensor.sleep(); // available since FW 2.3
///////////////////////////////////
//get the data from the dht sensor
///////////////////////////////////
float temperature = 0;
float humidity = 0;
int err = SimpleDHTErrSuccess;
///////////////////////////////////
//get the data from the light sensor
///////////////////////////////////
int rawValue = analogRead(sensorPin);
lightValue=RawToLux(rawValue);
void printValue(){
Serial.print("Soil Moisture Capacitance: ");
Serial.print(", Temperature: ");
Serial.print(", Light: ");
}
× 1
Resistor 1k ohm
× 3
Resistor 3k ohm
× 1
4x3 matrix 12 key array switch
keypad × 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
In the diagram the resistor R1 is connected toline 2 because the one on line
1 has drawn it with a wire, so the resistorreferences have been scaled by
one. Pin assignments can be modified accordingto needs, as long as they
are pin configurable as analog.
Of course, if Arduino is powered at 3.3V, nothing would change because
the ADC converter as default uses the supplyvoltage and the ADC
numbers don’t change.
To test the program, not having a keyboardof this type, I built it with
recycled keys, the figure below shows myprototype. The 5-pin right
connector is used to wire it to Arduino.
SCHEMATICS
CODE
// limits of keyboard output values:
const int NADCm100[4] = {923,669,412,156};
const int NADCp100[4] = {1123,869,612,356};
const char key[13] = {'1','4','7','C','2','5','8','0','3','6','9','E'};
int keyval[3];
int i,colp,val;
void setup(){
Serial.begin(9600); // used with serial monitor
}
void loop() {
char k;
k = KeyPad();// read keypad
if (k != 'N'){ // a key was pressed
Serial.print("key = ");
Serial.println(k);
delay(500);
}
}
Z80 Processor
× 1
Breadboard (generic)
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
z80-test.inoC/C++
#include "memory.h"
/*Wiring:
Address Lines:
Arduino Pin 22..29 <---> Z80 A0..A7
Data Lines:
Arduino Pin 49..42 <---> Z80 D0..D7
Control lines:
Arduino Pin 10 <---> Z80 Pin 6 (CLK)
Arduino Pin 19 <---> Z80 Pin 21 (RD)
Arduino Pin 18 <---> Z80 Pin 22 (WR)
Arduino Pin A9 <---> Z80 Pin 19 (MREQ)
Arduino Pin A10 <---> Z80 Pin 20 (IORQ)
Arduino Pin 40 <---> Z80 PIN 26 (RESET)
*/
//Working memory
uint8_t memory[1024];
//Z80 Out
//Port D
#define RD_PIN PD2 //(INT2 - Arduino Pin 19) Z80 Pin21
#define WR_PIN PD3 //(INT3 - Arduino Pin 18) Z80 Pin 22
#define RD ((PIND & (1 << RD_PIN)) == 0)
#define WR ((PIND & (1 << WR_PIN)) == 0)
#define PORT_MASK_D ~((1 << RD_PIN) + ( 1 << WR_PIN));
//Port K
#define MREQ_PIN PK1 //(PCINT17 - Arduino Pin A9) Z80 Pin 19
#define IORQ_PIN PK2 //(PCINT18 - Arduino Pin A10) Z80 Pin 20
//Z80 In
//PortB
#define CLK_PIN PB4 //(OC2A) Z80 Pin 6
//Port G
#define INT_PIN PG0 //Z80 Pin 16, Arduino Pin 41
#define RST_PIN PG1 //Z80 PIN 26, Arduino Pin 40
#define WAIT_PIN PG2 //Z80 Pin 24, Arduino Pin 39
#define RESET(b) b == 0 ? PORTG |= (1 << RST_PIN) : PORTG &= ~(1 << RST_PIN);
#define PORT_MASK_G (1 << INT_PIN) + (1 << RST_PIN) + (1 << WAIT_PIN);
// the setup function runs once when you press reset or power the board
void setup() {
Serial.begin(115200);
const long fClk = 1E5;
//Serial.begin(256000);
DDRA = 0x00; //Port A (Addr Low) input
DDRC = 0x00; //Port C (Addr Hi) input
DDRD &= PORT_MASK_D;
DDRK = 0x00; //Port K Input (Z80 sysctl out)
DDRG |= PORT_MASK_G;
PORTG |= PORT_MASK_G;
DDRL = 0xff; //Data Bus
PORTL = 0x00;
//Pin Interrupts
EICRA |= (1 << ISC31) + (0 << ISC30) + (1 << ISC21) + (0 << ISC20);
EIMSK |= (1 << RD_PIN) + (1 << WR_PIN);
//Clock Timer2
DDRB |= (1 << CLK_PIN); //Output
TCCR2A = (0 << COM2A1) + (1 << COM2A0); //Toggle OC2A on Compare Match
TCCR2A |= (1 << WGM21); //CTC Mode
TCCR2B = (0 << CS22) + (0 << CS21) + (1 << CS20); //No Prescaling
OCR2A = 16E6 / (2 * fClk) - 1;
memset(memory, 0, sizeof(memory));
memcpy(memory, mem, sizeof(mem));
RESET(1);
delay(1);
RESET(0);
}
memory.hC/C++ code
#ifndef MEMORY_H
#define MEMORY_H
uint8_t mem[] = {
0x21, 0x0a, 0x00, //ld hl, ??
0x0e, 0x00, //ld c, 0
0x06, 0x0c, //ld b, 12
0xed, 0xb3, //otir
0x76, //halt
'H','e','l','l','o', ' ','W','o','r','l','d','\n'
};
#endif
Arduino Nano R3
× 1
SCHEMATICS
CODE
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define S0 4
#define S1 5
#define S2 6
#define S3 7
#define sensorOut 8
int frequency = 0;
int Red, Green, Blue;
void setup() {
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(sensorOut, INPUT);
Serial.begin(9600);
pixels.begin(); // This initializes the NeoPixel library.
}
void loop() {
// Setting red filtered photodiodes to be read
digitalWrite(S2,LOW);
digitalWrite(S3,LOW);
// Reading the output frequency
frequency = pulseIn(sensorOut, LOW);
//Remaping the value of the frequency to the RGB Model of 0 to 255
frequency = map(frequency, 25,72,255,0);
if (frequency < 0) {
frequency = 0;
}
if (frequency > 255) {
frequency = 255;
}
Red= frequency;
// Printing the value on the serial monitor
Serial.print("R= ");//printing name
Serial.print(frequency);//printing RED color frequency
Serial.print(" ");
delay(100);
× 1
Buzzer, Piezo
× 1
9V battery (generic)
× 1
× 1
9V Battery Clip
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
int times = 150;
int times2 = 75;
int times3 = 133;
void setup() {
// put your setup code here, to run once:
pinMode(9,INPUT);
pinMode(LED_BUILTIN,OUTPUT);
void loop() {
// put your main code here, to run repeatedly:
int sensorValue = digitalRead(9);
if (sensorValue == HIGH){
digitalWrite(LED_BUILTIN,HIGH);
// Get ready for... LA CUCARACHA
tone(8,261,times2); //First part
delay(times);
tone(8,261,times2);
delay(times);
tone(8,261,times2*1.5);
delay(times);
tone(8,349,times2*2);
delay(times*1.5);
tone(8,440,times2);
delay(times);
tone(8,261,times2);
delay(times);
tone(8,261,times2);
delay(times);
tone(8,261,times2);
delay(times);
tone(8,349,times2*2);
delay(times*1.5);
tone(8,440,times2);
delay(times*2);
Ultrasonic Sensor
× 1
× 1
× 1
NeoPixel strip
Summary
After a few easy connections to the UNO, you have a pretty night light
that will activate when you walk in front of the Ultrasonic sensor. I hope
this has helped those of you that want to use an Ultrasonic sensor as a
motion detector. Adjust the distance for activation by altering the "if" loop
cm = _____.
SCHEMATICS
CODE
#include <Adafruit_NeoPixel.h>
#define LEDPIN 12 // connect the Data from the strip to this pin on the Arduino
#define NUMBER_PIEXELS 43// the number of pixels in your LED strip
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMBER_PIEXELS, LEDPIN, NEO_GRB
+ NEO_KHZ800);
const int TrigPin = 2;
const int EchoPin = 3;
float cm;
int delayTime = 200;
int wait = 500;
int i = 0;
void setup()
{
Serial.begin(9600);
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
strip.begin();
}
void loop()
{
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
cm = pulseIn(EchoPin, HIGH) / 58.0; //The echo time is converted into cm
cm = (int(cm * 100.0)) / 100.0; //Keep two decimal places
Serial.print("Distance\t=\t");
Serial.print(cm);
Serial.print("cm");
Serial.println();
if (cm <100){
× 1
9v Battery
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
EasyIOT Server
Here we will use 9v battery for power supply. We will need 7805
voltage regulator IC to get 9V. Then from 7805 IC, feed it to Arduino.
Step 2: Connecting ESP266 and powering it
Connect the RES or RESET pin, When you ground the reset pin, the
Arduino works as a dumb USB to serial connector, which is what we want
to talk to the ESP8266.
Step 5: Connecting Water Leak Sensor
Next we connect Ardino and water sensor. We connect Arduino VCC
and GND to water sensor VCC and GND. Arduino digital Pin 2 is
connected to digital out pin of water sensor.
Now Upload Code.
Step 6: EasyIOT Server
We have To make Our IOT Server which Can be found on link
here: https://iot-playground.com/download
SCHEMATICS
CODE
#include <Esp8266EasyIoT.h>
#include <SoftwareSerial.h>
Esp8266EasyIoT esp;
void setup()
{
serialEsp.begin(9600);
Serial.begin(115200);
Serial.println("EasyIoTEsp init");
esp.begin(NULL, 3, &serialEsp, &Serial);
pinMode(LEAK_PIN, INPUT);
esp.present(CHILD_ID_LEAK, S_LEAK);
}
void loop()
{
esp.process();
5V DC power supply
× 2
DS3231 clock
× 1
× 1
The high voltage box contains the 3-phase input supply (3 phase +
Neutral + Earth). Circuit brakers for motor/transformer and for MCU in
the other box. Transformer (230V to 24-18-12-6-3V). Reversing
contactor and thermal relay. Input and output cables from motor to
Supply Box, from MCU box to Supply Box.
The biggest limitation is the physical size of the controller housing.
First it was a headache how to install everything in a logical manner.
The MCU Box contains the controller aka the Climate Cube, and an
I2C bus expander housing. The controller have all the stuff what counts
here. But first, the most important thing is I wanted to built it as a
structure of modules to be able to expand, enhance later and replace
parts if necessary. See the wiring diagram.
MKR1000 has everything (now) i need. Lots of GPIOs, hardware I2C,
WIFI option, and strong processing ability not to mention it has more
program space than Nanos.
Connection between circuit boards by wires
I use 2-channel opto-isolated relay to switch the 24V AC circuit to
drive the contactors' coil. The relay can be fully separated from the
MCU by giving a second 5V DC power supply. So the coil of the relay
powered from one power supply (PSU) and the optocouplers (relay
inputs' VCC) are from another PSU shared with MCU. The two PSUs
have been built with input and output EMI filter circuits. (I did not find
such filtered PSU where 24V AC input available).
A DS3231 clock is installed also. During plant production there are
many scenarios. For example if there is not enough sunlight for plants
to do their photosynthesis effectively no need to keep hotter air.
The lack of sunlight in the winter (January) not warmth the air and
there is a high chance that temperature inside is lower than what we
wanted so windows stay closed. If this happens plant cannot get fresh
CO2 rich air. So we need to get some fresh air in despite the
temperature inside still lower what needed. Of course we don't want to
do that in the night when outer temperature drops minuses. That is why
MCU needs to know what time it is. Because, for the daylight I need to
set checkpoint/time. Example: when certain conditions appear MCU
opens the windows for 5 seconds interval then keep that for 3 minutes
than close them. Air freshening done.
A display is also necessary to set things and inform us. The 1,3"
OLED was the simplest and best for this project. Uses 3.3V and I2C.
Piece of cake.
Keypad was a hard choice. Tried several types but MPR121 Capacitive
keypad won. The 4x4 membrane also in duty elsewhere but uses 8
input. (to achive only 2 wires using different resistors connected to its'
wires gave hectic readings, so in the end membrane OK but not with 8
outputs). So the cap. keypad... Farming is a dirty thing, much have
rough hands and fingers, not to mention gloves. I have to get used to
that capacitive keypad requires clean hand.
There are dedicated switches and a button in duty. Main switch is a full
ON/OFF switch for AC 230V input. The metal tactile button only
switches the Relay coil ON/OFF (good when debugging needed). And
there is a momentary button also. Pushing it the display activates for
certain seconds and then deactivates (or pushing it again also
deactivates it). OLED displays have limited lifetime that's the reason I
put it there.
MCU cannot capable of running parallel processes at the exact same
time. To show user what is going on inside the Cube I also installed
an RGB 5MM (common cathode) LED. You can program which colour
what means in the program loop. For example in normal 'stand-by'
mode when MCU only reads sensors a blinking green colour indicates
everything is fine "you can go to your work". If freezing hits (not
happened since OLED displays used) blinking stops or it is just light
but not blinks.
The first and most important input is coming from the temperature
sensor. I chose the 1-Wire bus type DS18B20 sensor. Simple and long
range. Range is needed here, we are talking about 200 meters where
can be so much differences between temperatures. I managed to reach
50 meters using CAT5 cable. Sometimes, thanks to the EMI sensor
gives 'error' values but you can filter them easily in the software.
Ready to assembly
In the future under new project names but based on this very first
Climate Cube project i am going to install more sensors (RH%, LUX,
etc.). Optimum relative humidity for sweet pepper is important
and Si7021 sensor can measure it quite well. The amount of radiation is
also very important to know. If it is less than the optimum you have to
keep cooler temperature inside, not to turn the growing process into
vegetative stage etc.
The 'What if...' session
There are many dilemmas and 'what if...' type questions but the main
thing is we all exposed to the changes of weather. All we can do is to
adapt our micro-climate to it. First of all, for optimum adaptation we
need exact data (°C of Air, °C of Soil, RH%, Soil moisture, Watts/m2°
etc.) from our surroundings. Second, we should know what plants exact
need in certain period of production. Only after these information we
can start to think about what type of intervention should we take.
Next levels of Climate Cube
I am about to build a 3G based Wi-Fi network in the area, after that i
can monitor, manage etc. the already installed units. I real IoT based
plant production come alive soon.
SCHEMATICS
CODE
#include <HCMatrixKeypad.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Metro.h>
#include <Wire.h>
#include <Arduino.h>
#include <U8g2lib.h>
#include "RTClib.h"
#define LED 19
/*----------------Keypad-----------------*/
HCMatrixKeypad Keypad(DEBOUNCE, C1, C2, C3, C4, ROWMARKER, R1, R2, R3,
R4);
/*1=14 . . A=11
4=24 . . B=21
7=34
*=44
*/
/*---------------------------------------------------------------------*/
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers
RTC_DS3231 rtc;
void setup()
{
pinMode(LED,OUTPUT);
digitalWrite(LED,ledstate);
rtc.begin();
sensors.begin(); // Elindul a homero
sensors.setResolution(10);
pinMode(relayPin0, OUTPUT);
digitalWrite(relayPin0, HIGH);
pinMode(relayPin1, OUTPUT);
digitalWrite(relayPin1, HIGH);
// initialize the button pin as a input:
pinMode(inPin, INPUT);
/*u8g2.setCursor(16,2);
u8g2.print("W/m2");
u8g2.setCursor(0,1);
u8g2.print("Par:");
u8g2.setCursor(8,1);
u8g2.print("%");
u8g2.setCursor(10,1);
u8g2.print("Hom:");
u8g2.setCursor(0,3);
u8g2.print("Aj.Hom:");
/*t = rtc.getTime();
if(t.hour<10) {
u8g2.setCursor(5,3);
u8g2.print("0");
u8g2.setCursor(6,3);
u8g2.print(t.hour);
}
else {
u8g2.setCursor(5,3);
u8g2.print(t.hour);
}
if(t.min<10) {
u8g2.setCursor(8,3);
u8g2.print("0");
u8g2.setCursor(9,3);
u8g2.print(t.min);
}
else {
u8g2.setCursor(8,3);
u8g2.print(t.min);
}*/
sensors.requestTemperatures();
delay(500);
metro0.reset();
metro1.reset();
ledMetro.reset();
metro3.reset();
metro4.reset();
metro5.reset();
//WiFi.begin(ssid, pass);
//ThingSpeak.begin(client);
//delay(2000);
}
void loop()
{
//
digitalWrite(LED,ledstate);
}
float tempRaw = sensors.getTempCByIndex(0);
float tempFloat = tempRaw*100;
int tempInt = tempFloat;
//Serial.println(sensors.getTempCByIndex(0));
//Serial.println(tempInt);
//Serial.println(tempCaverage);
u8g2.setCursor(0,10);
u8g2.print("Bh:");
u8g2.setCursor(0,24);
u8g2.print("D:");
u8g2.setCursor(0,38);
u8g2.print("Ah:");
u8g2.setCursor(0,52);
u8g2.print("Ido:");
Keypad.Scan();
if (Keypad.Read() == 14) {
kivantHomerseklet+=100;
if (kivantHomerseklet == 2600){
kivantHomerseklet = 1600;
}
}
if (Keypad.Read() == 24) {
kivantHomerseklet-=100;
if (kivantHomerseklet == 1500){
kivantHomerseklet = 2500;
}
}
if (Keypad.Read() == 13) {
homDiff+=10;
if (homDiff > 205){
homDiff = 10;
}
}
if (Keypad.Read() == 23) {
homDiff-=10;
if (homDiff < 5){
homDiff = 200;
}
}
if (rtcMetro.check()== 1) {
Serial.print(now.year());
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();
u8g2.setCursor(30,52);
u8g2.print(now.hour());
u8g2.setCursor(45,52);
u8g2.print(":");
u8g2.setCursor(54,52);
u8g2.print(now.minute());
int Bh = kivantHomerseklet/100;
u8g2.setCursor(23,10);
u8g2.print(Bh);
u8g2.setCursor(23,38);
u8g2.print(tempRaw,1);
u8g2.setCursor(62,38);
u8g2.print("C");
/*if(humidity<=0) {
u8g2.setCursor(4,1);
u8g2.print(" 0 ");
}
if(humidity>0 && humidity<100) {
u8g2.setCursor(4,1);
u8g2.print(humidity,0);
u8g2.setCursor(6,1);
u8g2.print(" ");
}
if(humidity>=100 && humidity<=115) {
u8g2.setCursor(4,1);
u8g2.print(humidity,0);
u8g2.setCursor(7,1);
u8g2.print(" ");
}
if(humidity>115) {
u8g2.setCursor(5,1);
u8g2.print("115");
u8g2.setCursor(4,1);
u8g2.print(">");
}
u8g2.setCursor(14,1);
u8g2.print(cTemp, 1);
u8g2.setCursor(19,1);
u8g2.print("C");
if(lux<10) {
u8g2.setCursor(12,2);
u8g2.print(lux);
u8g2.setCursor(13,2);
u8g2.print(" ");
u8g2.setCursor(14,2);
u8g2.print(" ");
if(lux>1000) {
u8g2.setCursor(11,2);
u8g2.print(lux);
if(lux<100) {
u8g2.setCursor(7,3);
u8g2.print("18-20 ");
u8g2.setCursor(13,3);
u8g2.print("C");
}
//u8g2.setCursor(0,2);
//u8g2.print("Besugarzas:");
}
reading = digitalRead(inPin);
// if the input just went from LOW and HIGH and we've waited long enough
// to ignore any noise on the circuit, toggle the output pin and remember
// the time
if (reading == HIGH && previous == LOW) {
if (state == HIGH)
state = LOW;
else
state = HIGH;
metro5.reset();
}
if (state == HIGH) {
u8g2.sendBuffer();
Serial.println("OLED ON");
metro5.interval(20000);
}
if (state == LOW) {
// if the current state is LOW then the button
// wend from on to off:
u8g2.clearDisplay();
}
previous = reading;
if ((kivantHomerseklet-homDiff) == tempCaverage ) {
digitalWrite(relayPin0, HIGH);
digitalWrite(relayPin1, HIGH);
}
if ((kivantHomerseklet+homDiff) == tempCaverage) {
digitalWrite(relayPin0, HIGH);
digitalWrite(relayPin1, HIGH);
}
if (((kivantHomerseklet-homDiff) < tempCaverage && tempCaverage <
(kivantHomerseklet+homDiff)) && relayPin0==LOW) {
digitalWrite(relayPin0, HIGH);
}
if (((kivantHomerseklet-homDiff) < tempCaverage && tempCaverage <
(kivantHomerseklet+homDiff)) && relayPin1==LOW) {
digitalWrite(relayPin1, HIGH);
}
}
53) Arduino CNC Flatbed Pen Plotter
× 1
SCHEMATICS
CODE
#include <AccelStepper.h>
#include <MultiStepper.h>
MultiStepper motors;
short motors_dir = 1;
int motors_avgSpeed = MOTORS_MAXSPEED;// Average speed
void setup() {
Serial.begin(115200);// Maximum baud rate for Arduino Uno
Serial.println("Запуск");
input.reserve(128);
motorX.setMaxSpeed(MOTORS_MAXSPEED);
motorY.setMaxSpeed(MOTORS_MAXSPEED);
motorZ.setMaxSpeed(MOTORS_MAXSPEED);
motorX.setAcceleration(MOTORS_ACCELERATION);
motorY.setAcceleration(MOTORS_ACCELERATION);
motorZ.setAcceleration(MOTORS_ACCELERATION);
motors.addStepper(motorX);
motors.addStepper(motorY);
motors.addStepper(motorZ);
}
void loop() {
while (Serial.available()) {
input = Serial.readStringUntil('\n');
input.trim();
int input_sp = input.indexOf(' ');// Checking for space character in input string
String input_command = input;
String input_param;
if (input_sp > 0) {
input_command = input.substring(0, input_sp);
input_param = input.substring(input_sp + 1);
input_param.trim();
}
doCommand(input_command, input_param);
input = "";
}
measureSteps();
motors.run();
}
void _stop() {
motors.moveTo(motorX.currentPosition());
motorX.setSpeed(0);
motorY.setSpeed(0);
motorZ.setSpeed(0);
motorX.stop();
motorY.stop();
motorZ.stop();
Serial.println("Stopped");
}
void _dir() {
motors_dir = -motors_dir;
if (motors_dir > 0) Serial.println("CW");
else Serial.println("CCW");
}
void measureSteps() {
if (motorX.speed() != 0) {
Serial.print("Position: ");
Serial.print(motorX.currentPosition());
Serial.print(" | Speed: ");
Serial.print(motorX.speed());
Serial.println(" steps/s");
}
}
Arduino Nano R3
× 1
Recycled cables
× 1
#define echo 8
#define trig 7
long duration,distance;
void setup() {
Serial.begin(9600);
pinMode(echo,INPUT);
pinMode(trig,OUTPUT);
pinMode(5,OUTPUT);
}
void loop() {
digitalWrite(trig,LOW);
delayMicroseconds(2);
digitalWrite(trig,HIGH);
delayMicroseconds(10);
digitalWrite(trig,LOW);
duration=pulseIn(echo,HIGH);
distance=(duration/(2*29));
if(distance>=500 || distance<=0){
Serial.println("____");
}
else{
Serial.print(distance);
Serial.println("cm.");
digitalWrite(5,LOW);
}
if(distance<=45 && distance>=1){// distance in which the bracelet vibrates, you can edit
according to your need
digitalWrite(5,HIGH);
Serial.println("Alarm!!!");
}
delay(400);
}
× 1
Android device
× 1
SCHEMATICS
CODE
#include <avr/delay.h>
/* servo libs */
#include "_Servo.h"
/* WiFi libs */
#include "CC3000.h"
#include "CC3000_Client.h"
#include "common.h"
Servo servo_x;
Servo servo_y;
void setup()
{
/* add setup code here */
ConnectionInfo connection_info;
else {
//FreeRam();
#ifdef CC3000_DEBUG
DEBUGPRINTLN(PSTR("Initialize CC3000 OK"));
#endif
}
else
{
#ifdef CC3000_DEBUG
DEBUGPRINT(PSTR("IP Address: "));
printIPAddr(connection_info.ip_address);
#endif
}
servo_x.attach(SERVO_PIN_X);
servo_y.attach(SERVO_PIN_Y);
// center servos
servo_x.write(SERVO_CENTER_X);
servo_y.write(SERVO_CENTER_Y);
_delay_ms(200);
}
void loop()
{
}
56) Arduino Event Monitor for Independent Senior Citizens
Arduino MKR1000
× 1
ADXL345
× 1
DS18B20
× 1
Photo resistor
× 1
3 mm LED: Red
× 1
3 mm LED: Green
× 1
Buzzer
× 1
× 3
Resistor 1k ohm
× 2
× 1
Breadboard (generic)
× 1
× 1
× 1
SCHEMATICS
CODE
MKR1000 Azure Sensor Node Sketch
MKR1000 pinouts:
----------------
LDR analog A0 2
Battery voltage A1 3
LED red D0 9
LED green D1 10
DS18B20 signal D2 11
ADXL345 INT1 ?
Buzzer D3 12
Switch D4 13
MKR1000_LED D6 15 // internal LED
ADXL345 SDA D11 21
ADXL345 SCL D12 22
GND 25
Vcc 26
Vin 27
*/
#include <SPI.h>
#include <WiFi101.h>
#include <Wire.h>
#include <ADXL345.h>
#include <OneWire.h>
#include <avr/dtostrf.h>
#include <ArduinoJson.h>
// Sensor stuff
#define ldrPin A0 // light sensor
#define batPin A1 // battery voltage
#define LED_red 0 // red status led
#define LED_green 1 // green status led
#define DS18S20_Pin 2 // DS18S20 Signal pin
#define Buzzer 3 // sound output
#define swPin 4 // switch input
#define MKR1000_LED 6 // internal LED
float prevtemp = 0;
float prevacc = 0;
float prevlight = 0;
float prevbattery = 0;
int prevswitch = 0;
// setup I/Os
pinMode(LED_red, OUTPUT); // status LED red
digitalWrite(LED_red, HIGH); // high is off
pinMode(LED_green, OUTPUT); // status LED green
digitalWrite(LED_green, HIGH); // high is off
pinMode(Buzzer, OUTPUT); // sound out
digitalWrite(Buzzer, LOW); // low is off
pinMode(MKR1000_LED, OUTPUT); // internal LED
pinMode(swPin, INPUT); // external switch
void loop()
{
// Check for messages from Azure IoT Hub and process them
azureHttpMessage();
time_new = millis();
if ((time_new - time_last) > 20000) {
LED_blink(LED_green, 50, 2);
time_last = millis();
azureIoTReceiveMessage(); // send Azure request for message
}
}
if (!ds.search(addr)) {
//no more sensors on chain, reset search
ds.reset_search();
return -1000;
}
if (OneWire::crc8(addr, 7) != addr[7]) {
return -1000;
}
if (addr[0] == 0x10) {
//Sensor is a DS18S20
}
else if (addr[0] == 0x28) {
//Sensor is a DS18BS20
}
else
{
return -1000;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion, with parasite power on at the end
ds.reset_search();
return TemperatureSum;
int getAccelerometer() {
char action[50]; // strcat needs a character array
memset(action, '\0', sizeof(action));
int interrupt = 0;
int x, y, z;
adxl.readAccel(&x, &y, &z); //read the accelerometer values and store
them in variables x,y,z
//read interrupts source and look for triggerd actions
byte interrupts = adxl.getInterruptSource();
// freefall
if (adxl.triggered(interrupts, ADXL345_FREE_FALL)) {
strcat(action, "freefall ");
interrupt = 1;
//add code here to do when freefall is sensed
}
//inactivity
if (adxl.triggered(interrupts, ADXL345_INACTIVITY)) {
strcat(action, "inactivity ");
interrupt = 0;
//add code here to do when inactivity is sensed
}
//activity
if (adxl.triggered(interrupts, ADXL345_ACTIVITY)) {
strcat(action, "activity ");
interrupt = 1;
//add code here to do when activity is sensed
}
//double tap
if (adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)) {
strcat(action, "double tap ");
interrupt = 1;
//add code here to do when a 2X tap is sensed
}
//tap
if (adxl.triggered(interrupts, ADXL345_SINGLE_TAP)) {
strcat(action, "tap ");
interrupt = 1;
//add code here to do when a tap is sensed
}
// JSON buffer created
// Create the root of the object tree.
StaticJsonBuffer<256> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["DeviceID"] = DeviceID;
root["Accelerometer"] = action;
// Print to buffer
root.printTo(buffer, sizeof(buffer));
return interrupt;
}
float getLight() {
float lightlevel = analogRead(ldrPin);
return lightlevel;
}
float getBatteryV() {
float batteryV = analogRead(batPin);
return batteryV;
}
int getSwitch() {
int swStatus = digitalRead(swPin);
char truefalse[5]; // strcat needs a character array
memset(truefalse, '\0', sizeof(truefalse));
if (swStatus == 0) {
strcat(truefalse, "OFF");
}
else
{
strcat(truefalse, "ON");
}
return swStatus;
}
int wifiConnect() {
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
// wait 1 seconds for connection:
delay(1000);
}
return 1;
}
/************* this method checks for messages from the Aure IoT Hub
and processes them ***************/
void azureHttpMessage() {
String response = "";
char c;
///read response if WiFi Client is available
while (client.available()) {
c = client.read();
response.concat(c);
}
if (!response.equals(""))
{
//if there are no messages in the IoT Hub Device queue, Azure will return
204 status code.
if (response.startsWith("HTTP/1.1 204"))
{
//turn off onboard LED
digitalWrite(MKR1000_LED, LOW);
}
else
{
//turn on onboard LED
digitalWrite(MKR1000_LED, HIGH);
azureIoTCompleteMessage(eTag);
if (command == "beepon") {
//turn on buzzer
digitalWrite(Buzzer, HIGH);
}
if (command == "beepoff") {
//turn off buzzer
digitalWrite(Buzzer, LOW);
}
}
}
}
void azureIoTReceiveMessage()
{
httpRequest("GET", feeduri, "", "");
}
/************* Tells Azure IoT Hub that the message with the
msgLockId is handled and it can be removed from the queue
***************/
if (verb.equals("POST"))
{
client.print("Content-Type: ");
client.println(contentType);
client.print("Content-Length: ");
client.println(content.length());
client.println();
client.println(content);
}
else
{
client.println();
}
}
}
if (idx >= 0)
{
int skip = 0;
if (headerName.endsWith(":"))
skip = headerName.length() + 1;
else
skip = headerName.length() + 2;
return headerValue;
}
/********** Azure IoT sets ETag string enclosed in double quotes, not in
sync with its other endpoints - need to remove the double quotes
************/
if (value.startsWith("\""))
retVal = value.substring(1);
if (value.endsWith("\""))
retVal = retVal.substring(0, retVal.length() - 1);
return retVal;
}
Receiving events...
26 Mar 2016 10:44:14 PM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Temperature":24.44}]
27 Mar 2016 8:40:50 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Temperature":85.00}]
27 Mar 2016 8:40:50 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Temperature":18.62}]
27 Mar 2016 8:43:49 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Temperature":19.69}]
27 Mar 2016 8:49:26 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Temperature":20.75}]
27 Mar 2016 8:51:44 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":451.00}]
27 Mar 2016 9:06:44 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Temperature":21.81}]
27 Mar 2016 9:07:31 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":364.00}]
27 Mar 2016 9:11:16 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":376.00}]
27 Mar 2016 9:11:59 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":477.00}]
27 Mar 2016 9:13:11 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":335.00}]
27 Mar 2016 9:26:48 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":420.00}]
27 Mar 2016 9:27:24 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":521.00}]
27 Mar 2016 9:39:31 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Temperature":20.75}]
27 Mar 2016 9:51:58 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Lightlevel":398.00}]
27 Mar 2016 9:52:25 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Switch":"OFF"}]
27 Mar 2016 9:52:34 AM> Device: [RethinkAzureSuite01], Data:
[{"DeviceID":"RethinkAzureSuite01","Switch":"ON"}]
Commands sent from Device Explorer
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
Tape, Green
APPS AND ONLINE SERVICES
Arduino IDE
This is a replacement part for the washing machine I have that has a broken wash timer. The
original timer was a mechanical timer/direction switch, which can control the washing tub's
motor in following manner:
Take x minutes of wash time input from user
Rotate washing tub's motor clockwise for few seconds
Stop motor for few seconds
Rotate wash tub's motor anti-clockwise for few seconds
Stop motor for few seconds
Keep doing last 4 steps until wash timer expires
Hardware
Arduino Pro Mini: Runs code and controls everything
1306 OLED: Show user instruction and timer countdown
Red/Black Push Button: Set timer and start timer
5V Relay Modules: Supply AC power to motor and control direction
5V Adapter: Power the electronic timer
1306 OLED is directly soldered on the pro mini like this:
Arduino Pro Mini + 1306 OLED
2 relays module, 2 push buttons, Arduino Pro Mini + 1306 OLED is connected on a
protoboard like this -
Hardware
Soldering
Programming
Step 1: Get a HC-05 Bluetooth-Serial module and change it's baud rate to 57600 according
to this tutorial or this step. To perform this step another Arduino Uno or a USB to Serial
module will be required.
Use following AT commands
AT
AT+UART = 57600,0,0
AT+RESET
Step 2: After the baud rate is changed to 57600, connect the HC-05 to
Arduino pro mini according to following wiring diagram
Wireless Programming of Arduino Pro mini with HC-05
Step 3: Select board from Arduino IDE, paste the code and click upload.
Wiring Explained
Broken Mechanical Timer/Motor Direction Control Switch
When WHITE WIRE is switched to the RED WIRE motor rotates in clockwise and when
WHITE WIRE is switched to the BLUE WIRE motor rotates in anticlockwise direction.
This electronic timer made with Arduino pro mini will keep track of wash time, rotate the
wash tub's motor in one direction for 5 seconds by connecting WHITE and RED wires
through one relay contact. Then it will stop the motor and wait for 5 seconds. After that it
will rotate the was tub's motor in the other direction for 5 seconds by connecting the
WHITE and BLUE wires through the other relay contact. Then it will stop and wait for
another 5 seconds. All these timing sequence can be modified from the code if necessary.
Following diagram shows how just flipping the AC incoming mains to one leg or the other
leg of the motor's capacitor, direction of the AC motor can be altered.
AC Induction Motor Direction Control
SCHEMATICS
CODE
#include "U8glib.h"
//SSD1306 oled waveshare(clk,din,cs,d/c,res);
U8GLIB_SSD1306_128X64 u8g(A4,A5,12,11,10);
void setup()
{
u8g.setRot180();
analogReference(INTERNAL);
pinMode(2,INPUT_PULLUP);
pinMode(3,INPUT_PULLUP);
attachInterrupt(0, ISR_SW_RED,FALLING);
attachInterrupt(1, ISR_SW_BLACK,FALLING);
pinMode(5,OUTPUT);
digitalWrite(5,LOW);
pinMode(4,OUTPUT);
digitalWrite(4,LOW);
}
void loop(void)
{
while(!rbc)
{
// show timer set menu
u8g.firstPage();
do {
draw_menu();
} while( u8g.nextPage() );
// start timer
if(rbc>0)
{
sec =59;
mi = bbc-1;
while(mi>=0)
{
// show countdown timer message
unsigned long temp = millis()+1000;
while(temp>=millis())
{
u8g.firstPage();
do {
draw_timer();
} while( u8g.nextPage() );
}
sec=sec-1;
if(sec%5==0)
{
control_motor(); // call every 5 sec
}
if (sec <= 0)
{
sec = 59;
mi = mi - 1;
}
}
rbc = 0; bbc = 0;
mi = 0 ; sec = 0;
digitalWrite(5,LOW);digitalWrite(6,LOW);
}
void draw_menu(void)
{
u8g.setFont(u8g_font_timB24);
if (bbc<10)
{
u8g.drawStr( 22,30,"0");
u8g.setPrintPos(38,30);u8g.print(bbc);
}
else
{
u8g.setPrintPos(22,30);u8g.print(bbc);
}
u8g.drawStr( 54,30,":00");
u8g.setFont(u8g_font_8x13);
u8g.drawStr( 0,62," 'WASHING TIMER'");
u8g.setFont(u8g_font_5x8);
u8g.drawStr( 0,47,"Red:START Black:SET TIME");
}
void draw_message(void)
{
u8g.setFont(u8g_font_8x13);
u8g.drawStr( 0,10," SET WASH TIMER");
u8g.drawStr( 0,23,"FIRST BY PUSHING");
u8g.drawStr( 0,36,"THE BLACK BUTTON");
// u8g.setFont(u8g_font_8x13);
u8g.drawStr( 0,62," 'WASHING TIMER'");
u8g.setFont(u8g_font_5x8);
u8g.drawStr( 0,47,"Red:START Black:SET TIME");
void draw_timer(void)
{
u8g.setFont(u8g_font_timB24);
if (mi<10)
{
u8g.drawStr( 22,30,"0");
u8g.setPrintPos(38,30);u8g.print(mi);
}
else
{
u8g.setPrintPos(22,30);u8g.print(mi);
}
u8g.drawStr( 54,30,":");
if (sec<10)
{
u8g.drawStr( 70,30,"0");
u8g.setPrintPos(86,30);u8g.print(sec);
}
else
{
u8g.setPrintPos(70,30);u8g.print(sec);
}
if(motor_rotation==0)
{
u8g.setFont(u8g_font_5x8);
u8g.drawStr( 0,47," WASHING MOTOR CW Spin");
digitalWrite(5,HIGH);
}
if(motor_rotation==1)
{
u8g.setFont(u8g_font_5x8);
u8g.drawStr( 0,47," WASHING MOTOR STOPPED ");
digitalWrite(5,LOW);digitalWrite(4,LOW);
}
if(motor_rotation==2)
{
u8g.setFont(u8g_font_5x8);
u8g.drawStr( 0,47," WASHING MOTOR CCW Spin");
digitalWrite(4,HIGH);
}
if(motor_rotation==3)
{
u8g.setFont(u8g_font_5x8);
u8g.drawStr( 0,47," WASHING MOTOR STOPPED ");
digitalWrite(5,LOW);digitalWrite(4,LOW);
u8g.setFont(u8g_font_8x13);
u8g.drawStr( 0,62," 'WASHING TIMER'");
void ISR_SW_RED()
{
sei();
rbc++;
cli();
}
void ISR_SW_BLACK()
{
sei();
bbc++;
cli();
}
void control_motor()
{
motor_rotation++;
if(motor_rotation>3)
{
motor_rotation = 0;
}
}
Arduino Nano R3
× 1
× 1
× 4
× 1
× 1
Veroboard
× 1
You when something annoys you so much you just have to fix it
especially if every one else nags you. Our television remote falls in this
category, its a "Dick Smith" brand unit and has a dodgy intermittent
remote. I've used universal remotes before and even after hours of
programming them they are not so flash. So what to do? Our Panasonic
DVR we use has a more than adequate universal section built in but in
spite of talking to 100s of other devices our TV is not one of them. If
only it spoke the lingo!
Arduino IR library and Nano on the job
Did you know with a couple of parts you can receive, analyse and send
IR codes with even the smallest Arduino? So with not much more than
the example sketch you can work out what codes in what protocol gets
sent from your remote for each button. With a couple more lines of
code you can send another code that you would like substituted for the
the first code.
So in no time at all you have built yourself a transcoder. Receives
codes of one remote and re-transmits them as if from another. "Piece of
Pi" or maybe Arduino? I even put in the start of an overlay function so
I can use all of the remote buttons for the TV if the original device is
off, I used a RGB LED indicator to show when your in that mode to
avoid user confusion.
Anyhow, all that is left now is to give the remote to family members to
test and suggest while you watch for bugs.
The circuit
Very simple, due to the IR receiver doing a lot of the heavy lifting. It
has the automatic gain control and many other items needed to
successfully demodulate the 38 kHz signal that is passed to the
Arduino. There is no current limmit resistor on the two IR LEDs. I was
expecting scorch marks on the couch while testing but it seems to work
fine at 5V with the LEDs I bought. Trying this was a response to what
seemed a pathetic range at 20 ma, "More power Igor !"
Beta testing, note the recycled mobile phone charger as a power source
You can see the proof of concept test unit with the breadboard to the
left of our TV. The Arduino Nano is mounted on a prototype shield to
the right. These prototype shields are neat as no toolkit should be
without one!
Not all beer and Skittles
There are some subtle things at play in the project and its all in the
timing of the reception and transmission of the new code. but as always
"Professor Google" has most of the answers that you seek.
Worthwhile?
Definitely, I only need one remote which I didn't have to buy. I can
change functionality (Include some macros) if I wish. Most importantly
I learned a lot about IR remote controls.
But wait there's more... ESP to the rescue!
All the parts for the final build sat on my bench for 12 months,
assigned to the back burner after some success with a soldering iron
and the actual TV remote. In the mean time I learned about the
ESP8266. So when it can to put the unit in a box I thought why not
make it run on a NodeMCU board. So with that thought in mind the
final chapter and build was started.
Other side showing ESP8266 and all the LED's and IR receiver.
So the software was rearranged and refactored to suit the new and
better IR library for the ESP8266. The tri-color LED was used as
follows. Red flash for IR transmit, Blue flash for WiFi Receive and
Green flash for IR receive. The Blue LED also flashes fast during the
boot phase as it attempts to login to the WiFi. The built in LED is used
as a confidence meter / heart beat.
The unit has both soft AP and WiFi client, This makes configuration
easier as there is always a configuration port available.
The remote control page uses some in-line CSS in the web response to
set the style of the form buttons which form the basis of the remote
control page. The page works nicely on mobile phones due to the
"viewport" command which helps the phone get a better "perspective"
on how it should display the content. These represent a departure from
my usual web M.O but I am trying to "up skill" a bit.
But wait... how could I build a remote control that has WiFi with
making it programmable via the WiFi and IR port. So a new web page
and interface was designed so I could capture an IR code and assign it
to a button in the control matrix. In fact you can reprogram it all via
this interface. There is a factory reset to return it to the original state if
you completely loose your way.
Unit positioned just below the IR receiver on the TV
Final assembled and working unit
Actually I found the virtual remote on a mobile web page much handier
than just a gimmick. Every member of the family has some sort of
device and can now operate the TV even if the remote has scurried
away into the deepest recesses of the sofa.
#define DECODE_NEC 1
#define TVONOFF 0xFB38C7
#define TVAV 0xFBE817 // signal source
#define TVVOLUP 0xFBD22D
#define TVVOLDN 0xFBF20D
#define TVCHUP 0xFB906F
#define TVCHDN 0xFBA05F
#define TV1PAD 0xFB2AD5
#define TV2PAD 0xFB6897
#define TV3PAD 0xFBA857
#define TV4PAD 0xFB0AF5
#define TV5PAD 0xFB48B7
#define TV6PAD 0xFB8877
#define TV7PAD 0xFB32CD
#define TV8PAD 0xFB708F
#define TV9PAD 0xFBB04F
#define TV0PAD 0xFB30CF
#define TVLNAV 0xFBE21D
#define TVRNAV 0xFBE01F
#define TVUNAV 0xFB58A7
#define TVDNAV 0xFB12ED
#define TVOKNAV 0xFB609F
#define TVAPMENU 0xFB18E7
#define TVEXITNAV 0xFB50AF
#define TVMUTE 0xFB10EF
#define TVPLAY 0xFB5AA5
#define TVPAUSE 0xFB4AB5
#define TVSTOP 0xFBBA45
#define TVWTF 0xFB3AC5
#define TVREW 0xFBAA55
#define TVFF 0xFB7A85
#define TVPREV 0xFB8A75
#define TVNEXT 0xFB9A65
#define TVTEXT 0xFB9A65
#define TVSUBTTL 0xFBFA05
#define TVFREEZE 0xFB9867
#define TVINFO 0xFB1AE5
#define TVRED 0xFB6A95
#define TVGREEN 0xFBEA15
#define TVYELLOW 0xFBF807
#define TVBLUE 0xFBDA25
IRsend irsend;
long PrevCode;
int iMode = 0;
bool bTransmit=false;
bool bRepeat=false;
//------------------------------------------------------------------------------
// Tell IRremote which Arduino pin is connected to the IR Receiver
(TSOP4838)
//
int recvPin = 11;
IRrecv irrecv(recvPin);
//+============================================================
// Configure the Arduino
//
void setup ( )
{
Serial.begin(115200); // Status message will be sent to PC at 9600 baud
Serial.println("Start");
pinMode(3,OUTPUT); // IR LED
pinMode(4,OUTPUT); // RGB LED FOR MODE INDICATOR
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
irrecv.enableIRIn(); // Start the receiver
irrecv.blink13(1);
}
//+============================================================
// Display IR code
//
void ircode (decode_results *results)
{
// Panasonic has an Address
if (results->decode_type == PANASONIC) {
Serial.print(results->address, HEX);
Serial.print(":");
}
// Print Code
Serial.print(results->value, HEX);
}
//+============================================================
// Display encoding type
//
void encoding (decode_results *results)
{
switch (results->decode_type) {
default:
case UNKNOWN: Serial.print("UNKNOWN"); break ;
case NEC: Serial.print("NEC"); break ;
case SONY: Serial.print("SONY"); break ;
case RC5: Serial.print("RC5"); break ;
case RC6: Serial.print("RC6"); break ;
case DISH: Serial.print("DISH"); break ;
case SHARP: Serial.print("SHARP"); break ;
case JVC: Serial.print("JVC"); break ;
case SANYO: Serial.print("SANYO"); break ;
case MITSUBISHI: Serial.print("MITSUBISHI"); break ;
case SAMSUNG: Serial.print("SAMSUNG"); break ;
case LG: Serial.print("LG"); break ;
case WHYNTER: Serial.print("WHYNTER"); break ;
case AIWA_RC_T501: Serial.print("AIWA_RC_T501"); break ;
case PANASONIC: Serial.print("PANASONIC"); break ;
case DENON: Serial.print("Denon"); break ;
}
}
//+============================================================
// Dump out the decode_results structure.
//
void dumpInfo (decode_results *results)
{
// Check if the buffer overflowed
if (results->overflow) {
Serial.println("IR code too long. Edit IRremoteInt.h and increase
RAWLEN");
return;
}
//+============================================================
// Dump out the decode_results structure.
//
void dumpRaw (decode_results *results)
{
// Print Raw data
Serial.print("Timing[");
Serial.print(results->rawlen-1, DEC);
Serial.println("]: ");
//+============================================================
// Dump out the decode_results structure.
//
void dumpCode (decode_results *results)
{
// Start declaration
Serial.print("unsigned int "); // variable type
Serial.print("rawData["); // array name
Serial.print(results->rawlen - 1, DEC); // array size
Serial.print("] = {"); // Start declaration
// Dump data
for (int i = 1; i < results->rawlen; i++) {
Serial.print(results->rawbuf[i] * USECPERTICK, DEC);
if ( i < results->rawlen-1 ) Serial.print(","); // ',' not needed on last one
if (!(i & 1)) Serial.print(" ");
}
// End declaration
Serial.print("};"); //
// Comment
Serial.print(" // ");
encoding(results);
Serial.print(" ");
ircode(results);
// Newline
Serial.println("");
//+============================================================
// The repeating section of the code
//
void loop ( )
{
decode_results results; // Somewhere to store the results
// Serial.println(iMode);
Serial.print("R ");
Serial.println(results.value, HEX);
bTransmit = false ;
switch(results.value){
case 0x18E710EF: // TV on off
PrevCode = TVONOFF ;
bTransmit = true ;
bRepeat = false ;
iMode = 0 ;
break;
case 0x18E750AF: // AV
PrevCode = TVAV ;
bTransmit = true ;
bRepeat = false ;
iMode = 0 ;
break;
case 0x18E740BF: // VOL +
PrevCode = TVVOLUP ;
bTransmit = true ;
bRepeat = true ;
iMode = 0 ;
break;
case 0x18E7C03F: // VOL -
PrevCode = TVVOLDN ;
bTransmit = true ;
bRepeat = true ;
iMode = 0 ;
break;
case 0x18E700FF: // CH +
PrevCode = TVCHUP ;
bTransmit = true ;
bRepeat = false ;
iMode = 0 ;
break;
case 0x18E7807F: // CH-
PrevCode = TVCHDN ;
bTransmit = true ;
bRepeat = false ;
iMode = 0 ;
break;
case 0xFFFFFFFF: // repeat code
if ( bRepeat == true ){
bTransmit = true ;
}
break;
}
59) Arduino Weather Wand
TMP36 sensor
× 1
wx_wand_1.txtC/C++
/*
The Weather Wand!
A small wand that lights up at the tip based on if it is hot or cold.
Hot and cold are determined by the standard deviation from the average of
the 50 most recent temperature samples.
Hardware: An Arduino pro mini with a TMP36 temp sensor and an
common cathode RGB LED.
*/
//________________Setup________________________
//delay var
int del = 100;
//statistics
int max_samples = 50;
int temperature_samples[50];
int n_temperature_samples = 0;
int i_temperature_samples = 0;
float stddev_temperature = 5;
float avg_temperature = 50;
float tempF_recent = 0;
//________________Run Time________________________
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
void loop()
{
getTemp();
temperature_samples[i_temperature_samples] = tempF;
i_temperature_samples++;
if (n_temperature_samples < max_samples) {
n_temperature_samples++;
}
if (i_temperature_samples >= max_samples) {
i_temperature_samples = 0;
}
computeStdDev();
tempColor();
delay(del);
}
void getTemp()
{
//getting the voltage reading from the temperature sensor
int reading = analogRead(sensorPin);
// converting that reading to voltage, for 3.3v arduino use 3.3, for 5v use 5
float voltage = reading * 3.3;
voltage /= 1024.0;
// Convert to Fahrenheit
tempF = (tempC * 9.0 / 5.0) + 32.0;
Serial.println("--------------");
}
void computeStdDev() {
int i;
avg_temperature = 0;
for (i = 0; i < n_temperature_samples; i++){
avg_temperature = avg_temperature + temperature_samples[i];
}
avg_temperature = avg_temperature / n_temperature_samples;
stddev_temperature = 0;
for (i = 0; i < n_temperature_samples; i++){
stddev_temperature = stddev_temperature + (temperature_samples[i] -
avg_temperature) * (temperature_samples[i] - avg_temperature);
}
tempF_recent = 0;
for (i = start_i; i < i_temperature_samples; i++) {
tempF_recent = tempF_recent + temperature_samples[i];
}
tempF_recent /= (i_temperature_samples - start_i);
} else {
tempF_recent = tempF;
}
//Set the RGB color based on standard deviation distance from average
temp
void tempColor()
{
float diff = (tempF_recent - avg_temperature) / stddev_temperature;
file_15302.txtC/C++
/*
The Weather Wand!
A small wand that lights Neo Pixels (addressable RGB LEDs) at the tip in
response to temperature .
Hot and cold are determined by the standard deviation from the average of
the 50 most recent temperature samples.
Hardware: An Arduino pro mini with a TMP36 temp sensor and
addressable RGB LEDs.
NeoPixel library from Adafruit
*/
//________________Setup________________________
// NeoPixel setup
#include <Adafruit_NeoPixel.h>
#define PIN 6
//delay var
int del = 80;
//statistics
int max_samples = 50;
int temperature_samples[50];
int n_temperature_samples = 0;
int i_temperature_samples = 0;
float stddev_temperature = 5;
float avg_temperature = 50;
float tempF_recent = 0;
//________________Run Time________________________
void setup()
{
strip.begin();
strip.show(); // Initialize all pixels to 'off'
strip.setBrightness(50); // Turn down for what 0-255
void loop()
{
getTemp();
temperature_samples[i_temperature_samples] = tempF;
i_temperature_samples++;
if (n_temperature_samples < max_samples) {
n_temperature_samples++;
}
if (i_temperature_samples >= max_samples) {
i_temperature_samples = 0;
}
computeStdDev();
tempColor();
delay(del);
}
void getTemp()
{
//getting the voltage reading from the temperature sensor
int reading = analogRead(sensorPin);
// converting that reading to voltage, for 3.3v arduino use 3.3, for 5v use 5
float voltage = reading * 3.3;
voltage /= 1024.0;
// Convert to Fahrenheit
tempF = (tempC * 9.0 / 5.0) + 32.0;
}//end
void computeStdDev() {
int i;
avg_temperature = 0;
stddev_temperature = 0;
for (i = 0; i < n_temperature_samples; i++){
stddev_temperature = stddev_temperature + (temperature_samples[i] -
avg_temperature) * (temperature_samples[i] - avg_temperature);
}
tempF_recent = 0;
for (i = start_i; i < i_temperature_samples; i++) {
tempF_recent = tempF_recent + temperature_samples[i];
}
tempF_recent /= (i_temperature_samples - start_i);
} else {
tempF_recent = tempF;
}
//Set the RGB color based on standard deviation distance from average
temp
void tempColor()
{
float diff = (tempF_recent - avg_temperature) / stddev_temperature;
× 1
SCHEMATICS
CODE
void loop()
{
int err;
float temp, humi;
if((err=dht11.read(humi, temp))==0) //Read temperature, humidity read
{
Serial.print("temperature:");
Serial.print(temp);
Serial.print(" humidity:");
Serial.print(humi);
Serial.println();
}
else //Processing in case of error
{
Serial.println();
Serial.print("Error No :");
Serial.print(err);
Serial.println();
}
delay(1000); //Repeat every second
}
× 1
× 1
SCHEMATICS
CODE
/*
*/
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <LiquidCrystal.h>
#include <EEPROM.h>
#include <avr/pgmspace.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //8>RS,9>E, 4-7>D4-D7,RW>0V,
SoftwareSerial gpsSerial(2, 3); //RX, TX 2>bleuTX, 3>VertRX
TinyGPS gps;
byte clo_n = 0;
boolean eco_mode = false;
boolean pro_mode = false;
static int vref = 211; // 1023/4.9 volts
byte solPanel = 3; //pin
byte batt = 4; //pin
byte LCD_LED = 11;
byte power_pin = 12;
byte sw_sel = 14;// select
byte sw_up = 15;// up
byte sw_dwn = 16;//down
byte fonction = 0;
int gmt;//, hr ;
long Year_Min;
long Tide_one;
unsigned long time_On;
unsigned long time_run;
unsigned long time_old;
const char*azimuts[] = {"N ", "NE ", "E ", "SE ", "S ", "SW ", "W ", "NW " };
const char custom[][8] PROGMEM = { // Custom character definitions
{ 0x1F, 0x1F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00 }, // char 1
{ 0x18, 0x1C, 0x1E, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }, // char 2
{ 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x0F, 0x07, 0x03 }, // char 3
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x1F, 0x1F }, // char 4
{ 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1E, 0x1C, 0x18 }, // char 5
{ 0x1F, 0x1F, 0x1F, 0x00, 0x00, 0x00, 0x1F, 0x1F }, // char 6
{ 0x1F, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x1F, 0x1F }, // char 7
{ 0x03, 0x07, 0x0F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }, // char 8
};
const char bigChars[][8] PROGMEM = {
{ 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // Space
{ 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // !
{ 0x05, 0x05, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00 }, // "
{ 0x04, 0xFF, 0x04, 0xFF, 0x04, 0x01, 0xFF, 0x01 }, // #
{ 0x08, 0xFF, 0x06, 0x07, 0xFF, 0x05, 0x00, 0x00 }, // $
{ 0x01, 0x20, 0x04, 0x01, 0x04, 0x01, 0x20, 0x04 }, // %
{ 0x08, 0x06, 0x02, 0x20, 0x03, 0x07, 0x02, 0x04 }, // &
{ 0x05, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // '
{ 0x08, 0x01, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00 }, // (
{ 0x01, 0x02, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00 }, // )
{ 0x01, 0x04, 0x04, 0x01, 0x04, 0x01, 0x01, 0x04 }, // *
{ 0x04, 0xFF, 0x04, 0x01, 0xFF, 0x01, 0x00, 0x00 }, // +
{ 0x20, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, //
{ 0x04, 0x04, 0x04, 0x20, 0x20, 0x20, 0x00, 0x00 }, // -
{ 0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // .
{ 0x20, 0x20, 0x04, 0x01, 0x04, 0x01, 0x20, 0x20 }, // /
{ 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x00, 0x00 }, // 0
{ 0x01, 0x02, 0x20, 0x04, 0xFF, 0x04, 0x00, 0x00 }, // 1
{ 0x06, 0x06, 0x02, 0xFF, 0x07, 0x07, 0x00, 0x00 }, // 2
{ 0x01, 0x06, 0x02, 0x04, 0x07, 0x05, 0x00, 0x00 }, // 3
{ 0x03, 0x04, 0xFF, 0x20, 0x20, 0xFF, 0x00, 0x00 }, // 4
{ 0xFF, 0x06, 0x06, 0x07, 0x07, 0x05, 0x00, 0x00 }, // 5
{ 0x08, 0x06, 0x06, 0x03, 0x07, 0x05, 0x00, 0x00 }, // 6
{ 0x01, 0x01, 0x02, 0x20, 0x08, 0x20, 0x00, 0x00 }, // 7
{ 0x08, 0x06, 0x02, 0x03, 0x07, 0x05, 0x00, 0x00 }, // 8
{ 0x08, 0x06, 0x02, 0x07, 0x07, 0x05, 0x00, 0x00 }, // 9
};
const static byte gpsDefault[] PROGMEM = {0xB5, 0x62, 0x06, 0x09, 0x0D, 0x00, 0xFF,
0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x07, 0x1F, 0x9E};
const static byte gpsSave[] PROGMEM = {0xB5, 0x62, 0x06, 0x09, 0x0D, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x31, 0xBF,
0x13};
const static byte gpsSleep[] = {0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x08,
0x00, 0x16, 0x74};
const static byte gpsHot[] = {0xB5, 0x62, 0x06, 0x04, 0x04, 0x00, 0x00, 0x00, 0x02,
0x00, 0x10, 0x68};
const static byte Disable_GPDTM[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x44, 0x54, 0x4d, 0x2a, 0x33, 0x42, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x0a, 0x00, 0x04, 0x23}; //->Disable_GPDTM
const static byte Disable_GPGBS[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x47, 0x42, 0x53, 0x2a, 0x33, 0x30, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x09, 0x00, 0x03, 0x21}; //->Disable_GPGBS
const static byte Disable_GPGGA[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x47, 0x47, 0x41, 0x2a, 0x32, 0x37, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x00, 0x00, 0xfa, 0x0f}; //>Disable_GPGGA
const static byte Disable_GPGLL[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x47, 0x4c, 0x4c, 0x2a, 0x32, 0x31, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x01, 0x00, 0xfb, 0x11}; //->Disable_GPGLL
const static byte Disable_GPGRS[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x47, 0x52, 0x53, 0x2a, 0x32, 0x30, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x06, 0x00, 0x00, 0x1b}; //->Disable_GPGRS
const static byte Disable_GPGSA[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x47, 0x53, 0x41, 0x2a, 0x33, 0x33, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x02, 0x00, 0xfc, 0x13}; //->DisableGPGSA
const static byte Disable_GPGST[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x47, 0x53, 0x54, 0x2a, 0x32, 0x36, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x07, 0x00, 0x01, 0x1d}; //->Disable_GPGST
const static byte Disable_GPGSV[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x47, 0x53, 0x56, 0x2a, 0x32, 0x34, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x03, 0x00, 0xfd, 0x15}; //->Disable_GPGSV
const static byte Disable_GPRMC[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x52, 0x4d, 0x43, 0x2a, 0x33, 0x41, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x04, 0x00, 0xfe, 0x17}; //->Disable_GPRMC
const static byte Disable_GPVTG[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x56, 0x54, 0x47, 0x2a, 0x32, 0x33, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x05, 0x00, 0xff, 0x19}; //->Disable_GPVTG
const static byte Disable_GPZDA[] PROGMEM = {0x24, 0x45, 0x49, 0x47, 0x50, 0x51,
0x2c, 0x5a, 0x44, 0x41, 0x2a, 0x33, 0x39, 0x0d, 0x0a, 0xb5, 0x62, 0x06, 0x01, 0x03,
0x00, 0xf0, 0x08, 0x00, 0x02, 0x1f}; //->Disable_GPZDA
///////////////////////////////////////////////////////
// Minute depuis debut annee //
///////////////////////////////////////////////////////
int days[] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; // Number of days
at the beginning of the month in a not leap year.
long DofY(int yr, int mo, int dy, int h, int mi)
{
int DfY;
long Min2Date;
if (mo == 1 || mo == 2)
{
DfY = days[mo] + dy - 1; //for any type of year, it calculate the number of days
for January or february
}
else if ((yr % 4 == 0 && yr % 100 != 0) || yr % 400 == 0)
{
DfY = days[mo] + dy + 1 - 1;
}
else
{
DfY = days[mo] + dy - 1;
}
Min2Date = (long)DfY * 1440l + (long)h * 60l + (long)mi;
return (Min2Date);
}
///////////////////////////////////////////////////////
// SETUP //
///////////////////////////////////////////////////////
void setup()
{
pinMode(power_pin, OUTPUT);
digitalWrite (power_pin, HIGH); // POWER ON!
analogReference(DEFAULT);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Serial.begin(9600);
gpsSerial.begin(9600);
pinMode(LCD_LED, OUTPUT);
//pinMode(buz, OUTPUT);
pinMode(sw_sel, INPUT);
pinMode(sw_up, INPUT);
pinMode(sw_dwn, INPUT);
lcd.begin(16, 2);
analogWrite(LCD_LED, 100);
///////////////////////////////////////////////////////
// EE PROM Variable //
///////////////////////////////////////////////////////
hour = EEPROM.read(0); //lire le gmt
pro_mode = EEPROM.read(4);
EEPROM.get(10, wp_lat);
EEPROM.get(15, wp_lon);
EEPROM.get(20, Tide_one);
EEPROM.get(25, Odometre);
EEPROM.get(30, time_On);
if (isnan(Odometre)) // test if NAN value
{
Odometre = 0;
}
if (hour > 127) //numbre negatif
{
gmt = hour - 256;
}
else
{
gmt = hour;
}
///////////////////////////////////////////////////////
/// REV ///
///////////////////////////////////////////////////////
lcd.clear();
lcd.print(F("Ultimate YAK GPS"));
lcd.setCursor(0, 1);
lcd.print(F("GPS_1602B rev 92.1")); // Revision Version<<<<
delay (2000);
lcd.clear();
lcd.print("GMT="); lcd.print(gmt);
float vbatt = (float) analogRead(batt) / vref + .21; //
lcd.setCursor(0, 1);
lcd.print(F("Batterie:"));
lcd.print(vbatt);
lcd.print("V");
delay (2000);
lcd.clear();
lcd.print(F("Odometre:"));
lcd.print(Odometre);
delay (2000);
lcd.clear();
lcd.print("WPLat:");
lcd.print(wp_lat);
lcd.setCursor(0, 1);
lcd.print("WPLon:");
lcd.print(wp_lon);
delay (2000);
lcd.clear();
lcd.print("Last Time ON:");
lcd.setCursor(0, 1);
lcd.print(time_On / 60000); lcd.print("Min");
delay (4000);
/*lcd.clear();
lcd.print("TIDE: ");
lcd.print(Tide_one);
float a = (float)Tide_one / 288; //288 = 24hr * 60/ 5 min/hr)
int tide_jr = (int)a;
float b = (a - (float) tide_jr) * 24;
tide_hr = (int)b;
tide_min = (b - (float) tide_hr) * 60 ;
lcd.setCursor(0, 1);
lcd.print(tide_jr + 1);
lcd.print("Days ");
lcd.print(tide_hr);
lcd.print(":");
lcd.print(tide_min);
delay(2000);
*/
///////////////////////////////////////////////////////
// GPS Reset //
///////////////////////////////////////////////////////
lcd.clear();
if (gps.encode(gpsSerial.read()))
{
lcd.print("GPS Reset");
gpsSerial.write(gpsHot, sizeof(gpsHot)); gpsSerial.flush();
gpsSerial.write( gpsDefault, sizeof( gpsDefault)); gpsSerial.flush();
gpsSerial.write( Disable_GPDTM, sizeof( Disable_GPDTM)); gpsSerial.flush();
gpsSerial.write( Disable_GPGBS, sizeof( Disable_GPGBS)); gpsSerial.flush();
gpsSerial.write( Disable_GPGLL, sizeof( Disable_GPGLL)); gpsSerial.flush();
gpsSerial.write( Disable_GPGRS, sizeof( Disable_GPGRS)); gpsSerial.flush();
gpsSerial.write( Disable_GPGSA, sizeof( Disable_GPGSA)); gpsSerial.flush();
gpsSerial.write( Disable_GPGSV, sizeof( Disable_GPGSV)); gpsSerial.flush();
gpsSerial.write( Disable_GPVTG, sizeof( Disable_GPVTG)); gpsSerial.flush();
gpsSerial.write( Disable_GPGGA, sizeof( Disable_GPGGA)); gpsSerial.flush();
}
lcd.setCursor(0, 1); lcd.println(F("Wait satellites."));
///////////////////////////////////////////////////////
/// create 8 custom characters ///
///////////////////////////////////////////////////////
for (nb = 0; nb < 8; nb++ )
{
for (bc = 0; bc < 8; bc++)
bb[bc] = pgm_read_byte( &custom[nb][bc] );
lcd.createChar ( nb + 1, bb );
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// LOOP ///
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{
while (gpsSerial.available()) // check for gps data
{
if (gps.encode(gpsSerial.read())) // encode gps data
{
gps.get_position(&lat, &lon); // get lat and long
gps.crack_datetime(&year, &month, &day, &hour, &minute, &second);
lat = lat / 100; //enlever les d-secondes
lon = lon / 100;
// lcd.setCursor(0, 0); lcd.print (lat); lcd.print (" "); lcd.print (lon); delay (4000);
hour = hour + gmt;
if (hour > 128) // reference a gmt
{
hour = hour + 24;
day = day - 1;
}
////Serial.print ("DofY=");//Serial.println (DofY (year,month,day,hour,minute));
//Serial.print (year); //Serial.print ("/"); //Serial.print (month); //Serial.print ("/");
//Serial.print (day); //Serial.print (" "); //Serial.print (hour); //Serial.print (":");
//Serial.println (minute);
Year_Min = DofY ((int)year, (int)month, (int)day, (int)hour, (int)minute);
//Serial.print ("Year2min ="); //Serial.println (Year_Min);
if (digitalRead(sw_sel) == LOW) {
lcd.clear();
while (digitalRead(sw_sel) == 0) {} // wait for release
menu(0);
}
if (digitalRead(sw_dwn) == LOW)
{
lcd.clear();
while (digitalRead(sw_dwn) == 0) {} // wait for release
if (pro_mode == false)
{
lcd.clear(); lcd.print("PRO Display ");
delay (1500);
pro_mode = true;
EEPROM.write(4, pro_mode);
}
else
{
lcd.clear(); lcd.print("Dashboard MODE ");
pro_mode = false;
EEPROM.write(4, pro_mode);
delay (1500);
}
lcd.clear ();
}
///////////////////////////////////////////////////////
// LCD LED & test de batt //
///////////////////////////////////////////////////////
float vsol = (float) analogRead(solPanel) / vref ; // 1024/2.5voltsRef
if (eco_mode == true) {
LCD_LED_N = 20;
}
else {
LCD_LED_N = 150;
}
if (vsol > 1) {//volt
vsol = 1;//volt
}
LCD_LED_N = LCD_LED_N - (vsol * LCD_LED_N);
analogWrite(LCD_LED, LCD_LED_N);
if (P2P < 5 && speedf != 0) // plus de 5 km est une erreur ou speed =0kmh
{
Odometre += P2P;
lat2 = lat;
lon2 = lon;
EEPROM.put(25, Odometre);
time_run = time_run + (millis() - time_old);
///////////////////////////////////////////////////////
// MENU //
///////////////////////////////////////////////////////
static char* menu_items [] = {"Sel-UP-down", "Power OFF", "Lat-Long & WP ", "Power
Moniteur",
"Eco Mode", "GMT set ", "TIDE set" , "Display Mode", "Odometre", "Retour", "Sel-up-
DOWN"
};
void menu(int menu_index)
{
lcd.clear(); lcd.print(menu_items[menu_index]);
while (digitalRead(sw_sel) == LOW) {}; delay(5); //Debounce
while (digitalRead(sw_sel) != LOW)// Select
{
if (digitalRead(sw_up) == LOW)
{
lcd.clear();
while (digitalRead(sw_up) == LOW) {}; delay(10); //Debounce
menu_index ++;
if (menu_index > 8)
{
menu_index = 0;
}
lcd.clear();
//lcd.setCursor(0, 0); lcd.print(menu_items[0]);
lcd.setCursor(0, 1);
lcd.print(menu_items[menu_index]);
}
if (digitalRead(sw_dwn) == LOW)
{
lcd.clear();
while (digitalRead(sw_dwn) == LOW) {}; delay(10); //Debounce
menu_index -= 1;
if (menu_index < 0)
{
menu_index = 8;
}
lcd.clear();
lcd.print(menu_items[0]);
lcd.setCursor(0, 1);
lcd.print(menu_items[menu_index]);
}
}
lcd.clear();
while (digitalRead(sw_sel) == LOW) {}; delay(100); //Debounce
switch (menu_index)
{
case 1:
///////////////////////////////////////////////////////
// POWER OFF //
///////////////////////////////////////////////////////
{
lcd.clear();
lcd.print ("POWER OFF....");
delay (1500);
digitalWrite(power_pin, LOW);
delay (50);
asm volatile (" jmp 0");
}
break;
case 2:
///////////////////////////////////////////////////////
// LAT et LONG MEMO //
///////////////////////////////////////////////////////
{
lcd.clear ();
lcd.setCursor (0, 0);
lcd.print("Push DWN to Save") ;
lcd.setCursor (0, 1);
lcd.print("WayPoint ") ;
delay (1000); lcd.clear ();
while (digitalRead(sw_sel) != LOW)
{
Print_Latitude (0, 0);
Print_Longitude (0, 1);
if (digitalRead(sw_dwn) == LOW)
{
wp_lat = lat;
wp_lon = lon;
EEPROM.put(10, lat);
EEPROM.put(15, lon);
lcd.clear ();
lcd.setCursor (0, 0);
lcd.print("WayPoint SAVED") ;
delay (1500);
break;
}
if (digitalRead(sw_up) == LOW)
{
lcd.clear ();
lcd.setCursor (0, 0);
lcd.print("Push DWN to Save") ;
while (digitalRead(sw_up) == LOW) {};
delay(1000);
lcd.clear ();
}
gps.get_position(&lat, &lon);
lat = lat / 100; //enlever les d-secondes
lon = lon / 100;
}
lcd.clear ();
while (digitalRead(sw_sel) == LOW) {};
}
break;
case 3:
///////////////////////////////////////////////////////
// POWER MONITOR batt sol //
///////////////////////////////////////////////////////
{
gpsSerial.write(gpsSleep, sizeof(gpsSleep));
while (3)
{
float vsol = (float) analogRead(solPanel) / 204; // 1024/5voltsRef
dtostrf (vsol, 3, 1, msg) ;
lcd.setCursor(0, 0);
lcd.print ("Solaire=");
lcd.print (msg);
lcd.print ("V ");
float vbatt = (float) analogRead(batt) / vref + .21; // 1024/5voltsRef
dtostrf (vbatt, 3, 1, msg) ;
lcd.setCursor(0, 1);
lcd.print ("Batterie=");
lcd.print (msg); lcd.print ("V ");
if ((vsol - vbatt) > .4)//volts
{
lcd.setCursor(12, 1); lcd.print ("V Charge ");
}
else
{
lcd.setCursor(12, 1); lcd.print ("V ");
}
delay (1000);
if (digitalRead(sw_sel) == LOW)
{
lcd.clear();
while (digitalRead(sw_sel) == LOW) {} ;
gpsSerial.write(gpsHot, sizeof(gpsHot));
return;
}
delay (1000);
}
}
break;
case 4:
///////////////////////////////////////////////////////
/// ECO MODE select ///
///////////////////////////////////////////////////////
{
if (eco_mode == false)
{
lcd.setCursor(0, 0); lcd.print("ECONO MODE ON ");
delay (1500);
eco_mode = true;
analogWrite(LCD_LED, 0); // off lcd led
}
else
{
lcd.setCursor(0, 0); lcd.print("ECONO MODE OFF ");
eco_mode = false;
delay (1500);
analogWrite(LCD_LED, LCD_LED_N); // off lcd led
}
lcd.clear ();
}
break;
case 5:
///////////////////////////////////////////////////////
// GMT //
///////////////////////////////////////////////////////
{
//gmt = 0;
while (digitalRead(sw_sel) != LOW)
{
if (digitalRead(sw_up) == LOW)
{
lcd.clear ();
while (digitalRead(sw_up) == LOW) {} ;
gmt ++;
}
if (digitalRead(sw_dwn) == LOW)
{
lcd.clear ();
while (digitalRead(sw_dwn) == LOW) {} ;
gmt --;
}
lcd.clear();
lcd.print ("GMT");
lcd.print(gmt);
delay (300);
}
lcd.clear ();
while (digitalRead(sw_sel) == LOW) {} ;
lcd.setCursor (0, 1);
lcd.print ("SET GMT");
lcd.print(gmt);
EEPROM.write(0, gmt);
delay(1000);
return;
}
break;
case 6:
///////////////////////////////////////////////////////
// SET TIDE //
///////////////////////////////////////////////////////
{
//int tide_min, tide_hr;
lcd.setCursor (0, 0);
lcd.print ("Set ");
lcd.setCursor (0, 1);
lcd.print ("FullMoonHighTide");
EEPROM.get(20, Tide_one);
int tide_mth = 1;
//float a = (float)Tide_one / 288; //288 = 24hr * 60/ 5 min/hr)
int tide_jr = 12; //(int)a;
//float b = (a - (float) tide_jr) * 24;
int tide_hr = 7; // (int)b;
int tide_min = 45; //(b - (float) tide_hr) * 60 ;
///////////////////////////////////////////////////////
lcd.clear ();
while (digitalRead(sw_sel) != LOW)
{
lcd.setCursor (0, 1);
lcd.print (tide_mth); lcd.print("/");
lcd.setCursor (3, 1); lcd.print(tide_jr); lcd.print(" ");
lcd.setCursor (8, 1); lcd.print(tide_hr); lcd.print(":"); lcd.print(tide_min); lcd.print(" ");
lcd.setCursor (0, 0) ;
lcd.print("v--Month ");
delay (350);
if (digitalRead(sw_up) == LOW)
{
tide_mth ++;
}
if (digitalRead(sw_dwn) == LOW)
{
tide_mth --;
}
}
///////////////////////////////////////////////////////
lcd.clear ();
while (digitalRead(sw_sel) == LOW) {}; delay (100);
while (digitalRead(sw_sel) != LOW)
{
lcd.setCursor (0, 1);
lcd.print (tide_mth); lcd.print("/");
lcd.setCursor (3, 1); lcd.print(tide_jr ); lcd.print(" ");
lcd.setCursor (8, 1); lcd.print(tide_hr); lcd.print(":"); lcd.print(tide_min); lcd.print(" ");
lcd.setCursor (3, 0);
delay (350);
lcd.print("v--Day ");
if (digitalRead(sw_up) == LOW)
{
tide_jr ++;
}
if (digitalRead(sw_dwn) == LOW)
{
tide_jr --;
}
}
///////////////////////////////////////////////////////
lcd.clear ();
while (digitalRead(sw_sel) == LOW) {}; delay (100);
while (digitalRead(sw_sel) != LOW)
{
lcd.setCursor (0, 1);
lcd.print (tide_mth); lcd.print("/");
lcd.setCursor (3, 1); lcd.print(tide_jr ); lcd.print(" ");
lcd.setCursor (8, 1); lcd.print(tide_hr); lcd.print(":"); lcd.print(tide_min); lcd.print(" ");
lcd.setCursor (8, 0);
lcd.print("v--Hr ");
delay (350);
if (digitalRead(sw_up) == LOW)
{
tide_hr ++;
}
if (digitalRead(sw_dwn) == LOW)
{
tide_hr --;
}
}
///////////////////////////////////////////////////////
lcd.clear ();
while (digitalRead(sw_sel) == LOW) {}; delay (100);
while (digitalRead(sw_sel) != LOW)
{
lcd.setCursor (0, 1);
lcd.print (tide_mth); lcd.print("/");
lcd.setCursor (3, 1); lcd.print(tide_jr ); lcd.print(" ");
lcd.setCursor (8, 1); lcd.print(tide_hr); lcd.print(":"); lcd.print(tide_min); lcd.print(" ");
lcd.setCursor (5, 0);
lcd.print("Min--v ");
delay (350);
if (digitalRead(sw_up) == LOW)
{
tide_min += 5;
}
if (digitalRead(sw_dwn) == LOW)
{
tide_min -= 5;
}
if (tide_min < 1) {
tide_min = 1; // prevention 0/5
}
}
lcd.clear ();
while (digitalRead(sw_sel) == LOW) {}
Tide_one = DofY (year, tide_mth, tide_jr, tide_hr, tide_min);
lcd.setCursor (0, 0);
lcd.print ("Tide_one="); lcd.print (Tide_one); lcd.print (" ");
lcd.setCursor (0, 1);
lcd.print (tide_mth); lcd.print("/"); lcd.print (tide_jr ); lcd.print (" "); lcd.print (tide_hr);
lcd.print (":"); lcd.print (tide_min);
delay (3500);
while (digitalRead(sw_sel) == LOW) { }
lcd.clear ();
lcd.print ("Push Dwn to Save");
while (digitalRead(sw_sel) != LOW)
{
if (digitalRead(sw_dwn) == LOW)
{
if (Tide_one > 0)
{
EEPROM.put(20, Tide_one);
lcd.clear ();
lcd.print ("TIDE SAVED");
lcd.setCursor (0, 1);
lcd.print (Tide_one);
delay (2000);
while (digitalRead(sw_dwn) == LOW) { }
lcd.clear ();
return;
}
else
{
lcd.clear ();
lcd.print ("TIDE E R R O R");
lcd.setCursor (0, 1);
lcd.print (Tide_one);
delay (2500);
lcd.clear ();
return;
}
}
delay (50);
}
lcd.clear ();
return;
}
break;
case 7:
///////////////////////////////////////////////////////
// PRO MODE //
///////////////////////////////////////////////////////
{
if (pro_mode == false)
{
lcd.clear(); lcd.print("PRO Display ");
delay (1500);
pro_mode = true;
EEPROM.write(4, pro_mode);
}
else
{
lcd.clear(); lcd.print("Dashboard ");
pro_mode = false;
EEPROM.write(4, pro_mode);
delay (1500);
}
lcd.clear ();
}
break;
case 8:
///////////////////////////////////////////////////////
// ODOMETRE //
///////////////////////////////////////////////////////
{
Odometre = 0;
time_run = 0;
lat2 = lat;
lon2 = lon;
lcd.clear(); lcd.print("Odometre Reset");
delay (1500); lcd.clear ();
}
break;
default:
{
}
return;
}
}
/////////////////////////////////////////////////////////////////////////////////////
// SUBROUTINES //
/////////////////////////////////////////////////////////////////////////////////////
// writeBigChar: writes big character 'ch' to column x, row y; returns number of columns
used by 'ch'
int writeBigChar(char ch, byte x, byte y) {
if (ch < ' ' || ch > '_') return 0; // If outside table range, do nothing
nb = 0; // character byte counter
for (bc = 0; bc < 8; bc++) {
bb[bc] = pgm_read_byte( &bigChars[ch - ' '][bc] ); // read 8 bytes from PROGMEM
if (bb[bc] != 0) nb++;
}
bc = 0;
for (row = y; row < y + 2; row++) {
for (col = x; col < x + nb / 2; col++ ) {
lcd.setCursor(col, row); // move to position
lcd.write(bb[bc++]); // write byte and increment to next
}
}
return nb / 2 - 1; // returns number of columns used by char
}
// writeBigString: writes out each letter of string
void writeBigString(char *str, byte x, byte y)
{
char c;
while ((c = *str++))
x += writeBigChar(c, x, y) + 1;
}
///////////////////////////////////////////////////////
// HORLOGE //
///////////////////////////////////////////////////////
void horloge(int C, int R)
{
lcd.setCursor(C, R);
lcd.print(hour); lcd.print(":");
if (minute < 10)
{
lcd.print("0");
}
lcd.print(minute);
lcd.print(" ");
}
///////////////////////////////////////////////////////
// LATITUDE //
///////////////////////////////////////////////////////
void Print_Latitude(int C, int R)
{
long latdeg = (lat / 10000);
lcd.setCursor(C, R);
lcd.print("Lat:");
lcd.print(abs(latdeg));
lcd.print((char)223);
float x = (float)(lat - latdeg * 10000) * .6 / 100;
lcd.print(x); lcd.print("'");
if (lat > 0)
{
lcd.print ("N");
}
else
{
lcd.print("S");
}
}
///////////////////////////////////////////////////////
// PRINT LONGITUDE //
///////////////////////////////////////////////////////
void Print_Longitude(int C, int R)
{
long londeg = (lon / 10000);
lcd.setCursor(C, R);
lcd.print("Lon:");
lcd.print(abs(londeg));
lcd.print((char)223);
float x = (float) (abs(lon) - abs(londeg) * 10000) * .6 / 100;
lcd.print(x); lcd.print("'");
if (lon > 0) {
lcd.print("E");
}
else {
lcd.print("W");
}
}
///////////////////////////////////////////////////////
// TIDE CLOCK display //
///////////////////////////////////////////////////////
void Print_Tide(int C, int R)
{
EEPROM.get(20, Tide_one);
const char*tideclock [] {"HIGH ", "L 5Hr ", "L 4Hr ", "L 3Hr ", "L 2Hr ", "L 1Hr ",
"LOW ", "H 5Hr ", "H 4Hr ", "H 3Hr ", "H 2Hr ", "H 1Hr ", "HIGH ", "ERR "};
//Serial.print ("y min="); //Serial.println (Year_Min);
//Serial.print ("tide 1="); //Serial.println (Tide_one);
long tide_cycle = (Year_Min - Tide_one);
//Serial.print ("tide cycle="); //Serial.println (tide_cycle);
float tide_cyclef = (float)tide_cycle / 745.233333f; //Tide 12h25m14sec (745.23 min)
dtostrf (tide_cyclef, 1, 6, msg) ;
//Serial.print ("tide cyclef="); //Serial.println (msg);
tide_cyclef = tide_cyclef - int(tide_cyclef);
dtostrf (tide_cyclef, 1, 6, msg) ;
//Serial.print ("tide cyclefraction="); //Serial.println (msg);
tide_cyclef = tide_cyclef * 12;
dtostrf (tide_cyclef, 1, 6, msg) ;
tide_cycle = round (tide_cyclef);
lcd.setCursor(C, R);
lcd.print ("Tide:");
lcd.print (tideclock[tide_cycle]);
//; break;
× 1
Buzzer
× 1
LED (generic)
× 1
SparkFun Pushbutton switch
12mm
× 1
× 10
APPS AND ONLINE SERVICES
Arduino IDE
Although I am pretty new to the IoT and Arduino stage, with the help
of my friends and classmates and my professor I got into it pretty
quickly. This was one of my first real projects, finished a while ago,
but I am still making improvements.
Morse Code
Considering I knew Morse code as a kid, and that I wanted to play with
the components, I decided on the Morse machine.
The isn't to hard to make, it requires some basic parts (listed below)
and some basic programming skill (feel free to play with the code and
make it more interesting/efficient). Although writing in Morse code is
pretty hard you get a hang of it after a while. I practiced with printed
out sheet which you can get online. Don't feel bad if you make
mistakes or the timer feels odd, for practice I advise to change those
variable values to make it easier to practice and when you become a
pro, turn down those values, so you sound like a pro.
SCHEMATICS
CODE
int pause_value = 250; // depending on your skill and how fast your fingers are you can
change this value to make typing a message faster or slower
long signal_length = 0;
long pause = 0;
long lastDebounceTime = 0;
long debounceDelay = 50;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzer, OUTPUT);
while(!digitalRead(buttonPin))
;
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState && lastButtonState) // basic state machine depending on the state of the
signal from the button
{
++signal_length;
if (signal_length<2*pause_value) //this help to notice that there is a change in the
signal length aka that its not a dot anymore but a dash
{ // best use for the measuring of signal_length would be use of the
millis() but this was used for simplicity
tone(buzzer, 1500) ;
}
else
{
tone(buzzer, 1000) ;
}
}
else if(!buttonState && lastButtonState) //this part of the code happens when the
button is released and it send either * or - into the buffer
{
else if (prevodilac=="*----")
Serial.print("1");
else if (prevodilac=="**---")
Serial.print("2");
else if (prevodilac=="***--")
Serial.print("3");
else if (prevodilac=="****-")
Serial.print("4");
else if (prevodilac=="*****")
Serial.print("5");
else if (prevodilac=="-****")
Serial.print("6");
else if (prevodilac=="--***")
Serial.print("7");
else if (prevodilac=="---**")
Serial.print("8");
else if (prevodilac=="----*")
Serial.print("9");
else if (prevodilac=="-----")
Serial.print("0");
Serial.print(" ");
prevodilac="";
}
63) Arduino Insteon Gateway
COMPONENTS AND SUPPLIES
× 1
× 1
Insteon PLM
× 1
Arduino wiring shield
× 1
Plastic enclosure
× 1
The project is about Home Automation. I have some devices that are
Insteon-based. Insteon uses a proprietary protocol to make the devices
communicate wirelessly together, in a mesh topology.
Here are examples:
Dimmer Module,
On/off Module,
Dimmer Switch,
On/off Switch,
Dimmer Keypad (by 8 or by 6),
Thermostat,
Motion detector
The goal of this project is to build a gateway betwen Insteon world and
a generic MQTT broker, over IP BUT without dependency to Insteon
Cloud.
Features
Here are the features provided by the "Insteon gateway":
Gather and publish statuses: Arduino will (over a serial link to the
PLM ) get info published by all devices, display them on the front
panel, convert it to MQTT messages and send them to the MQTT
broker
Listen, push and execute commands: Arduino will listen to specific
MQTT queues (one per targeted Insteon device, display the
messages to the front panel and push those commands to the PLM
(over serial link). PLM will transfer those commands to the targeted
devices.
SCHEMATICS
CODE
#include <ArduinoJson.h>
#include <avr/wdt.h>
#include <Ethernet.h>
#include <LiquidCrystal.h>
#include <Network.h>
#include <PubSubClient.h>
#include <QueueArray.h>
#include "SoftwareSerial.h"
#include <SPI.h>
#include <Timer.h>
// HW pinout
const int LCD_E_PIN PROGMEM = 2; // LCD
const int RESET_BTN_PIN PROGMEM = 3; // goes to LOW
when someone press on the button and then goes to HIGH when button is released,
otherwise pull-down to GND
const int SD_CARD_PIN PROGMEM = 4; // SD card on
ethernet shield, not used
const int LCD_DB4_PIN PROGMEM = 5; // LCD
const int LCD_DB5_PIN PROGMEM = 6; // LCD
const int LCD_DB6_PIN PROGMEM = 7; // LCD
const int LCD_DB7_PIN PROGMEM = 8; // LCD
const int LCD_RS_PIN PROGMEM = 9; // LCD
const int INSTEON_TX PROGMEM = 16; // TX to INSTEON
PLM
const int INSTEON_RX PROGMEM = 17; // RX from
INSTEON PLM
// Network
const byte mac[] = { 0xDE, 0xED, 0xBE, 0xBB, 0xFC, 0xAC }; // Arduino's
MAC address
IPAddress ip(192, 168, 1, 221); // Arduino's IP address
IPAddress server(192, 168, 1, 100); // MQTT broker's address
(Orechestrator)
EthernetClient ethClient;
// MQTT
PubSubClient client(ethClient);
const int mqttInterval PROGMEM = 300; // determines how often
the system will report to MQTT broker (ie. every mqttInterval * mainLoopDelay ms )
int mqttIntervalCnt = 0; // local variable used to count
down
int isConnectedToBroker = -1; // 1 when connected, -1 =
unknown, 0 = unable to connected
#define INSTEONGATEWAY "PLM"
// Insteon
SoftwareSerial InsteonSerial(INSTEON_RX, INSTEON_TX, true); // This is
what we use to send/receive Insteon commands using the home automation shield
const int PLMtimeOut PROGMEM = 1000; // in millisec
int inByte[26]= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // for storing
incoming serial bytes
int outByte[26]= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // for storing
ougoing serial bytes
const int zeroByte PROGMEM= 0x00; // I use this because if I
do "Serial.write (0);" instead I get a compile error
const int startByte PROGMEM = 0x02; // Every Insteon message
begins with this
const int msgLength PROGMEM = 30; // Used to assign an
expected length for the message... starts out high so that we don't prematurely trigger an
end-of-message
int i = 0; // Looping variable for incoming
messages
int j = 0; // Looping variable for outgoing
messages
// Local queue
volatile QueueArray <byte> cmdQueue; // each command received
from MQTT broker is stored here
byte* incoming; // an incoming message to route to
Insteon network
// Logic
const int mainLoopDelay = 500; // a fixed delay within main
loop, in ms
void(* resetFunc) (void) = 0;
// Initialization
void setup()
{
wdt_disable(); // disable watchdog
Serial.begin(19200); // open console port
Serial.println(F("Begin of setup"));
pinMode(SD_CARD_PIN, OUTPUT); // always good to disable it, if
it was left 'on' or you need init time
digitalWrite(SD_CARD_PIN, HIGH); // to disable SD card since we
do not use it
pinMode (RESET_BTN_PIN, INPUT);
InsteonSerial.begin(19200); // open another serial port for Insteon
PLM
cmdQueue.setPrinter (Serial); // setup local queue
lcd.begin(LCD_COLUMNS, LCD_ROWS); // set up the LCD's number
of columns and rows:
testLCD(); // just a welcome message
client.setServer(server, 1883); // setup MQTT
client.setCallback(MQTTBrokerCallback);
Ethernet.begin(mac, ip); // setup network
Serial.print(F("Current IP is : "));
Serial.print(Ethernet.localIP());
Serial.print(F(" - MQTT broker IP is : "));
Serial.println(server);
enableInterruptOnResetButton(); // from here, interrupts are trapped
subscribeToToDoLists(); // from here, callbacks are trapped
delay(1500); // allow hardware to sort itself out
Serial.println(F("End of setup")); Serial.println();
}
// Main loop
void loop()
{
if (isResetRequested == 1) {resetAll();} // someone pressed the Reset button
// Part 1 : deal with messages originating from Insteon PLM
// Part 2 : deal with messages originating from MQTT Broker. Those messages are waiting
in a local queue
if (mqttIntervalCnt == 0)
{
Serial.println(F("Reporting gateway status to MQTT Broker..."));
routeGatewayStatusMessageToBroker();
mqttIntervalCnt = mqttInterval;
Serial.println();
}
else
{
mqttIntervalCnt = mqttIntervalCnt - 1;
}
// Take some rest
delay(mainLoopDelay / 2 );
client.loop();
delay(mainLoopDelay / 2);
}
int parseMessage()
{
byte b;
int hex_digit_to_read = 2;
bool reading_hex = true;
byte hex = 0;
for(int j=0;j<26;j++) outByte[j] = 0xFF;
while (!cmdQueue.isEmpty ())
{
b = cmdQueue.dequeue();
if (b == ':') // delimiter between each set of 2 characters
{
hex = 0;
hex_digit_to_read = 2;
reading_hex = true;
continue;
};
if (hex_digit_to_read > 0)
{
hex = (hex << 4) | CharToHex(b);
hex_digit_to_read--;
};
if (reading_hex && hex_digit_to_read == 0)
{
reading_hex = false;
if (hex == 0x02) // end of message
{
hex_digit_to_read = 2;
reading_hex = true;
hex = 0;
j = 0;
return 0;
}
else
{
outByte[j] = hex;
Serial.print(hex, HEX);
Serial.print(' ');
j++;
};
};
};
}
// Send commands to Insteon devices
int sendMessageToInsteonDevice()
{
Serial.print(F("Sending command to Insteon devices : "));
sendCmd(2, false);
sendCmd(98, false);
sendCmd(outByte[1], true);
sendCmd(outByte[2], true);
sendCmd(outByte[3], true);
sendCmd(15, false);
sendCmd(outByte[4], false);
sendCmd(outByte[5], false);
Serial.println();
}
// Gather bytes sent by Insteon PLM in order to get a well structured message
int receiveMessageFromPLM()
{
long start_time = millis();
int currentIndex = 0;
for(int j=0;j<26;j++) inByte[j] = 0;
byte currentByte;
while (true)
{
if ((millis() - start_time) > PLMtimeOut) // we should get a complete message in a short
period of time
{
displayError1();
return 1;
};
if (InsteonSerial.available() > 0)
{
if (currentIndex == 0)
{
Serial.print(F("### New message entering : "));
}
currentByte = InsteonSerial.read();
inByte[currentIndex] = currentByte;
displayRawData(currentByte);
if (currentIndex == 0 && currentByte != startByte) // a new message should always start
with the specified start byte
{
// displayError2(currentByte);
return 2;
};
if (currentIndex > 11) // message looks longer than expected
{
return 4;
};
if (currentIndex == 10) // message has been received as expected
{
return 0; // full message received
};
currentIndex = currentIndex + 1; // just keep going with parsing
};
};
}
void routeGroupBroacastToInsteon()
{
// displayInsteonOutgoingGroupBroadcast();
for (int i=0;i<26;i++)
{
if ( outByte[i] == 0xFF) { break;}
Serial.print(InsteonSerial.write(outByte[i]));
}
}
void resetAll()
{
Serial.println(F("Someone pushed on the button to reset this device"));
displayInfo("Reset requested");
routeGatewayStatusMessageToBroker();
wdt_enable(WDTO_1S); //enable watchdog, will fire in 1 second
delay(5000);
Serial.println(F("This message should never appear... unless this board is a zombie"));
}
void enableInterruptOnResetButton()
{
isResetRequested = 0;
attachInterrupt(1, onResetRequested, CHANGE);
}
void onResetRequested()
{
detachInterrupt(1);
isResetRequested = 1;
}
//
// MQTT related functions
//
// NOTE : MQTT_MAX_PACKET_SIZE = 128 bytes.. therefore not more than 100 for the
payload !!!!!!!
// unless you change it in /Arduino/libraries/pubSubClient/src/PubSubClient.h
void routeGroupBroadcastMessageToBroker()
{
char topic[30];
strcpy(topic, "GLI");
strcat(topic, "/");
strcat(topic, byteToHexaString(inByte[2]));
strcat(topic, "-");
strcat(topic, byteToHexaString(inByte[3]));
strcat(topic, "-");
strcat(topic, byteToHexaString(inByte[4]));
strcat(topic,"/");
strcat(topic, "WhishList");
char payload[100];
strcpy(payload, "{");
strcat(payload,"\n");
strcat(payload,"\"Group\": ");
strcat(payload, byteToString(inByte[7]));
strcat(payload, ",");
strcat(payload,"\n");
strcat(payload,"\"Command\": ");
strcat(payload, byteToHexaString(inByte[9]));
strcat(payload, ",");
strcat(payload,"\n");
strcat(payload,"\"Parameters\": ");
strcat(payload, byteToString(inByte[10]));
strcat(payload,"\n");
strcat(payload,"}");
publishMsg( topic, payload);
}
void routeGatewayStatusMessageToBroker()
{
char topic[30];
strcpy(topic, "GLI");
strcat(topic, "/");
strcat(topic, "Gateway");
strcat(topic,"/");
strcat(topic, "Status");
char payload[100];
strcpy(payload, "{");
strcat(payload,"\n");
strcat(payload,"\"ManualReset\": ");
strcat(payload,"\n");
if (isResetRequested == 1) { strcat(payload, "Yes");} else {strcat(payload, "No");};
strcat(payload,"\n");
strcat(payload, ",");
strcat(payload,"\n");
strcat(payload,"\"LocalQueueLevel\": ");
// strcat(payload, intToString(cmdQueue.count));
strcat(payload,"}");
publishMsg( topic, payload);
}
// Subscribe to the MQTT broker to get list of commands to forward to Insteon devices
(topic = GLI/Gateway/ToDo)
void subscribeToToDoLists()
{
if (connectToBroker() == true)
{
char topic[50];
strcpy(topic, "GLI");
strcat(topic, "/");
strcat(topic, "Gateway");
strcat(topic,"/");
strcat(topic, "ToDo");
client.subscribe(topic); // otherwise subscriptions will growth forever..
if (client.subscribe(topic) == true)
{
isConnectedToBroker = 1;
Serial.print(F("Registred to MQTT broker as a subscriber for the following topic: "));
Serial.println(topic);
}
else
{
Serial.println(F("Not registred to MQTT broker as a subscriber"));
isConnectedToBroker = 0;
}
client.loop();
}
else
{
isConnectedToBroker = 0;
Serial.println(F("Cannot subscribe to any topic since connection to MQTT broker is not
established"));
}
}
// This function will be invoked by MQTT broker each time a message is added to
GLI/Gateway/ToDo queue
int connectToBroker()
{
// Serial.println(F(""));
// Serial.print(F("Connecting to network and to MQTT Broker... "));
if (client.connect(INSTEONGATEWAY) == true)
{
// Serial.print(F("connected as "));
// Serial.println(INSTEONGATEWAY);
}
else
{
switch (client.state())
{
case -4:
Serial.println(F("MQTT_CONNECTION_TIMEOUT - the server didn't respond within the
keepalive time"));
break;
case -3:
Serial.println(F("MQTT_CONNECTION_LOST - the network connection was broken"));
break;
case -2:
Serial.println(F("MQTT_CONNECT_FAILED - the network connection failed"));
break;
case -1:
Serial.println(F("MQTT_DISCONNECTED - the client is disconnected cleanly"));
break;
case 0:
break;
case 1:
Serial.println(F("MQTT_CONNECT_BAD_PROTOCOL - the server doesn't support the
requested version of MQTT"));
break;
case 2:
Serial.println(F("MQTT_CONNECT_BAD_CLIENT_ID - the server rejected the client
identifier"));
break;
case 3:
Serial.println(F("MQTT_CONNECT_UNAVAILABLE - the server was unable to accept the
connection"));
break;
case 4:
Serial.println(F("MQTT_CONNECT_BAD_CREDENTIALS - the username/password
were rejected"));
break;
case 5:
Serial.println(F("MQTT_CONNECT_UNAUTHORIZED - the client was not authorized to
connect"));
break;
default:
Serial.print("failed, rc=");
Serial.println(client.state());
break;
}
}
return client.connected();
}
//
// LCD management
//
void displayInsteonGroupBroadcast()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print('G');
lcd.setCursor(2,0);
lcd.print(inByte[2], HEX);
lcd.print('-');
lcd.print(inByte[3], HEX);
lcd.print('-');
lcd.print(inByte[4], HEX);
lcd.setCursor(0,1);
lcd.print("CMD");
lcd.setCursor(5,1);
lcd.print(inByte[9], HEX);
lcd.setCursor(8,1);
lcd.print("TO ");
lcd.setCursor(11,1);
lcd.print(inByte[7]);
delay(1000);
}
char* byteToHexaString(byte b)
{
char buff[4];
snprintf(buff, 4, "%02X", b);
return buff;
}
char* byteToString(byte b)
{
char buff[4];
snprintf(buff, 4, "%d", b);
return buff;
}
char* intToString(int i)
{
char buff[4];
snprintf(buff, 4, "%d", i);
return buff;
}
byte CharToHex(char c)
{
byte out = 0;
if( c >= '0' && c <= '9'){
out = (byte)(c - '0');
}
else if ( c >= 'A' && c <= 'F'){
out = (byte) (c - 'A') + 10;
}
else if ( c >= 'a' && c <= 'f'){
out = (byte) (c - 'a') + 10;
}
return out;
}
× 1
× 1
ntroduction
In this tutorial, I am going to show you how to detect the fullness of
a paper shredder and send a notification via Gmail using Arduino Uno.
I made this tutorial for beginners! It is really easy!
Assembly
Assembly
1. Stack PHPoC Shield on Arduino
2. Connect LAN cable or USB wifi Dongle to the shield for Ethernet
3. Pin wiring between Arduino and Sensor.
#define PIN_TRIG 5
#define PIN_ECHO 6
#define BIN_HEIGHT 20 // maximum containable height of bin in centimeters
#include "SPI.h"
#include "Phpoc.h"
long ultrasonicGetDistance();
boolean dustbinSendGmail();
PhpocEmail email;
boolean isSent = false;
void setup() {
Serial.begin(9600);
while(!Serial)
;
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
void loop() {
long distance = 0;
// read 10 time and get average value to eliminate noises
for(int i = 0; i < 100; i++)
{
long temp = 0;
do
{
temp = ultrasonicGetDistance();
}
while(temp > BIN_HEIGHT);
distance += temp;
delay(10);
}
distance /= 100;
Serial.print(distance);
Serial.println(" cm");
if(distance <= 5)
{
if(!isSent)
{
Serial.println("Dustbin is almost full");
isSent = dustbinSendGmail();
}
}
else if(isSent && distance > 8) // avoid send alot of email when the distance is oscillated
around 5cm
isSent = false;
delay(500);
}
long ultrasonicGetDistance(){
long duration, distance;
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
duration = pulseIn(PIN_ECHO, HIGH);
distance = (duration/2) / 29.1;
return distance;
}
boolean dustbinSendGmail(){
// setup outgoing relay server - gmail.com
email.setOutgoingServer("smtp.gmail.com", 587);
email.setOutgoingLogin("your_login_id", "your_login_password");
// setup From/To/Subject
email.setFrom("from_email_address", "from_user_name");
email.setTo("to_email_address", "to_user_name");
email.endMessage();
// send email
if(email.send() > 0)
{
Serial.println("Email send ok");
return true;
}
else
{
Serial.println("Email send failed");
return false;
}
}
65) Arduino 4 Digit 7 Segment Counter with Lipo Backup
× 1
× 7
× 4
Battery, 3.7 V
LiPo Battery 18650, 3000mAH
× 1
ABOUT THIS PROJECT
// variable declarations
byte current_digit;
int count = 0;
void setup()
{
pinMode(button, INPUT_PULLUP);
pinMode(button_minus, INPUT_PULLUP);
pinMode(button_10, INPUT_PULLUP);
pinMode(button_100, INPUT_PULLUP);
pinMode(button_reset, INPUT_PULLUP);
pinMode(SegA, OUTPUT);
pinMode(SegB, OUTPUT);
pinMode(SegC, OUTPUT);
pinMode(SegD, OUTPUT);
pinMode(SegE, OUTPUT);
pinMode(SegF, OUTPUT);
pinMode(SegG, OUTPUT);
pinMode(Dig1, OUTPUT);
pinMode(Dig2, OUTPUT);
pinMode(Dig3, OUTPUT);
pinMode(Dig4, OUTPUT);
switch (current_digit)
{
case 1:
if (count >= 1000)
{
disp(count / 1000); // prepare to display digit 1 (most left)
digitalWrite(Dig1, HIGH); // turn on digit 1
}
break;
case 2:
if (count >= 100)
{
disp( (count / 100) % 10); // prepare to display digit 2
digitalWrite(Dig2, HIGH); // turn on digit 2
}
break;
case 3:
if (count >= 10)
{
disp( (count / 10) % 10); // prepare to display digit 3
digitalWrite(Dig3, HIGH); // turn on digit 3
}
break;
case 4:
disp(count % 10); // prepare to display digit 4 (most right)
digitalWrite(Dig4, HIGH); // turn on digit 4
}
current_digit = (current_digit % 4) + 1;
}
// main loop
void loop()
{
if(digitalRead(button) == 0)
{
count++; // increment 'count' by 1
if(count > 9999)
count = 0;
delay(200); // wait 200 milliseconds
}
else if(digitalRead(button_minus) == 0)
{
count--; // decrement 'count' by 1
if(count < 0)
count = 9999;
delay(200); // wait 200 milliseconds
}
else if(digitalRead(button_10) == 0)
{
count=count+10; // increment by 10
if(count > 9999)
count = 0;
delay(200); // wait 200 milliseconds
}
else if(digitalRead(button_100) == 0)
{
count=count+100; // increment by 100
if(count > 9999)
count = 0;
delay(200); // wait 200 milliseconds
}
else if(digitalRead(button_reset) == 0)
{
count=0; // reset
delay(200); // wait 200 milliseconds
}
}
case 1: // print 1
digitalWrite(SegA, LOW);
digitalWrite(SegB, HIGH);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, LOW);
digitalWrite(SegE, LOW);
digitalWrite(SegF, LOW);
digitalWrite(SegG, LOW);
break;
case 2: // print 2
digitalWrite(SegA, HIGH);
digitalWrite(SegB, HIGH);
digitalWrite(SegC, LOW);
digitalWrite(SegD, HIGH);
digitalWrite(SegE, HIGH);
digitalWrite(SegF, LOW);
digitalWrite(SegG, HIGH);
break;
case 3: // print 3
digitalWrite(SegA, HIGH);
digitalWrite(SegB, HIGH);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, HIGH);
digitalWrite(SegE, LOW);
digitalWrite(SegF, LOW);
digitalWrite(SegG, HIGH);
break;
case 4: // print 4
digitalWrite(SegA, LOW);
digitalWrite(SegB, HIGH);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, LOW);
digitalWrite(SegE, LOW);
digitalWrite(SegF, HIGH);
digitalWrite(SegG, HIGH);
break;
case 5: // print 5
digitalWrite(SegA, HIGH);
digitalWrite(SegB, LOW);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, HIGH);
digitalWrite(SegE, LOW);
digitalWrite(SegF, HIGH);
digitalWrite(SegG, HIGH);
break;
case 6: // print 6
digitalWrite(SegA, HIGH);
digitalWrite(SegB, LOW);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, HIGH);
digitalWrite(SegE, HIGH);
digitalWrite(SegF, HIGH);
digitalWrite(SegG, HIGH);
break;
case 7: // print 7
digitalWrite(SegA, HIGH);
digitalWrite(SegB, HIGH);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, LOW);
digitalWrite(SegE, LOW);
digitalWrite(SegF, LOW);
digitalWrite(SegG, LOW);
break;
case 8: // print 8
digitalWrite(SegA, HIGH);
digitalWrite(SegB, HIGH);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, HIGH);
digitalWrite(SegE, HIGH);
digitalWrite(SegF, HIGH);
digitalWrite(SegG, HIGH);
break;
case 9: // print 9
digitalWrite(SegA, HIGH);
digitalWrite(SegB, HIGH);
digitalWrite(SegC, HIGH);
digitalWrite(SegD, HIGH);
digitalWrite(SegE, LOW);
digitalWrite(SegF, HIGH);
digitalWrite(SegG, HIGH);
}
}
void disp_off()
{
digitalWrite(Dig1, LOW);
digitalWrite(Dig2, LOW);
digitalWrite(Dig3, LOW);
digitalWrite(Dig4, LOW);
}
// end of code.
66) Arduino Wireless Weather Station
× 1
LED (generic)
× 6
Buzzer
× 1
× 1
× 3
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
Electric file
Multimeter
APPS AND ONLINE SERVICES
Arduino IDE
ThingSpeak API
fig. 1
Wi-Fi ESP8266 E-12 Wi-Fi module (#6)
I guess it's pretty obvious what this part is used for and that's connecting to
a local Wi-Fi network (preconfigured in the source code) and sending the
sensor data to www.thingspeak.com
On/Off Switch (#10)
It seems that one cannot upload a new source code file on the Arduino
Uno while having the TX pin connected to another component. If you try
to do so you would get a lot of errors in Arduino IDE. While uploading a
new sketch the TX pin should be "floating". To do so, I've used a on/off
switch to disconnect the TX line from the ESP8266 whenever I want to
upload an new code on the board. (check schematics down bellow)
MQ-7 Gas Sensor (#5)
Used for reading the CO level in the air. The value provided is measured
in ppm.
As stated earlier check the datasheet to see the working principle. The
sensor needs to be powered for 90s@5v, time during which no reading
is done, and [email protected], time which represents the reading period.
Check the datasheet for info on calibrating the sensor.
Reset button (#9)
Since the hole wiring will be hidden inside a box a the end of this project,
with the Arduino Uno stuck with hot glue at the bottom of box, uploading
a new sketch on the board it would pose quite a problem when it comes to
physically reseting the board without opening the box. To solve this issue
we would need an external reset button. That's exactly what this big red
button does. It resets the board.
The LED's (#9)
11 - general error indicator (for debugging the error we would need to
connect the board to a pc and check the Serial Monitor Interface in
Arduino IDE for the error message)
12 - signals the presence/absence of the ESP8266 in the current system
13 - signals if ESP8266 is connected/not connected to the local network
14 - signals sending sensor data tot thingspeak.com
15 - blinks whenever the MQ-7 is heating
16 - blinks whenever Arduino Uno reads data from sensors
The Buzzer
Whenever the CO level read from the MQ-7 gas sensor exceeds a certain
value hardcoded in the code, an alarm will be triggered by using the
buzzer.
Software requirements:
In order to see the value of sensor data, we will need a private channel
on thingspeak.com. We will also need Arduino IDE to write/upload the
code for Arduino Uno.
List of software requirements:
Private channel on Thingspeak.com and
Arduino IDE (Preferably latest version).
In order for the sketch to work we will also need the DHT11 library which
you can download in the attachment section down bellow. For a step by
step tutorial on how to add this library to
Now lets create a private channel on thingspeak.com
Creating private channel on Thingspeak.com
To make a private channel on thingspeak.com follow these steps:
Open your web browser and go to thingspeak.com and click on 'Sign
Up' tab in right top corner, (Image no.1)
Fill in the details and click on 'Create account', (Image no.2)
Now click on 'New Channel' tab, (Image no.3)
Again fill in details for channel and enable 4 fields (as we will be
sending 4 sensor values), scroll down and click on 'Save Channel' tab,
(Image no.4/5)
On this page click on 'API Keys' tab and note down your 'Write API
Key'.
That's all folks, now you have your private ThingSpeak channel. Now lets
put all electronics component together.
The Code
The code for Portable weather station is quite simple. I have commented
code properly for ease of portability. Before you burn the code take care of
following things.
Make sure that all libraries are installed,
Replace hyphens (--------) with SSID of your access point (wifi router)
in line 14 of the code,
Replace hyphens (--------) with PASSWORD of your wifi network in
line 15 of the code,
Replace hyphens (--------) with your ThingSpeak's private channel write
API key in line 17 and
While uploading the code to the Arduino make sure that the on/off
switch on the TX line is set to "off" so that you can upload the code
Now that we have our hardware and software in place, only thing
remaining is packaging.
The logic
If you find the code pretty difficult to understand take a look on the logic
diagram down bellow:
Logical Diagram
Blinking order
Packaging and enclosing the system
Down bellow you are going to find some useful photos taken while I was
preparing the enclosure for the system. Make sure you have the tools
required to make a box like the one bellow (elecrtic file, soldering iron,
hot glue gun...)
As you can see in the third image above I've used some generic
"mother" type pins soldered together for providing power/ground to the
components of the system. I've then hot glue the piece to the side panel
of the box, inside of it.
Results
You can check the results of this project by clicking on the following link
which should redirect you to the public view of my thingspeak
channel: https://thingspeak.com/channels/152176
Plotted data
Problems encountered during development
Sometimes some parts of the system went unresponsive due to poor
contact on the breadboard. If the ESP8266 becomes unresponsive out of
a sudden, first thing I would suggest doing would be to check the
connections once again
If you see a lot of garbage in the Serial Monitor console make sure the
baud rate in the console is set accordingly with the ESP8266 settings.
For more info on changing the baud rate of the Serial Montior console
check the following link: https://learn.adafruit.com/adafruit-arduino-
lesson-5-the-serial-monitor/other-things-to-do
For more info on changing the baud rate setting of the ESP8266 check the
following link: http://www.esp8266.com/viewtopic.php?f=13&t=718
Make sure you calibrate the MQ-7 sensor correctly as if not you would
receive some big measurement errors
Future projects tips
DHT11 isn't quite precise, in the sense that it can give random errors. A
DHT22 sensor would prove much more accurate, but it is also a little
bit more expensive than the DHT11
ESP8266 proved to be a little bit unstable during the development
phase. A ESP32 or a NodeMCU board might be better for a future
project
Some random photos taken during developing stage
SCHEMATICS
CODE
#include<stdlib.h>
#include "DHT.h"
//-----ESP8266 macros---------
#define SSID "------"//your network name
#define PASS "------"//your network password
#define IP "184.106.153.149" // thingspeak.com
#define Baud_Rate 9600 //Another common value is 115200
#define GREEN_LED 3 //optional LED's for debugging
#define RED_LED 4 //optional LED's for debugging
#define YELLOW_LED 5 //optional LED's for debugging
#define ESP_FOUND_LED 6 //optional LED's for debugging
#define DELAY_TIME 3000 //time in ms between posting data to
ThingSpeak
bool updated;
//----Relay/MQ-7 macros
#define RELAY 8
#define MQ7_ANALOG_IN_PIN 0
#define HEATING_LED 9
#define READING_LED 10
#define BUZZER 11
//-----connect to network---------
Serial.println("Checking if ESP8266 is online...");
connectionStart:
Serial.println("AT");
delay(5000);
if (Serial.find("OK")) {
digitalWrite(ESP_FOUND_LED, HIGH);
Serial.println("ESP8266 found <module online>...");
Serial.println("Trying to connect to network...");
//connect to your wifi netowork
bool connected = false;
do {
networkBlinkConnecting();
connected = connectWiFi();
Serial.println("Connection achived....");
digitalWrite(YELLOW_LED, HIGH); // indicate connection achived
} else {
Serial.println("ESP8266 not found...");
Error();
goto connectionStart;
}
}
if (heaterInHighPhase) {
// 5v phase of cycle. see if need to switch low yet
if (millis() > switchTimeMillis) {
Serial.println("Reading from sensors....");
turnHeaterLow();
}
blinkHeating();
}
else {
// 1.4v phase of cycle. see if need to switch high yet
if (millis() > switchTimeMillis) {
Serial.println("Heating the gas sensor....");
turnHeaterHigh();
}
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(f) || isnan(gasLevel)) {
networkBlinkError();
return;
}
else if (gasLevel >= 60) {
tone(BUZZER, 3000); // Send 1KHz sound signal...
}
else {
noTone(BUZZER); // Stop sound...
}
//if update succeeded light up green LED, else light up red LED
Serial.println(updated);
if (updated) {
networkBlinkSending();
} else {
networkBlinkError();
}
blinkReading();
}
}
//----network update function--------------
bool updateValues(String temp, String humid, String gasLevel) {
//connect
Serial.println(cmd);
delay(500);
if (Serial.find("Error")) {
return false;
}
if (Serial.find("OK")) {
//success! Your most recent values should be online.
return true;
} else {
return false;
}
}
//----network functions--------------
boolean connectWiFi() {
//set ESP8266 mode with AT commands
Serial.println("AT+CWMODE=1");
delay(2000);
//build connection command
String cmd = "AT+CWJAP=\"";
cmd += SSID;
cmd += "\",\"";
cmd += PASS;
cmd += "\"";
void Error() {
networkBlinkError();
Serial.println("Error");
}
//----MQ-7 functions--------------
void blinkHeating() {
digitalWrite(HEATING_LED, HIGH);
delay(200);
digitalWrite(HEATING_LED, LOW);
delay(200);
}
void blinkReading() {
digitalWrite(READING_LED, HIGH);
delay(GAS_LEVEL_READING_PERIOD_MILLIS / 2);
digitalWrite(READING_LED, LOW);
delay(GAS_LEVEL_READING_PERIOD_MILLIS / 2);
}
//--read from gas sensor---------
unsigned int readGasLevel() {
return analogRead(MQ7_ANALOG_IN_PIN);
}
//----network LEDs--------
void networkBlinkSending() {
digitalWrite(RED_LED, LOW);
digitalWrite(GREEN_LED, HIGH);
delay(500);
digitalWrite(GREEN_LED, LOW);
delay(500);
}
void networkBlinkError() {
digitalWrite(GREEN_LED, LOW);
digitalWrite(RED_LED, HIGH);
delay(200);
digitalWrite(RED_LED, LOW);
delay(200);
}
void networkBlinkConnecting() {
digitalWrite(YELLOW_LED, HIGH);
delay(200);
digitalWrite(YELLOW_LED, LOW);
delay(200);
}
void turnHeaterLow() {
// 1.4v phase
digitalWrite(RELAY, LOW);
heaterInHighPhase = false;
switchTimeMillis = millis() + MQ7_HEATER_1_4_V_TIME_MILLIS;
}
× 1
Buzzer
× 1
× 1
Step 2: Copy and paste the code in new sketch of Arduino IDE.
Step 3: Conect the led matrix, buzzer and potentiometer to Arduino.
SCHEMATICS
CODE
int row[] = {2, 7, A5, 5, 13, A4, 12, A2};
int col[] = {6, 11, 10, 3, A3, 4, 8, 9};
int joystick = A0; //es un simple potenciometro
int lastUpdate;
int puntos = 0;
int vidas = 10;
int speakerPin = A1;
int speed = 16;
bool updatedAsteroid = false, updatedPlayer = true;
void setup() {
// put your setup code here, to run once:
for (int i = 0; i < 8; i++)
{
pinMode(row[i], OUTPUT);
pinMode(col[i], OUTPUT);
digitalWrite(col[i], HIGH);
digitalWrite(row[i], LOW);
}
pinMode(speakerPin, OUTPUT);
initGame();
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
for(int i = 0; i < 2; i++)
{
clearScreen(); //limpia la matriz de leds
if(lastUpdate == 1) {
movePlayer();
}
if(lastUpdate == 0) {
asteroidFall();
//Serial.print("El asteroide cambia de posicion!!\n");
}
lastUpdate = Update(); //actualiza la matriz de leds segun movePlayer() y
asteroidFall()
delay(speed);
}
puntuacion(); //calcula la puntuacion y aumenta una vida por punto,
cuando el jugador se queda sin vidas se pasa a gameover() para reiniciar la
partida
if (asteroid.y == 8 || asteroid.y > 8) {
initasteroid(); //inizializa un nuevo asteroid cuando el anterior ya ha caido
}
}
void initGame() {
vidas = 10;
puntos = 0;
speed = 16;
initplayer();
initasteroid();
return;
}
void initplayer() {
jugador.x = 3;
jugador.y = 7;
digitalWrite(col[jugador.y], HIGH);
digitalWrite(row[jugador.x], LOW);
return;
}
void initasteroid() {
asteroid.x = random(0, 7);
asteroid.y = -1; //para que asteroidFall() comienze en 0 nada mas
ejecutarse
digitalWrite(col[asteroid.x], LOW);
digitalWrite(row[asteroid.y], HIGH);
return;
}
void movePlayer() {
int value = analogRead(joystick);
value = map(value, 0, 1023, 0, 7);
value = constrain(value, 0, 7);
//Serial.print("joystickX: ");
//Serial.print(jugador.x);
//Serial.print("\n");
if(value >= 0 && value <= 7) {
jugador.x = value;
}
return;
}
void asteroidFall() {
asteroid.y++;
//Serial.print("AsteroidY: ");
//Serial.print(asteroid.y);
//Serial.print("\n");
return;
}
void clearScreen() {
for (int led = 0; led < 8; led++)
{
digitalWrite(col[led], HIGH);
digitalWrite(row[led], LOW);
}
return;
}
int Update() {
if(updatedAsteroid == true && updatedPlayer == false) {
digitalWrite(col[jugador.x], LOW);
digitalWrite(row[jugador.y], HIGH);
updatedAsteroid = false;
updatedPlayer = true;
//Serial.print("Jugador Actualizado!!\n");
return 0; //retorna que se ha actualizado el jugador
} else {
digitalWrite(col[asteroid.x], LOW);
digitalWrite(row[asteroid.y], HIGH);
updatedAsteroid = true;
updatedPlayer = false;
//Serial.print("Asteroid Actualizado!!\n");
return 1; //retorna que se ha actualizado el asteroide
}
}
void puntuacion() {
if(asteroid.y == jugador.y && asteroid.x == jugador.x) {
digitalWrite(speakerPin, HIGH);
puntos++;
delay(100);
digitalWrite(speakerPin, LOW);
vidas += 2;
if(speed > 9 && puntos >= 4) {
speed--; //aumenta la velocidad del juego (nivel nuevo)
puntos = 0; //reiniciamos la puntucion al pasar al siguiente nivel
}
Serial.print("Puntos: ");
Serial.print(puntos);
Serial.print("\n");
}
if(asteroid.y == jugador.y && asteroid.x != jugador.x) {
vidas--;
Serial.print("Vidas: ");
Serial.print(vidas);
Serial.print("\n");
if(vidas == 0) {
gameover();
}
}
return;
}
void gameover() {
//animacion cuando pierdes la partida
for(int y = 0; y < 5; y++)
{
//Serial.print("Animacion: ");
//Serial.print(y);
//Serial.print("\n");
//bucle que apaga todos los leds de la matriz
digitalWrite(speakerPin, HIGH);
for(int i = 0; i < 8; i++)
{
digitalWrite(col[i], HIGH);
digitalWrite(row[i], LOW);
}
delay(500);
//bucle que enciende todos los leds de la matriz
for(int i = 0; i < 8; i++)
{
digitalWrite(col[i], LOW);
digitalWrite(row[i], HIGH);
}
digitalWrite(speakerPin, LOW);
delay(500);
}
delay(1000);
initGame(); //inicializa una nueva partida
return;
}
× 1
× 1
Temperature Sensor
× 1
× 1
9V battery (generic)
× 1
NXP Hexiwear
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
Connect the sensors and bluetooth module using jumper wires to the
Arduino Uno.
void setup()
{
void loop()
{
///// Read pH Regularly //////
static unsigned long samplingTime = millis();
static unsigned long printTime = millis();
static float pHValue,voltage;
if(millis()-samplingTime > samplingInterval)
{
pHArray[pHArrayIndex++]=analogRead(SensorPin);
if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
pHValue = 3.5*voltage+Offset;
samplingTime=millis();
}
if(Serial.available()>0){
String message = readSerialMessage();
if(find(message,"debugdebugBluetooth:")){
String result =
sendTobluetooth(message.substring(13,message.length()),responseTime,DEBUG);
if(find(result,"OK"))
sendData("\nOK");
else
sendData("\nEr");
}
}
if(bluetoothSerial.available()>0){
if(find(message,"debugBluetooth:")){
String result =
sendTobluetooth(message.substring(8,message.length()),responseTime,DEBUG);
if(find(result,"OK"))
sendData("\n"+result);
else
sendData("\nATCE1001"); //At command ERROR CODE for
Failed Executing statement
}else
if(find(message,"getT")){
float temp = 0;
sensors.requestTemperatures(); // Send the command to get
temperatures
temp = sensors.getTempCByIndex(0);
sensors.requestTemperatures(); // Send the command to get
temperatures
temp = sensors.getTempCByIndex(0);
if(temp==85)
sendData("\nTE1001"); //Temperature ERROR CODE for
INITIALIZE
else if(temp==0 || temp==-127)
sendData("\nTE1002"); //Temperature ERROR CODE for NOT
CONNECTED
else{
String temperature = "";
temperature+=temp+tempOffSet;
sendData("\n"+temperature);
}
}else
if(find(message,"getP")){
//sending ph level:
if(pHValue==0){
sendData("\nPE1001"); //pH ERROR CODE for NOT OPEN
}else{
String ph = "";
ph+=pHValue;
sendData("\n"+ph);
}
}else if(find(message,"pHOff")){
//sending ph level:
digitalWrite(12,0);
}else if(find(message,"pHOn")){
//sending ph level:
digitalWrite(12,1);
}
else{
sendData("\nErrRead"); //Command ERROR CODE for
UNABLE TO READ
}
}
delay(responseTime);
}
/*
* Name: sendData
* Description: Function used to send string to tcp client using cipsend
* Params:
* Returns: void
*/
void sendData(String str){
String len="";
len+=str.length();
sendTobluetooth("AT+CIPSEND=0,"+len,responseTime,DEBUG);
delay(100);
sendTobluetooth(str,responseTime,DEBUG);
delay(100);
sendTobluetooth("AT+CIPCLOSE=5",responseTime,DEBUG);
}
/*
* Name: find
* Description: Function used to match two string
* Params:
* Returns: true if match else false
*/
boolean find(String string, String value){
if(string.indexOf(value)>=0)
return true;
return false;
}
/*
* Name: readSerialMessage
* Description: Function used to read data from Arduino Serial.
* Params:
* Returns: The response from the Arduino (if there is a reponse)
*/
String readSerialMessage(){
char value[100];
int index_count =0;
while(Serial.available()>0){
value[index_count]=Serial.read();
index_count++;
value[index_count] = '\0'; // Null terminate the string
}
String str(value);
str.trim();
return str;
}
/*
* Name: readbluetoothSerialMessage
* Description: Function used to read data from debugBluetooth Serial.
* Params:
* Returns: The response from the debugBluetooth (if there is a reponse)
*/
String readbluetoothSerialMessage(){
char value[100];
int index_count =0;
while(bluetoothSerial.available()>0){
value[index_count]=bluetoothSerial.read();
index_count++;
value[index_count] = '\0'; // Null terminate the string
}
String str(value);
str.trim();
return str;
}
/*
* Name: sendTobluetooth
* Description: Function used to send data to debugBluetooth.
* Params: command - the data/command to send; timeout - the time to
wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the debugBluetooth (if there is a reponse)
*/
String sendTobluetooth(String command, const int timeout, boolean
debug){
String response = "";
bluetoothSerial.println(command); // send the read character to the
debugBluetooth
long int time = millis();
while( (time+timeout) > millis())
{
while(bluetoothSerial.available())
{
// The esp has data so display its output to the serial window
char c = bluetoothSerial.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.println(response);
}
return response;
}
/*
* Name: sendTobluetooth
* Description: Function used to send data to debugBluetooth.
* Params: command - the data/command to send; timeout - the time to
wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the debugBluetooth (if there is a reponse)
*/
String sendToUno(String command, const int timeout, boolean debug){
String response = "";
Serial.println(command); // send the read character to the debugBluetooth
long int time = millis();
while( (time+timeout) > millis())
{
while(Serial.available())
{
// The esp has data so display its output to the serial window
char c = Serial.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.println(response);
}
return response;
}
Arduino Nano R3
× 1
Resistor 1k ohm
× 1
5 mm LED: Green
× 1
Heat Gun
APPS AND ONLINE SERVICES
Arduino IDE
I have significantly modified the code from the link above to use one
LED with blink codes rather than the three LEDs that were used in the
original development. I've also cleaned up the calibration instructions
to hopefully make this completely understandable for a layman. You
can simply assemble the circuit, upload my sketch to your Arduino, and
follow the calibration requirements to have a functional and reliable
water level monitor. Minimal programming knowledge is needed to
modify my sketch to suit your needs.
**NOTE - I have only been using this for a few days, and do not know
how well the sensor will hold up. There is potential for corrosion, and
it's possible that a piece of debris (wet pine needle) could short two
traces and give a false reading. I strongly recommend that you visually
confirm your water level until you are confident that the sensor will
continue to work as desired. I will continue to verify sensor operation
every few days, but this helps to avoid the necessity to move gifts and
tree skirt every day to check the water level.
About the sensor:
The sensor works by using a series of five exposed traces which are
connected to system ground. Interlaced between every two ground
trace is a sense trace, five ground traces and five sense traces in total.
The sense traces are connected to a 1 Megaohm pull-up resistor. The
sense traces are pulled high until a drop or plane of water shorts the
sense trace to ground. This sensor will theoretically output an analog
signal between 0-1024, but with the length of traces on this PCB I
found a usable range between 480 and ~710. The sensor is not designed
to be fully submersed, be mindful to install it so that only the exposed
traces on the PCB will be exposed to contact with water. Output
voltage of the sensor is 0 - 4.2 V, so this could be used as a digital input
if only low/high indication is required.
The analog output values correspond to the following distance from
bottom of the sensor (approximate):
480 = 0 mm
530 = 5 mm
615 = 10 mm
660 = 15 mm
680 = 20 mm
690 = 25 mm
700 = 30 mm
705 = 35 mm
710 = 40 mm
The sensor resolution decreases as the the water level increases.
== Installation
1. Upload the sketch to your Arduino.
2. Assemble the circuit using the schematic included with this project.
**LED: The LED resistor must be installed between the circuit ground
and LED. If your LED has one leg that is longer than the other, the
longer leg needs to be connected to the supply voltage (D2 of Arduino).
*Note: I used ~2.5 ft wire length for the sensor and 2 ft wire length for
the LED. This allowed me to place the Arduino away from the water,
and route the LED to the end of a tree branch for visibility.
3. Follow the calibration instructions below (also included in the
sketch):
**************************** Calibration/Setup
****************************
a) Connect Arduino to IDE and open serial monitor.
b) Insert depth sensor into water to a depth that you consider to be the
minimum amount needed to trigger the full indicator. Note the value
indicated in the serial monitor for use as the FULL level.
* Any value >= this will trigger the corresponding FULL blink code.
c) Repeat step 2 to determine the value you will assign to the LOW
value.
* Any value above this but below the FULL value will trigger the
corresponding INTERMEDIATE blink code.
* Any value below this value will trigger the corresponding LOW blink
code.
d) Plug the values determined from steps 2 and 3 in as the const int
FULL and LOW values in the sketch.
e) Upload the sketch with the updated values and your sensor is now
calibrated.
4. Place your Arduino is some type of enclosure to prevent damage
from water, moving parts, or shorts.
5. Install the system into your application.
=== Folder Structure
WaterLevelMontior_SingleLED => Arduino sketch folder
├── WaterLevelMonitor_SingleLED.ino => main Arduino file
├── WaterLevelMonitor.png => an image of the required schematics
└── ReadMe.adoc => this file
SCHEMATICS
CODE
****************************** Calibration/Setup
******************************
1) Upload sketch to Arduino and open serial monitor.
2) Insert depth sensor into water to a depth that you consider to be the
minimum amount needed
to trigger the full indicator. Note the value indicated in the serial monitor
for use as the FULL level.
* Any value >= this will trigger the corresponding FULL indicator.
3) Repeat step 2 to determine the value you will assign to the LOW value.
* Any value above this but below the FULL value will trigger the
corresponding INTERMEDIATE
blink code.
* Any value below this value will trigger the corresponding LOW blink
code.
4) Plug the values determined from steps 2 and 3 in as the const int FULL
and LOW values
in the sketch.
5) Upload the sketch with the updated values and your sensor is now
calibrated.
*/
/* The following line sets the LED pin to the corresponding digital pin of
the
Arduino. You can set these to any digital pin as needed
*/
void setup()
{
Serial.begin(9600); // Begin serial communication to obtain sensor values
during calibration.
pinMode(whiteLED, OUTPUT); // Set LED pin to OUTPUT mode.
}
void loop()
{
int value = analogRead(depthSensor); // Read the sensor values.
if(((lastValue >= value) && ((lastValue - value) > 10)) || (lastValue = 10))
/* If the delta
between last and current value is > 10, display the current value. */
{
// Displays depth sensor value to serial port.
sprintf(printBuffer, "ADC%d level is %d\n", depthSensor, value);
Serial.print(printBuffer);
Serial.println();
//Serial.println(value);
//Serial.println();
// Set last value to current value for next loop.
lastValue - value;
}
if(value >= full)
{
// FULL
for(int x = 0; x < 3; x++){
digitalWrite(whiteLED, HIGH);
delay(800);
digitalWrite(whiteLED, LOW);
delay(800);
}
}
else if((value < full) && (value >= low))
{
// INTERMEDIATE
for(int x = 0; x < 2; x++){
digitalWrite(whiteLED, HIGH);
delay(1000);
}
}
else
{
//LOW
for(int x = 0; x < 4; x++){
digitalWrite(whiteLED, HIGH);
delay(100);
digitalWrite(whiteLED, LOW);
delay(100);
}
}
delay(3000); // Read current sensor value every three seconds.
}
/*
=== License
This project utilizes common electronic theory and C/C++ programming
language. I am not claiming to hold
a copyright or own any intellectual property related to the documents
included in this project. This
sketch, the associated ReadMe.adoc, and system schematic may be
modified or distributed freely. This
project is released under a Public Domain License.
=== DISCLAIMER
This SOFTWARE PRODUCT is provided by THE PROVIDER "as is"
and "with all faults." THE PROVIDER makes no
representations or warranties of any kind concerning the safety, suitability,
lack of viruses,
inaccuracies, typographical errors, or other harmful components of this
SOFTWARE PRODUCT. There are
inherent dangers in the use of any software, and you are solely responsible
for determining whether this
SOFTWARE PRODUCT is compatible with your equipment and other
software installed on your equipment. You
are also solely responsible for the protection of your equipment and
backup of your data, and THE
PROVIDER will not be liable for any damages you may suffer in
connection with using, modifying, or
distributing this SOFTWARE PRODUCT.
*/
70) Arduino Obstacles Avoiding Robot with Servo Motor
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
× 1
SparkFun Ultrasonic Sensor - HC-
SR04 × 1
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
The instructions paper will come with the package that you buy from
online or the shops. Or else you can view "how to build" in the
youtube.
Step 2:
Before solder the jumper wires on your both motor, I would
recommend to test every components for make sure they all are
working well, example: Both DC motors, Arduino board, Motor Shield,
Servo motor and Ultrasonic sensor. Then we will start solder the red
and black wire on both motors, example picture below:
Step 3:
Come to our battery chassis and switch part. We only need to cut half
of the black wire from the battery chassis and solder 1 wire side at 1
hole, another black wire will solder at another hole. Our switch is
ready!
Step 4:
We will need to stack Arduino board and Motor Shield board, Motor
Shield will stack on Arduino board. Example below:
Step 5:
We will move on to the Motor Shield board. This shield provides power
to the motors and the servo motor, the motors need a lot of current, and
this shield can provide up to 600mA of current to each motor. We need
to solder/fixed the DC motors wires at the Motor shield board. If the
your DC motor wires are long enough to reach the Motor Shield will be
great, if not you might need to use external jumper wires(No matter is
Male/Female jumper wire), cut off the jumper wire head and make sure
inside the copper line shows up. (You will need to cut jumper wire
rubber to make the copper wire appear). And you need to solder the
external wires to the DC motor wires. Example:
Then connect the left motor wire to M1 connector of the motor shield.
Right motor wire will coneect to M3 connector from the Motor shield
board. Example:
Pictures by Darwin
Step 6:
Then we will need to connect the battery switch wires both red and
black wire to the Motor shield board.
For Battery switch wire (Pictures by Darwin)
After that, we will need to ready Male and Female jumper wires for
solder them to 5V, GND, Analog Pin 4 and Analog Pin 5. Before that,
we will need to find same colors of female and male jumper wires and
cut them into half. Why must be same color? First is easy for us to
recognize which wire are for which part. Second, white Male jumper
wire will solder with white Female jumper wire which connect to 5V.
Black color Male jumper wire will solder with female jumper wire and
Male jumper wire will solder to GND. Orange color Male jumper wire
will solder with orange Female jumper wire, Orange male jumper wire
will solder at Analog Pin 5. Lastly but not least, brown male jumper
wire will solder with female brown jumper wire, then brown color male
jumper wire will solder to Analog Pin 4. Example:
Pictures by Darwin
Step 7:
You are able to use double sided tape or hot glue gun for attach the
both shield on the robot chassis.
Step 8: Come to Ultrasonic Sensor part
From the Female & Male jumper wires that we solder just now, White
jumper wire(5V)(Female site jumper wire) will connect to Ultrasonic
Sensor VCC pin. Black Jumper wire(GND)(Female site jumper wire)
will connect to GND pin. Brown jumper wire(Analog Pin 4)(Female
site jumper wire) will connect to Echo pin. Orange color jumper
wire(Analog Pin 5)(Female site jumper wire) will connect to TRIG pin.
Step 9:
Lastly, For the Servo motor will connect to servo_2 slot. Note* (There
are few types of servo motor out there. you might need to find it online
for how they plug to servo_2 slot). Below is for my own version of
servo slot.
SCHEMATICS
CODE
#include <AFMotor.h>
#include <Servo.h>
#include <NewPing.h>
#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE_POSSIBLE 1000
#define MAX_SPEED 150 //
#define MOTORS_CALIBRATION_OFFSET 3
#define COLL_DIST 20
#define TURN_DIST COLL_DIST+10
NewPing sonar(TRIG_PIN, ECHO_PIN,
MAX_DISTANCE_POSSIBLE);
int pos = 0;
int maxDist = 0;
int maxAngle = 0;
int maxRight = 0;
int maxLeft = 0;
int maxFront = 0;
int course = 0;
int curDist = 0;
String motorSet = "";
int speedSet = 0;
void setup() {
neckControllerServoMotor.attach(10);
neckControllerServoMotor.write(90);
delay(2000);
checkPath();
motorSet = "FORWARD";
neckControllerServoMotor.write(90);
moveForward();
}
void loop() {
checkForward();
checkPath();
}
void checkPath() {
int curLeft = 0;
int curFront = 0;
int curRight = 0;
int curDist = 0;
neckControllerServoMotor.write(144);
delay(120);
for(pos = 144; pos >= 36; pos-=18)
{
neckControllerServoMotor.write(pos);
delay(90);
checkForward();
curDist = readPing();
if (curDist < COLL_DIST) {
checkCourse();
break;
}
if (curDist < TURN_DIST) {
changePath();
}
if (curDist > curDist) {maxAngle = pos;}
if (pos > 90 && curDist > curLeft) { curLeft = curDist;}
if (pos == 90 && curDist > curFront) {curFront = curDist;}
if (pos < 90 && curDist > curRight) {curRight = curDist;}
}
maxLeft = curLeft;
maxRight = curRight;
maxFront = curFront;
}
void setCourse() {
if (maxAngle < 90) {turnRight();}
if (maxAngle > 90) {turnLeft();}
maxLeft = 0;
maxRight = 0;
maxFront = 0;
}
void checkCourse() {
moveBackward();
delay(500);
moveStop();
setCourse();
}
void changePath() {
if (pos < 90) {lookLeft();}
if (pos > 90) {lookRight();}
}
int readPing() {
delay(70);
unsigned int uS = sonar.ping();
int cm = uS/US_ROUNDTRIP_CM;
return cm;
}
void moveForward() {
motorSet = "FORWARD";
leftMotor.run(FORWARD);
rightMotor.run(FORWARD);
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
{
leftMotor.setSpeed(speedSet+MOTORS_CALIBRATION_OFFSET);
rightMotor.setSpeed(speedSet);
delay(5);
}
}
void moveBackward() {
motorSet = "BACKWARD";
leftMotor.run(BACKWARD);
rightMotor.run(BACKWARD);
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
{
leftMotor.setSpeed(speedSet+MOTORS_CALIBRATION_OFFSET);
rightMotor.setSpeed(speedSet);
delay(5);
}
}
void turnRight() {
motorSet = "RIGHT";
leftMotor.run(FORWARD);
rightMotor.run(BACKWARD);
delay(400);
motorSet = "FORWARD";
leftMotor.run(FORWARD);
rightMotor.run(FORWARD);
}
void turnLeft() {
motorSet = "LEFT";
leftMotor.run(BACKWARD);
rightMotor.run(FORWARD);
delay(400);
motorSet = "FORWARD";
leftMotor.run(FORWARD);
rightMotor.run(FORWARD);
}
× 1
Breadboard (generic)
× 1
Jumper wires (generic)
× 27
Buzzer
× 1
× 1
× 2
APPS AND ONLINE SERVICES
Arduino IDE
CODE
#include <LiquidCrystal.h>
#define BUZZER 11
uint8_t hpos = 0;
void send_char(const char& c) {
// Send the character to the LCD
lcd.setCursor(hpos++, 0);
lcd.print(c);
send_char(number);
send_char(character);
void print_whitespace() {
send_char(' ');
delay(3 * SMALLER_DELAY);
}
delay(2 * SMALLER_DELAY);
}
void reset_LCD() {
hpos = 0;
lcd.clear();
lcd.noCursor();
lcd.setCursor(0, 0);
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
lcd.begin(16, 2);
reset_LCD();
pinMode(BUZZER, OUTPUT);
}
char* readStr() {
uint8_t idx = 0;
char* str = (char*)malloc(128 * sizeof(char));
return str;
}
void serialEvent() {
while (Serial.available()) {
char* string;
Serial.setTimeout(-1);
string = readStr();
Serial.print("Received: ");
Serial.println(string);
char substr[16];
for (uint8_t c = 0 ; c < 128 && string[c] != '\0' && string[c] != '\r' && string[c] != '\n' ; c
+= 16) {
for (uint8_t offset = 0 ; offset < 15 ; offset++) {
if (string[c + offset] != '\0' && string[c + offset] != '\r' && string[c + offset] != '\n') {
substr[offset] = string[c + offset];
} else {
substr[offset] = '\0';
}
}
reset_LCD();
print_string(substr);
}
free((void*)string);
}
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 0);
}
void loop() {
}
Arduino Nano R3
× 1
LED (generic)
× 17
Hall Effect Sensor
× 1
× 17
DC motor (generic)
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
CODE
// hobbyprojects
// ArduinoNanoPropellerLEDAnalogClock20190403A
int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int LED4 = 5;
int LED5 = 6;
int LED6 = 7;
int LED7 = 8;
int LED8 = 9;
int LED9 = 10;
int LED10 = 11;
int LED11 = 12;
int LED12 = A1;
int LED13 = A2;
int LED14 = A3;
int LED15 = A4;
int LED16 = A5;
int val;
void setup()
{
pinMode(LED1,OUTPUT);
pinMode(LED2,OUTPUT);
pinMode(LED3,OUTPUT);
pinMode(LED4,OUTPUT);
pinMode(LED5,OUTPUT);
pinMode(LED6,OUTPUT);
pinMode(LED7,OUTPUT);
pinMode(LED8,OUTPUT);
pinMode(LED9,OUTPUT);
pinMode(LED10,OUTPUT);
pinMode(LED11,OUTPUT);
pinMode(LED12,OUTPUT);
pinMode(LED13,OUTPUT);
pinMode(LED14,OUTPUT);
pinMode(LED15,OUTPUT);
pinMode(LED16,OUTPUT);
pinMode(sensorPin,INPUT_PULLUP);
if(hours == 12)
hours = 0;
}
void loop()
{
val = digitalRead(sensorPin);
propeller_posn=30;
n=0;
drawMinuteMarker();
if ((propeller_posn==0) || (propeller_posn==5) || (propeller_posn==10) ||
(propeller_posn==15) || (propeller_posn==20) || (propeller_posn==25) ||
(propeller_posn==30) || (propeller_posn==35) || (propeller_posn==40) ||
(propeller_posn==45) || (propeller_posn==50) || (propeller_posn==55))
drawHourMarker();
if(propeller_posn == minutes)
drawMinutesHand();
if(propeller_posn == seconds)
drawSecondsHand();
delayMicroseconds(140); // for LED pixel width (change the value according to motor
speed. Increase for low speed, decrease for high speed motor)
displayClear();
drawInner_Circle();
delayMicroseconds(600); // for the gap between LED pixels/minutes markers (change the
value according to motor speed. Increase for low speed, decrease for high speed motor)
n++;
propeller_posn++;
if(propeller_posn == 60)
propeller_posn=0;
}
val = digitalRead(sensorPin);
//=========================
void displayClear()
{
digitalWrite(LED1,LOW);
digitalWrite(LED2,LOW);
digitalWrite(LED3,LOW);
digitalWrite(LED4,LOW);
digitalWrite(LED5,LOW);
digitalWrite(LED6,LOW);
digitalWrite(LED7,LOW);
digitalWrite(LED8,LOW);
digitalWrite(LED9,LOW);
digitalWrite(LED10,LOW);
digitalWrite(LED11,LOW);
digitalWrite(LED12,LOW);
digitalWrite(LED13,LOW);
digitalWrite(LED14,LOW);
digitalWrite(LED15,LOW);
digitalWrite(LED16,LOW);
}
void drawMinuteMarker()
{
digitalWrite(LED16,HIGH);
}
void drawHourMarker()
{
digitalWrite(LED15,HIGH);
digitalWrite(LED14,HIGH);
}
void drawQuarterMarker()
{
digitalWrite(LED13,HIGH);
digitalWrite(LED12,HIGH);
}
void drawHoursHand()
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,HIGH);
digitalWrite(LED3,HIGH);
digitalWrite(LED4,HIGH);
digitalWrite(LED5,HIGH);
digitalWrite(LED6,HIGH);
digitalWrite(LED7,HIGH);
}
void drawMinutesHand()
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,HIGH);
digitalWrite(LED3,HIGH);
digitalWrite(LED4,HIGH);
digitalWrite(LED5,HIGH);
digitalWrite(LED6,HIGH);
digitalWrite(LED7,HIGH);
digitalWrite(LED8,HIGH);
digitalWrite(LED9,HIGH);
}
void drawSecondsHand()
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,HIGH);
digitalWrite(LED3,HIGH);
digitalWrite(LED4,HIGH);
digitalWrite(LED5,HIGH);
digitalWrite(LED6,HIGH);
digitalWrite(LED7,HIGH);
digitalWrite(LED8,HIGH);
digitalWrite(LED9,HIGH);
digitalWrite(LED10,HIGH);
digitalWrite(LED11,HIGH);
}
void drawInner_Circle()
{
digitalWrite(LED1,HIGH);
delayMicroseconds(30);
digitalWrite(LED1,LOW);
}
× 1
Breadboard (generic)
× 1
× 1
9V Battery Clip
× 1
RobotGeek Light Sensor
We used a photo resistor, also
know as a LDR ( Light Dependent
× 1
Resistor ), i would recommend
this as its cheaper and serves the
purpose.
9V battery (generic)
× 1
NECESSARY TOOLS AND MACHINES
Laser cutter (generic)
circuito.io
hot glued
smooth surface sticking out
Time to put it on
Simply put in the whole device
make sure the LDR sticks out
SCHEMATICS
CODE
#include <Servo.h>
Servo servo1;
Servo servo2;
int pos1 = 0;
int pos2 = 0;
void play(){
for (pos1 = 0; pos1 <= 180; pos1 += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos1 = 180; pos1 >= 0; pos1 -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
while(true);
}
void next_clip(){
for (pos2 = 0; pos2 <= 180; pos2 += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos2 = 180; pos2 >= 0; pos2 -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
while(true);
}
void setup() {
// put your setup code here, to run once:
servo1.attach(7);
servo2.attach(8);
Serial.begin(9600); //for debugging only
void loop() {
// put your main code here, to run repeatedly:
sensor_value = analogRead(ldr);
}
//once the victim is scared and tries to turn on the lights. play next clip
else if(sensor_value > thresh && state == true){
next_clip();
play();
state = false;
}
//do nothing
}
× 1
Optocoupler PC817
× 1
Transistor BC 547
× 1
Relay 5V DC
× 1
5 mm LED: Red
A second LED is used to show the
× 1
relay contact ON OFF
× 2
Breadboard (generic)
× 1
× 1
//Vibration Sensor Module (Code)Arduino with relay and external 5V power source.
int vib_pin=2;
int led_pin=13;
}
else
digitalWrite(led_pin,HIGH);
}
75) Arduino Tic Tac Toe Board Game with Robotic Arm
COMPONENTS AND SUPPLIES
4 x 4 Matrix Array 16 Key Membrane Switch
Keypad Keyboard for Arduino × 1
SCHEMATICS
Tic-tac-toe schematic
Tic-Tac-toe Breadboard
CODE
//
//BobN2Tech 03-22-18 add Xarm code for robotic control and Keypad input code
//Thanks to https://github.com/klauscam/ArduinoTicTacToe for the tic-tac-toe algorithm
//this code requires mega2560 which uses serial port 3 (serial3) to control the Lewansoul
xarm
//note: actiongroups 0-8 must be downloaded to the xarm controller prior
//to using this program. Action group numbers 0 to 8 represent the board positions that
//will be placed the moved piece. Initially has to be done manually (train the x-arm) to
determine each board position
//where the xarm will place the computer move piece.
//action group 100 is preloaed for the initial position of the arm (recommend standing up)
//action group 9 is for moving the arm as computer winning game - does some fancy
gyration
//optional action group 10 is for a draw - does some gyration
//optional action group 11 is for a losing - does some humble gesture.
//action group 12 is places arm into position where it will get the "O" pieces
//The computer will never lose!
//
int difficulty=8;
//xarm
#include <LobotServoController.h>
//Not using software serial
//#define rxPin 2 //software serial
//#define txPin 3 //software serial
const int speed = 100; //percent of action speed set in group. 100 = 100% = same speed as
programmed, 50 = 1/2 speed, 200 = twice speed
int lastComputerMove = -1;
bool xarmConnected = false;
//keypad
#include <Keypad.h>
void setup(){
Serial.begin(9600);
while(!Serial);
digitalWrite(13,HIGH);
Serial3.begin(9600);
while(!Serial3);
//xarm code
//
int moveNo = 0;
pinMode(13,OUTPUT);
// mySerial.begin(9600);
// while(!mySerial);
// digitalWrite(13,HIGH);
if (xarmConnected)
{
}
//optional
// myse.setActionGroupSpeed(100,speed); //Set the running speed of No.100 action group
at 1 sec
// delay(1000);
//put arm back into stand up as initial position (assume group 100)
// myse.runActionGroup(100,1);
// delay(2000);
xarmMove (12); //put arm into position for getting the pieces
delay (5000);
//
}
}
char displayChar(int c) {
switch(c) {
case -1:
return 'X';
case 0:
return ' ';
case 1:
return 'O';
}
}
if(board[i] == 0) {
board[i] = player;
int thisScore=0;
if (depth<difficulty){
thisScore = -minimax(board, player*-1,depth+1);
}
}
//choose the worst move for opponent
board[i] = 0;
}
}
if(move == -1) return 0;
return score;
do {
// Get value from custom keypad but start with keypad 1 = board 0;
Serial.println("\nInput move ([1..9]): ");
while ((customKey = customKeypad.getKey())== NO_KEY)
{delay(100);}
Serial.println(customKey);
//convert to string so can convert char to integer -
smove = (String)customKey;
bmove = smove.toInt()-1; //use keypad so will start with numbers 1-9 to correspond to
physical board layout
move = bmove;
//
Serial.println("\n");
} while ((move >= 9 || move < 0) || board[move] != 0);
board[move] = -1;
}
void loop(){
int board[9] = {0,0,0,0,0,0,0,0,0};
//x-arm Play only 1, playing 2 does not work correctly
// Serial.println("Would you like to play X(1) or O(2)?");
Serial.println("Press 1 to start playing - you are 'X' and Computer is 'O'");
/* get input from computer keyboard
while(Serial.available()==0)
{
delay(100);
}
int player=Serial.parseInt();
Serial.println(player);
*/
Serial.println(customKey);
//convert to string so can convert char to integer
s = (String)customKey;
player = s.toInt();
//
unsigned turn;
for(turn = 0; turn < 9 && win(board) == 0; ++turn) {
if((turn+player) % 2 == 0)
{
computerMove(board);
× 1
MSGEQ7
× 1
Capacitor 33pF
× 1
Capacitor 100 nF
× 2
Capacitor 10 nF
× 1
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
void setup()
{
Serial.begin(9600);
pinMode(strobePin, OUTPUT); // Define our pin modes
pinMode(resetPin, OUTPUT);
pinMode(outPin, INPUT);
pinMode(3,OUTPUT);
digitalWrite(resetPin, LOW); // Create an initial state for our pins
digitalWrite(strobePin, LOW);
delay(1);
digitalWrite(resetPin, HIGH); // Reset the MSGEQ7 as per the datasheet timing diagram
delay(1);
digitalWrite(resetPin, LOW);
digitalWrite(strobePin, HIGH);
delay(1);
pixels.begin(); // enables Adafruit Neopixels
pixels.show(); // reset Pixels
for (int i = 0; i < 70; i++)
{
int ii = i-5; //snake effect at the start
pixels.setPixelColor(i, gr);
pixels.setPixelColor(ii, aus);
pixels.show();
delay(20);
}
}
void LEDaus1(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
for (int i=a; i <=k; i++)
{
pixels.setPixelColor(i, aus);
pixels.show();
}
}
void LEDaus2(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
for (int i=a; i >=k; i--)
{
pixels.setPixelColor(i, aus);
pixels.show();
}
}
void LED0(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k, uint32_t gr)
{
pixels.setPixelColor(a, gr);
for (int i=b; i <= k; i++) pixels.setPixelColor(i, aus);
}
void LED1(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
for (int i=k; i <= c; i++) pixels.setPixelColor(i, aus);
}
void LED2(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
for (int i=d; i <= k; i++) pixels.setPixelColor(i, aus);
}
void LED3(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
pixels.setPixelColor(d, gbl);
for (int i=k; i <= e; i++) pixels.setPixelColor(i, aus);
}
void LED4(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
pixels.setPixelColor(d, gbl);
pixels.setPixelColor(e, bl);
for (int i=f; i <= k; i++) pixels.setPixelColor(i, aus);
}
void LED5(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
pixels.setPixelColor(d, gbl);
pixels.setPixelColor(e, bl);
pixels.setPixelColor(f, blr);
for (int i=k; i <= g; i++) pixels.setPixelColor(i, aus);
}
void LED6(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
pixels.setPixelColor(d, gbl);
pixels.setPixelColor(e, bl);
pixels.setPixelColor(f, blr);
pixels.setPixelColor(g, blro);
for (int i=h; i <= k; i++) pixels.setPixelColor(i, aus);
}
void LED7(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
pixels.setPixelColor(d, gbl);
pixels.setPixelColor(e, bl);
pixels.setPixelColor(f, blr);
pixels.setPixelColor(g, blro);
pixels.setPixelColor(h, bro);
for (int i=k; i <= j; i++) pixels.setPixelColor(i, aus);
}
void LED8(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
pixels.setPixelColor(d, gbl);
pixels.setPixelColor(e, bl);
pixels.setPixelColor(f, blr);
pixels.setPixelColor(g, blro);
pixels.setPixelColor(h, bro);
pixels.setPixelColor(j, ro);
pixels.setPixelColor(k, aus);
}
void LED9(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
pixels.setPixelColor(a, gr);
pixels.setPixelColor(b, grb);
pixels.setPixelColor(c, grbl);
pixels.setPixelColor(d, gbl);
pixels.setPixelColor(e, bl);
pixels.setPixelColor(f, blr);
pixels.setPixelColor(g, blro);
pixels.setPixelColor(h, bro);
pixels.setPixelColor(j, ro);
pixels.setPixelColor(k, rog);
}
void abfolge(int a,int b,int c,int d,int e,int f,int g,int h,int j,int k)
{
switch (l)
{
case 93 ... 104:/*<---------------------------------------first LED area-------------------------------
-------------------------*/
LED0(a,b,c,d,e,f,g,h,j,k,gr);
break;
case 105 ... 139:/*<---------------------------------------second LED area--------------------------
----------------------------*/
LED1(a,b,c,d,e,f,g,h,j,k);
break;
case 140 ... 164:/*<---------------------------------------third LED area-----------------------------
--------------------------*/
LED2(a,b,c,d,e,f,g,h,j,k);
break;
case 165 ... 199:/*<---------------------------------------fourth LED area---------------------------
---------------------------*/
LED3(a,b,c,d,e,f,g,h,j,k);
break;
case 200 ... 234:/*<---------------------------------------fith LED area------------------------------
--------------------------*/
LED4(a,b,c,d,e,f,g,h,j,k);
break;
case 235 ... 269:/*<---------------------------------------sixth LED area-----------------------------
--------------------------*/
LED5(a,b,c,d,e,f,g,h,j,k);
break;
case 270 ... 304:/*<---------------------------------------seventh LED area--------------------------
---------------------------*/
LED6(a,b,c,d,e,f,g,h,j,k);
break;
case 305 ... 339:/*<---------------------------------------eighth LED area---------------------------
---------------------------*/
LED7(a,b,c,d,e,f,g,h,j,k);
break;
case 340 ... 374:/*<---------------------------------------nineth LED area---------------------------
---------------------------*/
LED8(a,b,c,d,e,f,g,h,j,k);
break;
case 375 ... 1000:/*<---------------------------------------tenth LED area---------------------------
---------------------------*/
LED9(a,b,c,d,e,f,g,h,j,k);
break;
}
}
void loop()
{
// Cycle through each frequency band by pulsing the strobe.
for (int i = 0; i < 7; i++)
{
digitalWrite (strobePin, LOW);
delayMicroseconds (100); // Delay necessary due to timing diagram
level[i] = analogRead (outPin);
digitalWrite (strobePin, HIGH);
delayMicroseconds (100); // Delay necessary due to timing diagram
}
/*-----------------------------------------------------------Band1(For the first LED stripe)----------
-----------------------------------------------------*/
// allocation for the Numbers of LEDs
l = level [0];
abfolge(0,1,2,3,4,5,6,7,8,9);
if (l < 92) LEDaus1(0,1,2,3,4,5,6,7,8,9);
/*-----------------------------------------------------------Band2(For the second LED stripe)-------
--------------------------------------------------------*/
// allocation for the Numbers of LEDs
l = level [1];
abfolge(19,18,17,16,15,14,13,12,11,10);
if (l < 92) LEDaus2(19,18,17,16,15,14,13,12,11,10);
/*-----------------------------------------------------------Band3(For the third LED stripe)---------
------------------------------------------------------*/
// allocation for the Numbers of LEDs
l = level [2];
abfolge(20,21,22,23,24,25,26,27,28,29);
if (l < 92) LEDaus1(20,21,22,23,24,25,26,27,28,29);
/*-----------------------------------------------------------Band4(For the fourth LED stripe)--------
-------------------------------------------------------*/
// allocation for the Numbers of LEDs
l = level [3];
abfolge(39,38,37,36,35,34,33,32,31,30);
if (l < 92) LEDaus2(39,38,37,36,35,34,33,32,31,30);
/*-----------------------------------------------------------Band5(For the fifth LED stripe)----------
-----------------------------------------------------*/
// allocation for the Numbers of LEDs
l = level [4];
abfolge(40,41,42,43,44,45,46,47,48,49);
if (l < 92) LEDaus1(40,41,42,43,44,45,46,47,48,49);
/*-----------------------------------------------------------Band6(For the sixth LED stripe)---------
------------------------------------------------------*/
// allocation for the Numbers of LEDs
l = level [5];
abfolge(59,58,57,56,55,54,53,52,51,50);
if (l < 92) LEDaus2(59,58,57,56,55,54,53,52,51,50);
/*-----------------------------------------------------------Band7(For the seventh LED stripe)------
---------------------------------------------------------*/
// allocation for the Numbers of LEDs
l = level [6];
abfolge(60,61,62,63,64,65,66,67,68,69);
if (l < 92) LEDaus1(60,61,62,63,64,65,66,67,68,69);
}
17) Arduino Line Follower Robot
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
BO motor
× 1
wheels
× 1
ir sensor
× 1
Custom PCB
× 1
9V battery (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Components used:
Piece of cardboard/ Acrylic sheet
Arduino Uno
IR sensor
BO motor
Wheels
Caster wheel
L293d IC
PCB
Flexible wire
Battery
Fix all components on acrylic sheet and make a chassis as shown in
pictures.
you can make this circuit on dotted pcb like this.
//
//for Line Following Robot using 2IR sensors
int lm1=8; //left motor output 1
int lm2=9; //left motor output 2
int rm1=10; //right motor output 1
int rm2=11; //right motor output 2
int sl=13; //sensor 1 input (left)
int sr=12; //sensor 2 input (right)
int SlV=0;
int SrV=0;
int led=A0;
void setup()
{
pinMode(lm1,OUTPUT);
pinMode(lm2,OUTPUT);
pinMode(rm1,OUTPUT);
pinMode(rm2,OUTPUT);
pinMode(led,OUTPUT);
pinMode(sl,INPUT);
pinMode(sr,INPUT);
sTOP();
}
void loop()
{
SlV=digitalRead(sl);
SrV=digitalRead(sr);
if(SrV==LOW && SlV== LOW)
{
ForWard();
}
if(SrV==HIGH && SlV== LOW)
{
Left();
}
if(SrV==LOW && SlV== HIGH)
{
Right();
}
if(SrV==HIGH && SlV== HIGH)
{
sTOP();
}
}
void ForWard()
{
digitalWrite(lm1,HIGH);
digitalWrite(lm2,LOW);
digitalWrite(rm1,HIGH);
digitalWrite(rm2,LOW);
}
void BackWard()
{
digitalWrite(lm1,LOW);
digitalWrite(lm2,HIGH);
digitalWrite(rm1,LOW);
digitalWrite(rm2,HIGH);
}
void Left()
{
digitalWrite(lm1,LOW);
digitalWrite(lm2,HIGH);
digitalWrite(rm1,HIGH);
digitalWrite(rm2,LOW);
}
void Right()
{
digitalWrite(lm1,HIGH);
digitalWrite(lm2,LOW);
digitalWrite(rm1,LOW);
digitalWrite(rm2,HIGH);
}
void sTOP()
{
digitalWrite(lm1,LOW);
digitalWrite(lm2,LOW);
digitalWrite(rm1,LOW);
digitalWrite(rm2,LOW);
}
× 1
× 1
Relay (generic)
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
SCHEMATICS
CODE
Automated Garden Watering Nano
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
void loop()
{
displayTempHumid();
display.display();
}
/*
* This sketch demonstrates how to set up a simple HTTP-like server.
* The server will set a GPIO pin depending on the request
* http://server_ip/gpio/0 will set the GPIO2 low,
* http://server_ip/gpio/1 will set the GPIO2 high
* server_ip is the IP address of the ESP8266 module, will be
* printed to Serial when the module is connected.
*/
#include <ESP8266WiFi.h>
boolean waternow=false;
void setup() {
Serial.begin(9600);
delay(10);
pinMode(2, OUTPUT);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
int val;
if (req.indexOf("manu/ON") != -1){
waternow=true;}
else if (req.indexOf("manu/OFF") != -1){
waternow=false;}
else {
Serial.println("invalid request");
client.stop();
return;
}
client.flush();
delay(1);
Serial.println("Client disonnected");
if (waternow==true){ digitalWrite(2, HIGH);
delay (30000);
waternow=false;}
else{digitalWrite(2, LOW);}
79) Full Control of Your Tv Using Alexa and Arduino IoT Cloud
COMPONENTS AND SUPPLIES
× 1
× 1
IR receiver (generic)
× 1
ex. VS1838B
IR transmitter (generic)
× 1
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino Web Editor
We're done, it's now time to voice control our TV asking things like
”Alexa, turn the volume up on TV.”
”Alexa, mute TV" or “Alexa, unmute TV.”
”Alexa, next channel on TV.”
SCHEMATICS
CODE
/*
Sketch generated by the Arduino IoT Cloud Thing
"TVRemoteController"
https://create.arduino.cc/cloud/things/994d9efc-9c38-4a4c-9d3c-
454106da00f6
CloudTelevision tv;
#include "thingProperties.h"
#include <IRremote.h>
IRsend irsend;
const int freq = 38;
bool first;
int prevChannel;
int prevVolume;
bool prevSwitch;
bool prevMute;
void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without
blocking if none is found
delay(1500);
// Defined in thingProperties.h
initProperties();
first = true;
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
ArduinoCloud.update();
}
void onTvChange() {
Serial.println("==================");
Serial.println("Switch:"+String(tv.getSwitch()));
Serial.println("Volume:"+String(tv.getVolume()));
Serial.println("Channel:"+String(tv.getChannel()));
Serial.println("Mute:"+String(tv.getMute()));
Serial.println("==================");
if (first){
prevSwitch = tv.getSwitch();
prevVolume = tv.getVolume();
prevChannel = tv.getChannel();
prevMute = tv.getMute();
first = false;
return;
}
// Volume changed
if (tv.getVolume() > prevVolume) {
tv.setMute(false);
prevMute = false;
for (int k = prevVolume + 1 ; k<=tv.getVolume(); k++) {
sendIR(volUp);
Serial.println("Volume requested:"+String(tv.getVolume())+"
Set:"+String(k));
}
prevVolume = tv.getVolume();
}
else if (tv.getVolume() < prevVolume) {
tv.setMute(false);
prevMute = false;
for (int k = prevVolume - 1; k>=tv.getVolume(); k--) {
sendIR(volDown);
Serial.println("Volume changed:"+String(tv.getVolume())+"
Set:"+String(k));
}
prevVolume = tv.getVolume();
}
// Mute changed
if (tv.getMute() != prevMute && tv.getMute()) {
prevMute = tv.getMute();
sendIR(mute);
Serial.println("Mute changed:"+String(tv.getMute()));
}
else if (tv.getMute() != prevMute && !tv.getMute()) {
prevMute = tv.getMute();
sendIR(mute);
Serial.println("Mute changed:"+String(tv.getMute()));
}
// Channel changed
if (tv.getChannel() != prevChannel) {
int newChannel = tv.getChannel();
if (newChannel > 0 && newChannel < 10) {
sendIR(chan[newChannel-1]);
} else if (newChannel > 9) {
if (newChannel > prevChannel) {
for (int ch = prevChannel; ch < newChannel; ch++) {
sendIR(chanUp);
Serial.println("Chan requested:"+String(newChannel)+"
Set:"+String(ch));
}
} else if (newChannel < prevChannel) {
for (int ch = prevChannel; ch > newChannel; ch--) {
sendIR(chanDown);
Serial.println("Chan requested:"+String(newChannel)+"
Set:"+String(ch));
}
}
}
prevChannel = newChannel;
Serial.println("Channel changed:"+String(tv.getChannel()));
}
// On/Off changed
if (tv.getSwitch() != prevSwitch) {
prevSwitch = tv.getSwitch();
if (tv.getSwitch()) {
sendIR(chan[6]);
} else {
sendIR(onoff);
}
Serial.println("Switch changed:"+String(tv.getSwitch()));
}
}
× 1
Breadboard (generic)
× 1
Buzzer
× 1
Photo resistor
× 1
LED (generic)
× 1
× 1
× 2
× 12
ABOUT THIS PROJECT
DISCLAIMER: The song "Never Gonna Give You Up" by Rick Astley
is not the creative property of the author. This code simply
plays a Piezo buzzer rendition of the song.
*/
#define rest -1
int piezo = 7;
int led = 9;
int button = 2;
int sensor = A0;
int threshold;
int a; // part index
int b; // song index
int c; // lyric index
boolean flag;
int song1_intro_melody[] =
{c5s, e5f, e5f, f5, a5f, f5s, f5, e5f, c5s, e5f, rest, a4f, a4f};
int song1_intro_rhythmn[] =
{6, 10, 6, 6, 1, 1, 1, 1, 6, 10, 4, 2, 10};
// Parts 3 or 5 (Verse 1)
int song1_verse1_melody[] =
{ rest, c4s, c4s, c4s, c4s, e4f, rest, c4, b3f, a3f,
rest, b3f, b3f, c4, c4s, a3f, a4f, a4f, e4f,
rest, b3f, b3f, c4, c4s, b3f, c4s, e4f, rest, c4, b3f, b3f, a3f,
rest, b3f, b3f, c4, c4s, a3f, a3f, e4f, e4f, e4f, f4, e4f,
c4s, e4f, f4, c4s, e4f, e4f, e4f, f4, e4f, a3f,
rest, b3f, c4, c4s, a3f, rest, e4f, f4, e4f
};
int song1_verse1_rhythmn[] =
{ 2, 1, 1, 1, 1, 2, 1, 1, 1, 5,
1, 1, 1, 1, 3, 1, 2, 1, 5,
1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 3,
1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4,
5, 1, 1, 1, 1, 1, 1, 1, 2, 2,
2, 1, 1, 1, 3, 1, 1, 1, 3
};
char* lyrics_verse1[] =
{ "We're ", "no ", "strangers ", "", "to ", "love ", "", "\r\n",
"You ", "know ", "the ", "rules ", "and ", "so ", "do ", "I\r\n",
"A ", "full ", "commitment's ", "", "", "what ", "I'm ", "thinking ", "", "of", "\r\n",
"You ", "wouldn't ", "", "get ", "this ", "from ", "any ", "", "other ", "", "guy\r\n",
"I ", "just ", "wanna ", "", "tell ", "you ", "how ", "I'm ", "feeling", "\r\n",
"Gotta ", "", "make ", "you ", "understand", "", "\r\n"
};
// Parts 4 or 6 (Chorus)
int song1_chorus_melody[] =
{ b4f, b4f, a4f, a4f,
f5, f5, e5f, b4f, b4f, a4f, a4f, e5f, e5f, c5s, c5, b4f,
c5s, c5s, c5s, c5s,
c5s, e5f, c5, b4f, a4f, a4f, a4f, e5f, c5s,
b4f, b4f, a4f, a4f,
f5, f5, e5f, b4f, b4f, a4f, a4f, a5f, c5, c5s, c5, b4f,
c5s, c5s, c5s, c5s,
c5s, e5f, c5, b4f, a4f, rest, a4f, e5f, c5s, rest
};
int song1_chorus_rhythmn[] =
{ 1, 1, 1, 1,
3, 3, 6, 1, 1, 1, 1, 3, 3, 3, 1, 2,
1, 1, 1, 1,
3, 3, 3, 1, 2, 2, 2, 4, 8,
1, 1, 1, 1,
3, 3, 6, 1, 1, 1, 1, 3, 3, 3, 1, 2,
1, 1, 1, 1,
3, 3, 3, 1, 2, 2, 2, 4, 8, 4
};
char* lyrics_chorus[] =
{ "Never ", "", "gonna ", "", "give ", "you ", "up\r\n",
"Never ", "", "gonna ", "", "let ", "you ", "down", "", "\r\n",
"Never ", "", "gonna ", "", "run ", "around ", "", "", "", "and ", "desert ", "", "you\r\n",
"Never ", "", "gonna ", "", "make ", "you ", "cry\r\n",
"Never ", "", "gonna ", "", "say ", "goodbye ", "", "", "\r\n",
"Never ", "", "gonna ", "", "tell ", "a ", "lie ", "", "", "and ", "hurt ", "you\r\n"
};
void setup()
{
pinMode(piezo, OUTPUT);
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP);
pinMode(sensor, INPUT);
attachInterrupt(digitalPinToInterrupt(button), getFaster, FALLING);
digitalWrite(led, LOW);
Serial.begin(9600);
flag = false;
a = 4;
b = 0;
c = 0;
threshold = analogRead(sensor) + 250;
}
void loop()
{
int sensorreading = analogRead(sensor);
if (sensorreading < threshold) { // if bright, play
flag = true;
}
else if (sensorreading > threshold) { // if dark, pause
flag = false;
}
void play() {
int notelength;
if (a == 1 || a == 2) {
// intro
notelength = beatlength * song1_intro_rhythmn[b];
if (song1_intro_melody[b] > 0) {
digitalWrite(led, HIGH);
tone(piezo, song1_intro_melody[b], notelength);
}
b++;
if (b >= sizeof(song1_intro_melody) / sizeof(int)) {
a++;
b = 0;
c = 0;
}
}
else if (a == 3 || a == 5) {
// verse
notelength = beatlength * 2 * song1_verse1_rhythmn[b];
if (song1_verse1_melody[b] > 0) {
digitalWrite(led, HIGH);
Serial.print(lyrics_verse1[c]);
tone(piezo, song1_verse1_melody[b], notelength);
c++;
}
b++;
if (b >= sizeof(song1_verse1_melody) / sizeof(int)) {
a++;
b = 0;
c = 0;
}
}
else if (a == 4 || a == 6) {
// chorus
notelength = beatlength * song1_chorus_rhythmn[b];
if (song1_chorus_melody[b] > 0) {
digitalWrite(led, HIGH);
Serial.print(lyrics_chorus[c]);
tone(piezo, song1_chorus_melody[b], notelength);
c++;
}
b++;
if (b >= sizeof(song1_chorus_melody) / sizeof(int)) {
Serial.println("");
a++;
b = 0;
c = 0;
}
}
delay(notelength);
noTone(piezo);
digitalWrite(led, LOW);
delay(notelength * beatseparationconstant);
if (a == 7) { // loop back around to beginning of song
a = 1;
}
}
× 1
PHPoC Bread Board
× 1
LED (generic)
× 2
× 2
Buzzer
× 1
SCHEMATICS
CODE
#include <RFID.h>
#include <SPI.h>
#include <SR04.h>
#include <DS3231.h>
#include <Wire.h>
String ora;
String mins;
String orario;
DS3231 Clock;
#define ECHO_PIN 3
#define TRIG_PIN 4
#define green 5
#define red 6
#define buzz 8
#define RESET_DIO 9
#define SDA_DIO 10
bool h12;
bool PM;
int attivo=false;
int statoattivato=0;
String codiceLetto;
String codiceAutorizzato = "5545A93980";
void setup(){
Wire.begin();
SPI.begin();
RC522.init();
pinMode(buzz,OUTPUT);
pinMode(red,OUTPUT);
pinMode(green,OUTPUT);
digitalWrite(green,LOW);
digitalWrite(red,HIGH);
}
void loop(){
ora=Clock.getHour(h12, PM), DEC;
mins=Clock.getMinute(), DEC;
orario=ora+":"+mins;
byte i;
if (RC522.isCard()) {
if(verificaCodice(lettura())) {
rilevatore();
}
delay(delayRead);
}
if (orario=="21:56" && statoattivato==0) {
statoattivato=1;
rilevatore();
}
}
void rilevatore() {
if (attivo==false) {
attivo=true;
digitalWrite(red,LOW);
digitalWrite(green,HIGH);
while (attivo=true) {
if (sr04.Distance()<120)
tone(8,262,500);
if (RC522.isCard()) {
if (verificaCodice(lettura())) {
attivo=false;
digitalWrite(green,LOW);
digitalWrite(red,HIGH);
break;
}
}
}
}
}
boolean verificaCodice(String codiceLetto){
if(codiceLetto.equals(codiceAutorizzato)){
return true;
}
else{
return false;
}
}
String lettura(){
byte i;
RC522.readCardSerial();
String codiceLetto ="";
for(i = 0; i <= 4; i++) {
codiceLetto += String (RC522.serNum[i],HEX);
codiceLetto.toUpperCase();
}
return codiceLetto;
}
82) Arduino Smart Whellchair
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
DC motor (generic)
× 1
× 1
× 1
Buzzer
× 1
Breadboard (generic)
× 1
× 1
5 mm LED: Red
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Objective
The objective of this project is to help physically challenged people. It
will basically very helpful for those who cannot able to walk.
Introduction
This is a simple prototype of Smart Wheelchair. The wheelchair is
multi functioned. One can use this wheelchair for various purposes.
This chair can be used as panic alarm. If the person needs instant help,
he/she can hit the panic alarm button so that someone can help him/her
immediately. This wheelchair also has a led light. So, anyone can roam
here and there when the surroundings has not enough light. Last but not
the least this wheelchair is also automatically identify the obstacles and
it makes decision to go with the obstacle free path.
Required Equipments
Arduino UNO
Motor Driver (Model:L298N)
Bluetooth Module (Model:HC-05)
Ultrasonic Sensor (Model:HC-SR04)
DC Motor
Lipo Battery(1000mAh)
Breadboard
LED
Push Button
Switch(ON/OFF)
Buzzer
Jumper Wire (Male to Male | Male to Female | Female to Female)
Connections
A) Motor Driver to Arduino
IN1 to Digital Pin 8
IN2 to Digital Pin 9
IN3 to Digital Pin 10
IN4 to Digital Pin 11
+12V to Lipo Battery Positive Lead
GND to Lipo Battery Negative Lead
+5V to VIN (Arduino)
B)Bluetooth Module to Arduino
+5V (Arduino) to +5V (Bluetooth)
GND (Arduino) to GND (Bluetooth)
RX (Arduino) to TX (Bluetooth)
TX (Arduino) to RX (Bluetooth)
C) Ultrasonic Sensor to Arduino
Trig Pin to Digital Pin 12
Echo Pin to Digital Pin 13
Trig Pin to Digital Pin 7
Echo Pin to Digital Pin 6
VCC to 5V
GND to GND
D) Other Connections
Led Light (Anode ) to Digital Pin 5 (Arduino)
Buzzer (Positive Lead) to Digital Pin 4 (Arduino)
Push Button (Positive Lead) to Digital Pin 3 (Arduino)
Bluetooth App Google Play Store Link
App Download Link: https://play.google.com/store/apps/details?
id=com.keuwl.arduinobluetooth
Bluetooth App Setting
Step-1
First download the app from the Google Play Store. I have given the
link of the app in the above (Bluetooth App Google Play Store Link)
Section.
Android App
Step-2
Edit a new panel for your Wheelchair controls
Click on Connect
Click Done
Important Instructions
During the uploading the code on Arduino we need to pull down
the RX and TX connection from the Arduino.
Lipo Battery is very powerful battery. So, make sure that the each
connections are perfectly ok.
SCHEMATICS
CODE
int motorRightA = 8; //Right Motor-clockwise
int motorRightB = 9; //Right Motor-anticlockwise
int motorLeftA = 11; //Left Motor-clockwise
int motorLeftB = 10; //Left Motor-clockwise
int trigPin1 = 12; // Trig Pin
int echoPin1 = 13; // Echo Pin
int light = 5;
long duration1;
int distance1;
char bt = 0; //Bluetooth Control
int trigPin2 = 7; // Trig Pin
int echoPin2 = 6; // Echo Pin
long duration2;
int distance2;
int buzzer = 4;
int pushButton = 3;
void setup()
{
pinMode(motorRightA, OUTPUT);
pinMode(motorRightB, OUTPUT);
pinMode(motorRightB, OUTPUT);
pinMode(motorLeftB, OUTPUT);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(light, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(pushButton, INPUT_PULLUP);
Serial.begin(9600);
}
void loop()
{
//Light On Off
lightOnOff();
//Panic Button
panicSound();
// Right
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration1 = pulseIn(echoPin1, HIGH);
// Calculating the distance
distance1 = duration1 * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance1);
// Left
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration2 = pulseIn(echoPin2, HIGH);
// Calculating the distance
distance2 = duration2 * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance2);
void lightOnOff() {
if (bt == 'O') {
digitalWrite(light, HIGH);
}
else if (bt == 'o') {
digitalWrite(light, LOW);
}
}
void panicSound() {
int val = digitalRead(pushButton);
if (val == LOW) {
digitalWrite(buzzer, HIGH);
} else {
digitalWrite(buzzer, LOW);
}
}
Touch sensor
You can also use a button, but × 1
you'll need a pull-down resistor.
NTC Thermistor
× 1
× 1
Buzzer
× 1
× 1
A transparent box to put everything
into
It needs to be transparent for you × 1
to be able to see the LCD and it
needs to be waterproof to light
rain
APPS AND ONLINE SERVICES
Arduino IDE
What is it?
Reasonably, the most reliable approach to slowing down the spread of
the coronavirus is to keep away from others; prevention is better than
cure. However, it would be irritating to turn around every thirty
seconds and look if someone was approaching you. It would be helpful
if there were a device that could warn others to keep away from you.
That is the purpose behind the project: to alert others to maintain a 2-
meter distance from you. It is a 2-in-1 as the thermistor is not only used
to add accuracy to the distance measurement (the speed of sound
changes depending on the temperature) but it also means that – by
using a button or a touch sensor to switch between the modes – it can
have two modes: alerting if someone comes close to you (Mode 1) and
measuring the temperature and the distance (Mode 2). The measuring
mode shows the temperature and the distance on the LCD.
How does it work?
The Arduino measures the temperature.
The temperature is used to calculate the distance with greater
accuracy.
If the Arduino is on Mode 1:
If the distance is between 2m and 1m, the LCD backlight lights up
and the LCD shows "Please keep away" and how far away the
person is.
If the distance is 1m - 50cm the backlight of the LCD flashes and the
LCD shows "Keep away"
If the distance is less than 50cm the backlight turns off and on twice
a second and the LCD shows "STAY AWAY!"
If the Arduino is on Mode 2, the LCD shows the distance on the top
and the temperature on the bottom of the screen.
To protect the components from the rain, I attached half a plastic bottle
which can be pushed up when there is rain.
It can be attached to (using two pieces of string) and be easily removed
from the bottom of a rucksack.
Mode 2
1m to 50cm
Closer than 50cm
2m to 1m
Importing a library
SCHEMATICS
CODE
#include <HCSR04.h>
#include <LiquidCrystal.h>
#define trigPin 7
#define echoPin 6
#define buzzer 9
#define backlight 10
int tempReading;
double tempK;
float tempC;
int rounded;
int temp_round;
volatile boolean modes = 0;
double distance;
void setup() {
lcd.begin(16, 2);
attachInterrupt(0, changeMode, FALLING);
pinMode(2, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(backlight, OUTPUT);
digitalWrite(backlight, HIGH);
backlightOn();
}
void loop() {
tempReading = analogRead(A0);
tempK = log(10000.0 * ((1024.0 / tempReading - 1)));
tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) *
tempK );
tempC = tempK - 273.15;
distance = distanceSensor.measureDistanceCm(tempC);
temp_round = round(tempC);
if (modes == 1) {
backlightOn();
if (distance >= 300 || distance <= 0) {
rounded = 0;
lcd.clear();
lcd.print("Out of range");
lcd.setCursor(0, 1);
lcd.print("Temperature:" + String(temp_round) + " C");
}
else {
rounded = round(distance);
lcd.clear();
lcd.print("Distance: ");
lcd.print(rounded);
lcd.print(" cm");
lcd.setCursor(0, 1);
lcd.print("Temperature:" + String(temp_round) + " C");
}
} else {
if (distance >= 300 || distance <= 0) {
rounded = 0;
lcd.clear();
backlightOff();
}
else {
rounded = round(distance);
if (distance >= 200) {
backlightOff();
lcd.clear();
}
else if (distance <= 200 && distance > 100) {
backlightOn();
lcd.clear();
lcd.print("Please keep away");
lcd.setCursor(0, 1);
lcd.print("Distance:");
lcd.print(rounded);
lcd.print(" cm");
}
else if (distance <= 100 && distance > 50) {
backlightOn();
lcd.clear();
lcd.print("Keep away");
lcd.setCursor(0, 1);
lcd.print("Distance:");
lcd.print(rounded);
lcd.print(" cm");
delay(200);
buzz();
backlightOff();
delay(100);
unbuzz();
backlightOn();
delay(100);
}
else if (distance <= 50) {
backlightOn();
lcd.clear();
lcd.print("STAY AWAY!");
lcd.setCursor(0, 1);
lcd.print("Distance:");
lcd.print(rounded);
lcd.print(" cm");
delay(200);
buzz();
backlightOff();
delay(200);
unbuzz();
backlightOn();
delay(200);
buzz();
backlightOff();
delay(200);
unbuzz();
backlightOn();
}
}
}
delay(700);
}
void changeMode() {
modes = !modes;
}
void backlightOn() {
digitalWrite(backlight, HIGH);
}
void backlightOff() {
digitalWrite(backlight, LOW);
}
void buzz() {
digitalWrite(buzzer, HIGH);
}
void unbuzz() {
digitalWrite(buzzer, LOW);
}
84) Arduino RGB Goggles
COMPONENTS AND SUPPLIES
Arduino Nano R3
× 1
× 1
Battery, 3.7 V
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
Hey! I have made a RGB Goggles using WS2812B LEDs and Arduino
Nano. The goggles have many animations they can be controlled using
a mobile app.The app can communicate with Arduino through
Bluetooth module. This goggles are lightweight.
SCHEMATICS
CODE
#include <FastLED.h>
#define LED_PIN 3
#define NUM_LEDS 88
#define LED_TYPE WS2812B
#define COLOR_ORDER RGB
#define BRIGHTNESS 255
#define UPDATES_PER_SECOND 100
#define kMatrixWidth 17
#define kMatrixHeight 6
#define kMatrixSerpentineLayout true
CRGBArray<NUM_LEDS> leds;
uint32_t x,y,v_time,hue_time,hxy;
uint8_t octaves=1;
uint8_t hue_octaves=3;
int xscale=57771;
int yscale=57771;
int hue_scale=1;
int time_speed=1111;
int hue_speed=31;
int x_speed=331;
int y_speed=1111;
CRGBPalette16 currentPalette;
TBlendType currentBlending;
extern CRGBPalette16 myRedWhiteBluePalette;
extern const TProgmemPalette16 myRedWhiteBluePalette_p PROGMEM;
void setup()
{
Serial.begin(9600);
delay(1000);
FastLED.addLeds<NEOPIXEL,LED_PIN>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
currentPalette = RainbowColors_p;
currentBlending = LINEARBLEND;
random16_set_seed(8934);
random16_add_entropy(analogRead(3));
hxy = (uint32_t)((uint32_t)random16() << 16) + (uint32_t)random16();
x = (uint32_t)((uint32_t)random16() << 16) + (uint32_t)random16();
y = (uint32_t)((uint32_t)random16() << 16) + (uint32_t)random16();
v_time = (uint32_t)((uint32_t)random16() << 16) + (uint32_t)random16();
hue_time = (uint32_t)((uint32_t)random16() << 16) + (uint32_t)random16();
}
char ch;
void loop()
{
FastLED.clear();
FastLED.show();
if(Serial.available())
{
ch=Serial.read();
Serial.println(ch);
switch (ch)
{
case '1':
for(int i=0;i<10;i++)
{
leds[37] = CRGB(255, 0, 0);
leds[44] = CRGB(255, 0, 0);
FastLED.show();
delay(90);
FastLED.clear();
leds[20] = CRGB(255, 0, 0);
leds[30] = CRGB(255, 0, 0);
leds[36] = CRGB(255, 0, 0);
leds[38] = CRGB(255, 0, 0);
leds[43] = CRGB(255, 0, 0);
leds[45] = CRGB(255, 0, 0);
leds[51] = CRGB(255, 0, 0);
leds[58] = CRGB(255, 0, 0);
FastLED.show();
delay(90);
FastLED.clear();
delay(90);
FastLED.clear();
delay(90);
FastLED.clear();
leds[20] = CRGB(255, 0, 0);
leds[30] = CRGB(255, 0, 0);
leds[36] = CRGB(255, 0, 0);
leds[38] = CRGB(255, 0, 0);
leds[43] = CRGB(255, 0, 0);
leds[45] = CRGB(255, 0, 0);
leds[51] = CRGB(255, 0, 0);
leds[58] = CRGB(255, 0, 0);
FastLED.show();
delay(90);
FastLED.clear();
}
break;
case '2':
for(int i=0;i<5;i++)
{
leds[36] = CRGB(255, 0, 187);
leds[37] = CRGB(255, 0, 187);
leds[44] = CRGB(255, 0, 187);
leds[45] = CRGB(255, 0, 187);
leds[50] = CRGB(255, 0, 187);
leds[51] = CRGB(255, 0, 187);
leds[58] = CRGB(255, 0, 187);
leds[59] = CRGB(255, 0, 187);
FastLED.show();
delay(90);
FastLED.clear();
case '3':
for(int i=0;i<5;i++)
{
leds[0] = CRGB(255, 0, 187);
leds[1] = CRGB(255, 0, 187);
leds[2] = CRGB(255, 0, 187);
leds[3] = CRGB(255, 0, 187);
leds[4] = CRGB(255, 0, 187);
leds[5] = CRGB(255, 0, 187);
leds[6] = CRGB(255, 0, 187);
leds[7] = CRGB(255, 0, 187);
leds[8] = CRGB(255, 0, 187);
leds[9] = CRGB(255, 0, 187);
leds[10] = CRGB(255, 0, 187);
leds[11] = CRGB(255, 0, 187);
leds[12] = CRGB(255, 0, 187);
leds[13] = CRGB(255, 0, 187);
leds[14] = CRGB(255, 0, 187);
leds[15] = CRGB(255, 0, 187);
leds[16] = CRGB(255, 0, 187);
leds[17] = CRGB(255, 0, 187);
leds[18] = CRGB(255, 161, 0);
leds[19] = CRGB(255, 161, 0);
leds[20] = CRGB(255, 161, 0);
leds[21] = CRGB(255, 161, 0);
leds[22] = CRGB(255, 161, 0);
leds[23] = CRGB(255, 0, 187);
leds[24] = CRGB(255, 0, 187);
leds[25] = CRGB(255, 0, 187);
leds[26] = CRGB(255, 0, 187);
leds[27] = CRGB(255, 0, 187);
leds[28] = CRGB(255, 161, 0);
leds[29] = CRGB(255, 161, 0);
leds[30] = CRGB(255, 161, 0);
leds[31] = CRGB(255, 161, 0);
leds[32] = CRGB(255, 161, 0);
leds[33] = CRGB(255, 0, 187);
leds[34] = CRGB(255, 0, 187);
leds[35] = CRGB(255, 161, 0);
leds[36] = CRGB(0, 255, 255);
leds[37] = CRGB(0, 255, 255);
leds[38] = CRGB(0, 255, 255);
leds[39] = CRGB(255, 161, 0);
leds[40] = CRGB(255, 0, 187);
leds[41] = CRGB(255, 0, 187);
leds[42] = CRGB(255, 161, 0);
leds[43] = CRGB(0, 255, 255);
leds[44] = CRGB(0, 255, 255);
leds[45] = CRGB(0, 255, 255);
leds[46] = CRGB(255, 161, 0);
leds[47] = CRGB(255, 0, 187);
leds[48] = CRGB(255, 0, 187);
leds[49] = CRGB(255, 161, 0);
leds[50] = CRGB(0, 255, 255);
leds[51] = CRGB(0, 255, 255);
leds[52] = CRGB(0, 255, 255);
leds[53] = CRGB(255, 161, 0);
leds[54] = CRGB(255, 0, 187);
leds[55] = CRGB(255, 0, 187);
leds[56] = CRGB(255, 161, 0);
leds[57] = CRGB(0, 255, 255);
leds[58] = CRGB(0, 255, 255);
leds[59] = CRGB(0, 255, 255);
leds[60] = CRGB(255, 161, 0);
leds[61] = CRGB(255, 0, 187);
leds[62] = CRGB(255, 0, 187);
leds[63] = CRGB(255, 161, 0);
leds[64] = CRGB(255, 161, 0);
leds[65] = CRGB(255, 161, 0);
leds[66] = CRGB(255, 161, 0);
leds[67] = CRGB(255, 161, 0);
leds[68] = CRGB(255, 0, 187);
leds[69] = CRGB(255, 0, 187);
leds[70] = CRGB(255, 161, 0);
leds[71] = CRGB(255, 161, 0);
leds[72] = CRGB(255, 161, 0);
leds[73] = CRGB(255, 161, 0);
leds[74] = CRGB(255, 161, 0);
leds[75] = CRGB(255, 0, 187);
leds[76] = CRGB(255, 0, 187);
leds[77] = CRGB(255, 0, 187);
leds[78] = CRGB(255, 0, 187);
leds[79] = CRGB(255, 0, 187);
leds[80] = CRGB(255, 0, 187);
leds[81] = CRGB(255, 0, 187);
leds[82] = CRGB(255, 0, 187);
leds[83] = CRGB(255, 0, 187);
leds[84] = CRGB(255, 0, 187);
leds[85] = CRGB(255, 0, 187);
leds[86] = CRGB(255, 0, 187);
leds[87] = CRGB(255, 0, 187);
FastLED.show();
delay(90);
FastLED.clear();
case '4':
break;
case '5':
for(int i=0;i<4;i++)
{
static uint8_t hue;
for(int i = 0; i < NUM_LEDS/2; i++) {
// fade everything out
leds.fadeToBlackBy(40);
case '6':
{
for(int i=0;i<3;i++)
{
static uint8_t hue = 0;
Serial.print("x");
for(int i = 0; i < NUM_LEDS; i++) {
leds[i] = CHSV(hue++, 255, 255);
FastLED.show();
fadeall();
delay(10);
}
Serial.print("x");
for(int i = (NUM_LEDS)-1; i >= 0; i--) {
leds[i] = CHSV(hue++, 255, 255);
FastLED.show();
fadeall();
delay(10);
...
This file has been truncated, please download it to see its full contents.
85) Arduino Automated Aeroponic System Wifi
× 1
Multitool, Screwdriver
Manual saw
Introduction
Hi, I'm a chemical engineering student. Until I started this project I had
no idea how to code. I started with blink... two months ago... thanks to
the lockdown. I can't guarantee that my code is written according to the
rules. But I've tested it for hours, days, it works.
I challenge myself in many ways, in this project, I did it for myself; it's
not a school project or anything else. I started from scratch. I used a lot
of lines of code from other sources, but in the end, I started writing my
own. I'm not in a good position to teach someone because I'm a
beginner. But I think that since I've read tons of projects and trained for
over 450 hours reading, coding and failing tons of times, maybe this
one can help people. Besides, knowledge dies when it's not shared.
byte Heart[8] = {
0b00000,
0b01010,
0b11111,
0b11111,
0b01110,
0b00100,
0b00000,
0b00000
};
byte tete2[8] =
{
0b11000,
0b11100,
0b10001,
0b11110,
0b10001,
0b11000,
0b11111,
0b10001
};
byte tete3[8] =
{
0b00000,
0b00000,
0b10011,
0b01110,
0b10001,
0b00100,
0b10001,
0b01110
};
byte tete4[8] =
{
0b00000,
0b00000,
0b00000,
0b10000,
0b01000,
0b01000,
0b11100,
0b10110
};
byte bas1[8] =
{
0b00010,
0b00010,
0b00011,
0b00001,
0b00001,
0b00000,
0b00000,
0b00000
};
byte bas2[8] =
{
0b01011,
0b01100,
0b00111,
0b01000,
0b11111,
0b01001,
0b01001,
0b01001
};
byte bas3[8] =
{
0b00011,
0b11001,
0b00000,
0b10100,
0b11111,
0b00010,
0b00010,
0b00010
};
byte bas4[8] =
{
0b10001,
0b01001,
0b00101,
0b10011,
0b11110,
0b00100,
0b00100,
0b00100
};
//=========================================Fin
mouton=================================
//=========================================Librarie
utilisées=========================
#include <EEPROM.h>
#include <DHT.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <SD.h>
#include <LiquidCrystal_I2C.h>
#include <virtuabotixRTC.h> //Library used
#include <ResponsiveAnalogRead.h>
//=========================================Pin
definie=================================
#define RELAY1 24
#define POMPES 22
#define LAMPES 26
#define moteurA_1 38
#define moteurA_2 40
#define moteurB_1 36
#define moteurB_2 34
#define DS1302_GND_PIN 33
#define DS1302_VCC_PIN 31
#define Tbox A2
#define DHTPIN 32 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define TdsSensorPin A8
#define VREF 5.0 // analog reference voltage(Volt) of the ADC
#define SCOUNT 3 // sum of sample point
#define ONE_WIRE_BUS 7
//=========================================Constantes
utiilisées============================
unsigned long currentMillis1 = 0;
unsigned long currentMillis4 = 0;
unsigned long previousMillis1 = 0;
unsigned long previousMillis = 0;
unsigned long previousMillis3 = 0;
const long interval = 10000;
unsigned long periodtds = 3600000; // 1h
const long nettoyage = 10000;
const int chipSelect = 49;
unsigned long startMillis1;
unsigned long startMillis;
String message = "";
bool messageReady = false;
String message1 = "";
bool messageReady1 = false;
int analogBuffer1[SCOUNT]; // store the analog value in the array, read from ADC
int analogBufferTemp1[SCOUNT];
int analogBufferIndex1 = 0, copyIndex1 = 0;
int analogBuffer[SCOUNT];
int analogBufferTemp[SCOUNT];
int analogBufferIndex = 0, copyIndex = 0;
float averageVoltage = 0 , tdsValue = 0;
int analogBuffer2[SCOUNT];
int analogBufferTemp2[SCOUNT];
int analogBufferIndex2 = 0, copyIndex2 = 0;
float averageVoltage2 = 0;
int val;
int addr = 0;
int ledstate;
int pompestate;
int int1;
int int2;
int int3;
int int4;
int int5;
int int6;
int int7;
int minteau ;
int maxteau ;
int timearro;
float temperature;
float humi;
float temp;
float tbox;
int tdsval;
int OnHour;
int OnMin; //set hour and minutes for timer
int OffHour;
int OffMin;
int valeur_brute;
bool freshtds = false;
bool cleanup = false;
bool perioff = true;
//=========================================Fonction
declaré============================
LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line
display
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
ResponsiveAnalogRead analog(Tbox, true);
virtuabotixRTC myRTC(35, 37, 39); //If you change the wiring change the pins here also
//=========================================Fonction demmarage
============================
void LedState() {
val = EEPROM.read(addr);
if (val == 1)
{
digitalWrite(LAMPES, HIGH);
}
if (val == 2)
{
digitalWrite(LAMPES, LOW);
}
maxteau = EEPROM.read(2);
minteau = EEPROM.read(3);
OnHour = EEPROM.read(4);
OnMin = EEPROM.read(5);
OffHour = EEPROM.read(6);
OffMin = EEPROM.read(7);
tdsval = 10 * EEPROM.read(8);
timearro = EEPROM.read(9);
Serial.println(maxteau);
Serial.println(minteau);
Serial.println(OnHour);
Serial.println(OnMin);
Serial.println(OffHour);
Serial.println(OffMin);
Serial.println(tdsval);
Serial.println(timearro);
//=========================================Executé au
demmarage============================
void setup() {
Serial.begin(9600);
delay(1);
Serial1.begin(115200);
delay(1);
Serial.print("Initializing SD card...");
delay(1);
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
while (1);
}
Serial.println("card initialized.");
dht.begin();
sensors.begin();
pinMode(TdsSensorPin, INPUT);
pinMode(RELAY1, OUTPUT);
pinMode(POMPES, OUTPUT);
pinMode(LAMPES, OUTPUT);
pinMode(Tbox, INPUT);
pinMode(moteurA_1, OUTPUT);
pinMode(moteurB_1, OUTPUT);
pinMode(moteurA_2, OUTPUT);
pinMode(moteurB_2, OUTPUT);
digitalWrite(POMPES, HIGH);
digitalWrite(moteurA_1, LOW);
digitalWrite(moteurA_2, LOW);
digitalWrite(moteurB_1, LOW);
digitalWrite(moteurB_2, LOW);
digitalWrite(DS1302_GND_PIN, LOW);
pinMode(DS1302_GND_PIN, OUTPUT);
digitalWrite(DS1302_VCC_PIN, HIGH);
pinMode(DS1302_VCC_PIN, OUTPUT);
LedState();
startMillis1 = millis();
startMillis = millis();
lcd.init();
lcd.createChar(0, Heart);
lcd.createChar(1, tete1);
lcd.createChar(2, tete2);
lcd.createChar(3, tete3);
lcd.createChar(4, tete4);
lcd.createChar(5, bas1);
lcd.createChar(6, bas2);
lcd.createChar(7, bas3);
lcd.createChar(8, bas4);
lcd.backlight();
lcd.setCursor(0, 0);
void setpompe() {
timearro = EEPROM.read(9);
currentMillis1 = millis(); //get the current "time" (actually the number of milliseconds
since the program started)
if (currentMillis1 - startMillis >= (1000 * 60 * timearro) ) {
digitalWrite(POMPES, !digitalRead(POMPES)); //if so, change the state of the LED.
Uses a neat trick to change the state
startMillis = currentMillis1; //IMPORTANT to save the start time of the current LED
state.
}
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
void parseData() {
strtokIndx = strtok(tempChars, ","); // this continues where the previous call left off
integerFromPC = atoi(strtokIndx);
void showParsedData() {
if (integerFromPC == 1) {
digitalWrite(LAMPES, HIGH);
EEPROM.update(addr, 1);
integerFromPC = 250;
}
if (integerFromPC == 0) {
digitalWrite(LAMPES, LOW);
EEPROM.update(addr, 2);
integerFromPC = 250;
}
if (integerFromPC == 4) {
digitalWrite(POMPES, HIGH);
integerFromPC = 250;
}
if (integerFromPC == 5) {
digitalWrite(POMPES, LOW);
integerFromPC = 250;
}
if (integerFromPC == 9 && int1 != 0 ) {
EEPROM.update(9, timearro);
integerFromPC = 250;
int1 = 0;
}
}
void formulair () {
if (integerFromPC == 6 && int1 != 0 && int2 != 0) {
int maxteau = int1;
int minteau = int2;
EEPROM.update(2, maxteau);
EEPROM.update(3, minteau);
Serial.println(maxteau);
Serial.println(minteau);
integerFromPC = 250;
int1 = 0;
int2 = 0;
}
}
void formulair1 () {
if (integerFromPC == 7 && int3 != 0 ) {
int OnHour = int3;
int OnMin = int4;
int OffHour = int5;
int OffMin = int6;
EEPROM.update(4, OnHour);
EEPROM.update(5, OnMin);
EEPROM.update(6, OffHour);
EEPROM.update(7, OffMin);
Serial.println(OnHour);
Serial.println(OnMin);
Serial.println(OffHour);
Serial.println(OffMin);
integerFromPC = 250;
}
}
void tdsva () {
if (integerFromPC == 8 && int1 != 0 ) {
int tdsval = int1;
EEPROM.update(8, tdsval);
Serial.println(tdsval * 10);
integerFromPC = 250;
}
}
void settds() {
int tdsval = 10 * EEPROM.read(8); //10* valeur epprom car max 256 impossible de
stocker 1000 comme valeur mais 100*10 c'est possible
currentMillis4 = millis(); //get the current "time" (actually the number of milliseconds
since the program started)
if (currentMillis4 - startMillis >= 8000 ) {
digitalWrite(moteurB_1, !digitalRead(moteurB_1)); //if so, change the state of the LED.
Uses a neat trick to change the state
startMillis1 = currentMillis4; //IMPORTANT to save the start time of the current LED
state.
}
previousMillis3 = currentMillis3;
cleanup = true;
}
if (tdsValue >= tdsval && cleanup == true ) {
digitalWrite(moteurB_1, LOW);
digitalWrite(moteurB_2, HIGH);
freshtds = true;
cleanup = false;
perioff = false;
}
if (currentMillis3 - previousMillis3 > nettoyage && perioff == false ) {
digitalWrite(moteurB_1, LOW);
digitalWrite(moteurB_2, LOW);
perioff = true;
}
recvWithStartEndMarkers();
if (newData == true) {
strcpy(tempChars, receivedChars);
// this temporary copy is necessary to protect the original data
// because strtok() used in parseData() replaces the commas with \0
parseData();
showParsedData();
newData = false;
}
state();
sensor();
tdsva();
setpompe();
myRTC.updateTime();
settds();
formulair();
formulair1();
timmer();
data();
flcd();
average();
setwater();
}
void state() {
maxteau = EEPROM.read(2);
minteau = EEPROM.read(3);
OnHour = EEPROM.read(4);
OnMin = EEPROM.read(5);
OffHour = EEPROM.read(6);
OffMin = EEPROM.read(7);
tdsval = 10 * EEPROM.read(8);
timearro = EEPROM.read(9);
analog.update();
ledstate = digitalRead(LAMPES);
pompestate = digitalRead(POMPES);
}
void sensor() {
sensors.requestTemperatures();
temperature = sensors.getTempCByIndex(0);
humi = dht.readHumidity();
temp = dht.readTemperature();
valeur_brute = analog.getValue();
tbox = valeur_brute * (5.0 / 1023.0 * 100.0);
}
void setwater() {
if (temperature >= maxteau && temperature != -127 && temperature != 0)
{
digitalWrite(RELAY1, HIGH);
}
else if (temperature <= minteau && temperature != -127 && temperature != 0)
{
digitalWrite(RELAY1, LOW);
}
else {
;
}
}
void average() {
static unsigned long analogSampleTimepoint = millis();
if (millis() - analogSampleTimepoint > 40U) //every 40 milliseconds,read the analog value
from the ADC
{
analogSampleTimepoint = millis();
analogBuffer[analogBufferIndex] = analogRead(TdsSensorPin); //read the analog value
and store into the buffer
analogBufferIndex++;
if (analogBufferIndex == SCOUNT)
analogBufferIndex = 0;
}
static unsigned long printTimepoint = millis();
if (millis() - printTimepoint > 800U)
{
printTimepoint = millis();
for (copyIndex = 0; copyIndex < SCOUNT; copyIndex++)
analogBufferTemp[copyIndex] = analogBuffer[copyIndex];
averageVoltage = getMedianNum(analogBufferTemp, SCOUNT) * (float)VREF / 1024.0;
// read the analog value more stable by the median filtering algorithm, and convert to
voltage value
float compensationCoefficient = 1.0 + 0.02 * (temperature - 25.0); //temperature
compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
float compensationVolatge = averageVoltage / compensationCoefficient; //temperature
compensation
tdsValue = (133.42 * compensationVolatge * compensationVolatge *
compensationVolatge - 255.86 * compensationVolatge * compensationVolatge + 857.39 *
compensationVolatge) * 0.5; //convert voltage value to tds value
}
}
void recorddata() {
}
}
void timmer() {
if (myRTC.hours == OnHour && myRTC.minutes == OnMin ) {
EEPROM.update(addr, 1);
digitalWrite(LAMPES, HIGH);
delay(5);
}
else if (myRTC.hours == OffHour && myRTC.minutes == OffMin ) { // add &&
myRTC.minutes == OnMin ; (myRTC.hours == OffHour && myRTC.minutes ==
OffMin){
EEPROM.update(addr, 2);
digitalWrite(LAMPES, LOW);
delay(5);
}
}
void data() {
if (integerFromPC == 3) {
Serial1.print("<");
Serial1.print(ledstate);
Serial1.print(",");
Serial1.print(pompestate);
Serial1.print(",");
Serial1.print(tdsValue, 0);
Serial1.print(",");
Serial1.print(temp, 2);
Serial1.print(",");
Serial1.print(temperature, 2);
Serial1.print(",");
Serial1.print(humi, 2);
Serial1.print(",");
Serial1.print(tbox, 2);
Serial1.print(",");
Serial1.print(tdsval);
Serial1.print(",");
Serial1.print(OnHour);
Serial1.print(",");
Serial1.print(OnMin);
Serial1.print(",");
Serial1.print(OffHour);
Serial1.print(",");
Serial1.print(OffMin);
Serial1.print(",");
Serial1.print(maxteau);
Serial1.print(",");
Serial1.print(minteau);
Serial1.print(",");
Serial1.print(timearro);
Serial1.print(">");
Serial1.println("");
}
}
void flcd() {
lcd.setCursor(0, 0);
lcd.print("T Eau:");
lcd.print(temperature, 1);
lcd.print((char)223);
lcd.setCursor(12, 0);
lcd.print("Hum:");
lcd.print(humi, 0);
lcd.print(" % ");
lcd.print("AP Grow Box V1");
lcd.print(" ");
lcd.write(byte(1));
lcd.write(byte(2));
lcd.write(byte(3));
lcd.write(byte(4));
lcd.setCursor(0, 1);
lcd.print("T Air:");
lcd.print(temp, 1);
lcd.print((char)223);
lcd.setCursor(12, 1);
lcd.print("TDS:");
lcd.print(tdsValue, 0);
lcd.print(" ppm ");
lcd.print("T Box:");
lcd.print(tbox, 1);
lcd.print((char)223);
lcd.print(" ");
lcd.write(byte(5));
lcd.write(byte(6));
lcd.write(byte(7));
lcd.write(byte(8));
lcd.scrollDisplayLeft();
}
86) Arduino Nano 7SEG Clock + Temp + Humid
COMPONENTS AND SUPPLIES
× 4
Arduino Nano R3
× 1
DHT22 Temperature Sensor
SCHEMATICS
CODE
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <SevSeg.h>
DHT dht(A2,DHT22);
SevSeg Display;
char text[10][6];
int i = 0;
unsigned long timer;
//----------------------SET OROLOGIO
const unsigned long period = 1000; //durata 1 sec.
const unsigned long led_period = 500; //durata lampeggio :
unsigned long startMillis;
unsigned long led_startMillis;
unsigned long currentMillis;
unsigned long led_currentMillis;
const int hrs_btn = A0; //set ore
const int min_btn = A1; //set minuti
const int ledPin = 13; //pin lampeggio :
int Hrs = 0;
int Min = 0;
int Sec = 0;
int Time = 0000;
int ledState = HIGH;
void setup() {
pinMode(hrs_btn, INPUT_PULLUP);
pinMode(min_btn, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
byte numDigits = 4;
byte digitPins[] = {12, 10, 9, 11};
//byte digitPins[] = {11, 9, 10, 12};
byte segmentPins[] = {2, 3, 4, 5, 6, 7, 8,0};
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_CATHODE; // See README.md for options
bool updateWithDelays = false; // Default 'false' is Recommended
bool leadingZeros = true; // Use 'true' if you'd like to keep the leading zeros
bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or isn't
connected
Display.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
updateWithDelays, leadingZeros, disableDecPoint);
Display.setBrightness(100);
dht.begin();
pinMode(ledPin, OUTPUT); // PIN 13 lampeggio :
pinMode(A2, INPUT); // input DHT22
}
void loop()
{
char mychar[ ] = "ORA";
float hu = dht.readHumidity();
float t = dht.readTemperature();
float orario = Time;
orario=orario*10;
String c = String (orario); //memorizza ora
String d = c.substring (0,4); //memorizza cifra a 4 digit
d.toCharArray(text[2],5); //visualizza come 2 (ARRAY)
t=t*10;
String k = String(t); //memorizza t
String r = k.substring (0,3)+"*"; //memorizza cifra a 3 digit + C
r.toCharArray(text[3],5); //visualizza come 3 (ARRAY)
hu=hu*10;
String A = String(hu); //memorizza hu
String B = A.substring(0,3)+"h"; //memorizza cifra a 3 digit
B.toCharArray(text[4],5); // visualizza come 4 (ARRAY)
switch (i)
{
case 1:
digitalWrite(ledPin, LOW); //pin 13 on Humid
break;
case 2:
digitalWrite(ledPin, HIGH); //pin 13 off ORA
break;
case 3:
digitalWrite(ledPin, LOW); //orario
Display.setNumber(Time);
if (digitalRead(hrs_btn) == LOW){goto X;}
if (digitalRead(min_btn) == LOW){goto X;}
break;
case 4:
digitalWrite(ledPin, LOW); //gradi
break;
}
if (millis() > (timer + 6000)) //tempo di visualizzazione
{
switch(i);
Display.setChars(text[i]);
i++;
if (i >= 5) i = 1; // (ARRAY)conta fino a 5 poi torna a 1
timer = millis();}
//--------------------------------OROLOGIO
X: currentMillis = millis();
if (currentMillis - startMillis >= period)
{
Sec = Sec + 1;
startMillis = currentMillis;
}
led_currentMillis = millis();
if (led_currentMillis - led_startMillis >= led_period)
{ led_startMillis = led_currentMillis;
Display.refreshDisplay();
}
87) Interface I2C 16X2 LCD with Arduino
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
× 1
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
Devices++;
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (Devices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
delay(5000);
}
Upload the I2C Scanner Code to Arduino Uno.
Step- 2
If you have a I2C LCD please skip this step. But if you have a 16x2
LCD and a I2C Module see the step to connect this module to LCD.
Connection
First solder the I2C Module. There is no label on the I2C Module for
connecting to 16x2 LCD. So solder it with the help of the image given
below
SCHEMATICS
CODE
void setup()
{
lcd.begin();
lcd.backlight();
lcd.clear();
lcd.setCursor(4,0);
lcd.print("Hackster");
}
void loop()
{
}
88) Lego Gun Shooter with and Arduino
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
A program that runs Arduino Code on Mac,
Windows, and Linux Devices.
Servo countServo;
Servo countServo2;
Servo countServo3;
Servo countServo4;
void setup() {
Serial.begin(9600);
countServo.attach(7);
countServo.write(180);
delay(700);
countServo.write(0);
delay(700);
countServo.write(180);
countServo2.attach(8);
countServo2.write(180);
delay(700);
countServo2.write(0);
delay(700);
countServo2.write(180);
countServo3.attach(6);
countServo3.write(180);
delay(700);
countServo3.write(0);
delay(700);
countServo3.write(180);
countServo4.attach(9);
countServo4.write(180);
delay(700);
countServo4.write(0);
delay(700);
countServo4.write(180);
}
void loop() {
{
countdownServo();
}
delay(100);
{
countdownServo2();
}
delay(100);
{
countdownServo3();
}
delay(100);
{
countdownServo4();
}
}
void countdownServo() {
int halfseconds = 5;
countServo.write((int)(i * 4.5));
delay(500);
}
countServo.write(180);
delay(700);
}
void countdownServo2() {
int halfseconds = 5;
countServo2.write((int)(i * 4.5));
delay(500);
}
countServo2.write(180);
delay(700);
}
void countdownServo3() {
int halfseconds = 5;
countServo3.write((int)(i * 4.5));
delay(500);
}
countServo3.write(180);
delay(700);
void countdownServo4() {
int halfseconds = 5;
countServo4.write((int)(i * 4.5));
delay(500);
}
countServo4.write(180);
delay(700);
}
89) DIY Arduino Height Measuring Machine
Alphanumeric LCD, 16 x 2
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
When I noticed that my kids were measuring their height every day, I
got the idea to make such a device. To find out your height, all you
have to do is stand under the device and activate a sound that indicates
that your height has been measured.
It is very easy to build and consist only a few components:
-Arduino Nano
-HC SR04 ultrasonic sensor
-LCD display
-Buzzer
-Battery
Now let's explain how it works:
First we need to install the device with the help of double-sided
adhesive at a certain height, which is previously defined in the code,
and is marked with the letter H on the picture
When someone stands under the device, the sensor measures the
distance D. Next the code calculates the distance H-D which actually
represents the height of the person under the device H1 and displays
this value on the LCD. Library "LcdBarGraph" helps draw horizontal
bargraph, where the length of the bar is proportional to the values
provided. When there is no one under the device, the calculated value
is zero because in this case H = D and H-D is zero. The device is
mounted in a suitable box with the LCD on the front and the ultrasonic
sensor on the bottom.
.
SCHEMATICS
CODE
// Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
// Write a pulse to the HC-SR04 Trigger Pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
} else {
noTone (speakerPin);
}
lcd.setCursor(0,0);
lcd.print("HEIGHT: ");
lcd.print(distance1);
lcd.print(" cm ");
NSA1166
× 1
× 6
Breadboard (generic)
× 1
× 1
× 1
However, unlike the modern Serial displays it does not have a built-in
controller or a SPI interface - this means that Arduino pins need to be
connected to each segment (7) and a select pin for each digit (6). The
LED display is illuminated by the Arduino continually strobing across
each digit in order, and setting the right segments for that digit for just
a fraction of a second. If the Arduino sketch stops doing this, the
display will go blank or flicker.
Keeping the lights on
Of course, it's being driven by an Arduino MKR WiFi 1010 so there is
some Internet connected fun that could be had.
But fetching some data from the Internet takes time, and waiting for the
operation to complete means the display would go blank. A way to
solve this is to use timer-based interrupts in order to continually update
the LED display in the background.
SCHEMATICS
CODE
SevSegPlus ledDisplay;
void setup()
{
ledDisplay.begin();
}
void loop()
{
ledDisplay.print(" Hi ");
delay(1000);
ledDisplay.print("There ");
delay(1000);
}
91) Arduino Battery Capacity Tester
COMPONENTS AND SUPPLIES
× 1
× 2
× 1
prototyping pc board
× 1
wire
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
solder
diagonal cutters
APPS AND ONLINE SERVICES
Arduino IDE
I have, for a long while, avoided the use of Li-Ion type batteries, owing
to the cost and special charging profiles needed. Now that the
technology is more mature, I am venturing into their use.
Since my supply of cells will be primarily used stock from various
recycle streams, I needed to come up with the tools to test each cell.
With that in mind, here's my derivative of this tester.
What I did
The main changes I did are the 20x4 LCD rather than buying a Nokia
5110 that the original author used. I also used the I2C/TWI/SPI
interface board for the LCD screen.
Note that the SCL and SDA pins are NOT broken out on the pro mini,
they are on the A5 and A4 pins, as noted in the sketch.
Any MOSFET capable of 2.5A constant current or better can be used,
best to use one with the lowest Rds on that you can. The one used here
actually has a fairly high Rds on of 2.4 Ohm typical. This may actually
skew the mAh results. This means that my cells may have a slight bit
higher storage capacity than indicated. I had these on hand, left over
from a previous project. This particular HEXFET/MOSFET is SMD,
but the gate and source pins line up with the .1" spacing on a
protoboard. Easy to solder, and even gives a few vias under the drain
tab to add a heat sink under the board if needed.
Bad pic, and bad solder job... got it twisted a bit. The resistor is a pull-
down on the gate.
The odd headers for the speaker and LCD are recycled from an old
printer I tore apart. I used a 6 position female header section for the
load resistor, so I can change the load if I need to. I just have to
remember to change the code to match whatever I use. 3 position on
each end are paralleled, so I can match resistance to whatever load mA
I want to use according to the type of cell I'm testing.
Lower right screw block is for 5V power in, upper left block is test cell
connection.
The rat's nest of point to point wiring to make the connections. Maybe I
should have used several different colors to make it easier to trace
should I have a problem later on.
The I2C/TWI/SPI interface board. Cheap on eBay, or Aliexpress, as
long as you don't mind waiting 4-6 weeks for delivery. Can be bought
anywhere worldwide online.
Second view of the LCD, showing the changes from the title image.
Still to do is a case for it, might even need to change the screw blocks
out for something else.
SCHEMATICS
CODE
/*
* Li-Ion capacity tester.
* set up:
* 8 Ohm discharge load
* ~190mA discharge rate.
* I2C LCD.
* MOSFET for discharge control.
* SCl pin = A5
* SDA pin = A4
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//LCD set-up
LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 20 chars and 4 line
lcd
// definitions
#define STATE_WAITING 0
#define STATE_MEASURING 1
#define STATE_MEASURING_ENDED 2
#define BAT_LI 0
#define BAT_NI 1
#define BAT_UNREC 2
#define BAT_LI_DISCHARGED 3
//variables
void setup()
{
pinMode(FET_Base,OUTPUT);
pinMode(button,INPUT); //can be changed in the circuit to active low,
// will need to turn on the internal pull-up
pinMode(speaker,OUTPUT);
digitalWrite(FET_Base,LOW);
noTone(speaker);
lcd.init();
lcd.backlight();
}
void loop()
{
if (state==STATE_MEASURING)
{
vtgBatUnloaded=analogRead(0)*5.0/1024.0; //get the voltage of UNLOADED battery
if (vtgBatUnloaded<cutoff)
{
state=STATE_MEASURING_ENDED;
DischargeAllowed=false;
for (uint8_t i=0;i<4;++i)
{tone(speaker,2000,500); delay(500);noTone(5);delay(300);}
}
digitalWrite(FET_Base,HIGH); //turn the MOSFET on
delay(1000);
vtgBatLoaded=analogRead(0)*5.0/1024.0; //get the voltage of LOADED battery
vtgLoad=analogRead(1)*5.0/1024.0;
digitalWrite(FET_Base,LOW);//turn the MOSFET off
vtgDropOnLoad=vtgBatLoaded-vtgLoad;
if(vtgDropOnLoad>0) batCurrent=vtgDropOnLoad/rLoad;
else batCurrent=0;
vtgDropRin=vtgBatUnloaded-vtgBatLoaded;
if(batCurrent>0) rIn=vtgDropRin/batCurrent;
else rIn=0;
mAh+=batCurrent/3.6; //*1000.0/3600.0;
lcd.clear();
lcdState();
lcd.setCursor(0,0);
lcd.print(" Bat Load I ");
lcd.setCursor(0,1);
lcd.print(vtgBatUnloaded); lcd.print("V ");lcd.print(vtgBatLoaded); lcd.print("V
");lcd.print(batCurrent); lcd.print("A");
lcd.setCursor(0,2);
lcd.print("Rin= "); lcd.print(rIn); lcd.setCursor(11,2); lcd.print(" Ohm");
lcd.setCursor(0,3);
lcd.print("Cap= "); lcd.print(mAh); lcd.print(" mA/h");
delay(500);
}
else if (state==STATE_WAITING)
{
digitalWrite(FET_Base,LOW);//turn the MOSFET off
vtgBatUnloaded=analogRead(0)*5.0/1024.0; //get the voltage of UNLOADED battery
DefBatteryType();
lcd.clear();
lcdState();
lcd.setCursor(0,0);
lcd.print("Bat= "); lcd.print(vtgBatUnloaded); lcd.print(" V");
lcd.setCursor(0,1);
lcd.print(BatTypeString);
lcd.setCursor(0,2);
lcd.print("Test ");
if (DischargeAllowed) lcd.print("allowed");
else lcd.print("denied");
CheckButtons();
delay(500);
}
else if (state==STATE_MEASURING_ENDED)
{
digitalWrite(FET_Base,LOW);//turn the MOSFET off
vtgBatUnloaded=analogRead(0)*5.0/1024.0; //get the voltage of UNLOADED battery
lcd.clear();
lcdState();
lcd.setCursor(0,0);
lcd.print("Bat= "); lcd.print(vtgBatUnloaded); lcd.print(" V");
lcd.setCursor(0,1);
lcd.print("Cap= ");lcd.print(mAh); lcd.print(" mA/h");
CheckButtons();
delay(500);
}
}
void CheckButtons(void) {
void lcdState(void){
String stateString;
lcd.setCursor(0,0);
if(state==STATE_WAITING) stateString="Waiting ";
if(state==STATE_MEASURING) stateString="Measuring ";
if(state==STATE_MEASURING_ENDED) stateString="Measuring done";
lcd.print(stateString);
}
void DefBatteryType(void){
if (vtgBatUnloaded>LiCutoffVtg&&vtgBatUnloaded<LiChargedVtg)
{BatteryType=BAT_LI; DischargeAllowed=true;BatTypeString="Li-ion
battery";cutoff=LiCutoffVtg;}
if (vtgBatUnloaded>NiCutoffVtg&&vtgBatUnloaded<NiChargedVtg)
{BatteryType=BAT_NI; DischargeAllowed=true;BatTypeString="Ni-MH battery
";cutoff=NiCutoffVtg;}
if (vtgBatUnloaded<LiCutoffVtg&&vtgBatUnloaded>NiChargedVtg)
{BatteryType=BAT_LI_DISCHARGED; DischargeAllowed=false;BatTypeString="Li-ion
battery";}
if (vtgBatUnloaded<NiCutoffVtg||vtgBatUnloaded>LiChargedVtg)
{BatteryType=BAT_UNREC; DischargeAllowed=false;BatTypeString="UNKNOWN bat
";}
}
92) Arduino RFID Controlled Light Switch
COMPONENTS AND SUPPLIES
Arduino Nano R3
× 1
CODE
// define constants for pins
#include <SoftwareSerial.h>
int green_LED = 3;
int RELAY = 5;
int red_LED = 4;
int white_LED = 12;
void setup()
{
Serial.begin(9600);
ssrfid.begin(9600);
ssrfid.listen();
pinMode(green_LED, OUTPUT);
pinMode(RELAY, OUTPUT);
pinMode(red_LED, OUTPUT);
pinMode(white_LED, OUTPUT);
digitalWrite(green_LED, LOW);
digitalWrite(RELAY, LOW);
digitalWrite(red_LED, LOW);
digitalWrite(white_LED, HIGH);
initAuthorizedTags();
}
int checkTag() // check if the tag ID we just read is any of the authorized tags
{
int i;
for (i = 0; i < 10; ++i)
{
if (strcmp(authorizedTags[i], tagId) == 0)
{
return 1;
}
}
return 0;
}
void parseTag() // convert the int values read from serial to ASCII chars
{
int i;
for (i = 0; i < 10; ++i)
{
tagId[i] = readData[i];
}
tagId[10] = 0;
}
void printTag()
{
Serial.print("Tag value: ");
Serial.println(tagId);
}
void tagFailed() // inform the user that the tag is not authorized
{
Serial.println("Unauthorized access!");
digitalWrite(green_LED, LOW); // put the green LED low
digitalWrite(red_LED, HIGH); // put the red LED high, signal for unauthorized tag
delay(2000);
if ((ON_OFF % 2) != 0)
{
digitalWrite(green_LED, HIGH); // if tag fail and the light is on, green LED will be put
back high
}
}
void clearSerial() // this function clears the rest of data on the serial, to prevent
multiple scans
{
while (ssrfid.read() >= 0)
{
; // do nothing
}
}
void loop()
{
// turn red LED off
digitalWrite(red_LED, LOW);
if (ssrfid.available() > 0)
{
readVal = ssrfid.read(); // read the incoming byte:
if (readVal == 2) // a "2" signals the beginning of a tag
{
counter = 0; // start reading
}
else if (readVal == 3) // a "3" signals the end of a tag
{
processTag(); // process the tag we just read
clearSerial(); // clear serial to prevent multiple reads
counter = -1; // reset reading state
}
else if (counter >= 0) // if we are in the middle of reading a tag
{
readData[counter] = readVal; // save valuee
++counter; // increment counter
}
}
× 1
SCHEMATICS
CODE
const int FSR_PIN = A0; // Pin connected to FSR/resistor divider
const int LED_PIN1 = 7;
const int LED_PIN2 = 6;
const int LED_PIN3 = 4;
const float VCC = 4.98; // Measured voltage of Ardunio 5V line
const float R_DIV = 3230.0; // Measured resistance of 3.3k resistor
void setup()
{
Serial.begin(9600);
pinMode(FSR_PIN, INPUT);
pinMode(LED_PIN1, OUTPUT);
pinMode(LED_PIN2, OUTPUT);
pinMode(LED_PIN3, OUTPUT);
}
void loop()
{
int fsrADC = analogRead(FSR_PIN);
// If the FSR has no pressure, the resistance will be
// near infinite. So the voltage should be near 0.
if (fsrADC != 0) // If the analog reading is non-zero
{
// Use ADC reading to calculate voltage:
float fsrV = fsrADC * VCC / 1023.0;
// Use voltage and static resistor value to
// calculate FSR resistance:
float fsrR = R_DIV * (VCC / fsrV - 1.0);
Serial.println("Resistance: " + String(fsrR) + " ohms");
// Guesstimate force based on slopes in figure 3 of
// FSR datasheet:
float force;
float fsrG = 1.0 / fsrR; // Calculate conductance
// Break parabolic curve down into two linear slopes:
if (fsrR <= 600)
force = (fsrG - 0.00075) / 0.00000032639;
else
force = fsrG / 0.000000642857;
Serial.println("Force: " + String(force) + " g");
Serial.println();
if(force<10)
{
digitalWrite(LED_PIN1,LOW);
digitalWrite(LED_PIN2,LOW);
digitalWrite(LED_PIN3,LOW);}
if(force>20)
{
digitalWrite(LED_PIN1,HIGH);
digitalWrite(LED_PIN2,LOW);
digitalWrite(LED_PIN3,LOW);
}
if(force>60)
{
digitalWrite(LED_PIN2,HIGH);
digitalWrite(LED_PIN1,LOW);
digitalWrite(LED_PIN3,LOW);
}
if(force>100)
{
digitalWrite(LED_PIN3,HIGH);
digitalWrite(LED_PIN2,LOW);
digitalWrite(LED_PIN1,LOW);
}
delay(500);
}
else
{
// No pressure detected
}
}
× 1
1Sheeld
× 1
Fan 12V
× 1
LED strips
× 1
Push Button
× 1
Android Smartphone
× 1
Relay Module 5V
× 1
APPS AND ONLINE SERVICES
Twitter
Q : Do you have clothes, shoes, books and ...etc that you no longer
want ?
A : Sure!
Q : What happens to these things? Stored for along time in your closet?
A : Yes :(
Now, pick these things you no longer want, and take them to the
nearest donation machine :)
Simply, the machine will sense if you donated with something and will
ask you if you want to share your photo on the machine's twitter
account to encourage your friends to donate and know more about the
machine. Also when filled the machine will send a SMS message to a
charity association representative to ask him to empties the machine.
This machine is totally open source so you can build your own machine
at your district :) and i will be pleased if you shared your kindly
feedback to enhance the second version.You can download all the
needed files starting from the CAD files to the Arduino code, Enjoy :D
By the way, the machine was featured in a national TV show that
discuss out of the box solutions for enhancing our community.
Step 1: What you will need?
Materials:
1. MDF (8mm) Sheets
2. MDF (5mm) Sheets
3. Knotty pine wood
4. Stickers for the outer finish
5. Black Paint
6. Primer paint
7. Aluminum Bars
8. Hinge L3899-2B
Tools:>1. Screwdrivers>
2. Hammer
3. Pliers
4. Flush cutter
5. Wire Stripper
6. Soldering Iron
7. Soldering Iron Stand
8. Solder
9. De-soldering pump
10. Digital Multimeter
11. Double Sided Glue Tape.
12. Nails and adhesive
13. Screws & Nuts
14. M4 Bolts x 20mm
15. Copper spacers ( To fix the Arduino Board)
16. Nylon Cable Tie Belt
17. Stainless steel angle brackets
18. 3" Rubber Caster Wheels
19. Paint brush
20. Circular saw
21 Table saw
22. Jig Saw
23. Drill and bits
24. Laser cutter
25. CNC
26. Wood files
27. Sand paper
28. Air compressor with nail gun
Electronics:>1. Arduino UNO
2. 1Sheeld
3. Power Supply 12V/ 5A
4. Fan 12v
5. LED strips
6. Bush button
7. Android Smart Phone
8. Relay module 5V
Step 2: Building The Machine Frame
https://www.youtube.com/embed/Eu4tEww3dzw?feature=oembed
1. We used the pine wood to build the machine's frame then we used
MDF sheets to cover the machine's frame, we used nails and screws to
fix the MDF sheets to cover the machine's frame.Machine's dimensions
is : 170 * 100 * 80 cm
2. We used aluminum sections to create the machine's door and we
covered it using MDF sheets. we used laser cutter machine to cut the
machine's door.
3. We used 3 hinges(L3899-2B) to fix the machine's door to the
machine's body.
4. We used 4 x 3" Rubber Caster Wheels to make it movable.
5. We added a lock to secure the machine.
6. Then we started to prepare the machine for painting, we can't paint
MDF directly you should coat the machine with primer then we used
black paint for the final layer.
7. After the machine has dried we used the designed stickers to give the
machine the final finish and we used aluminum angels in the corners to
support the machine and protect the stickers.
Step 3: The Machine's Exterior Design
SCHEMATICS
CODE
#define CUSTOM_SETTINGS
#define INCLUDE_TERMINAL_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_TWITTER_SHIELD
#define INCLUDE_CAMERA_SHIELD
#define INCLUDE_TEXT_TO_SPEECH_SHIELD
//--------------------------------------------------------------------------------------
void setup() {
// Start communication
OneSheeld.begin();
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin2, OUTPUT);
void loop()
{
long duration1, distance1, duration2, distance2;
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
Terminal.print("Ultrasonic1 = ");
Terminal.print(distance1);
Terminal.println(" cm");
Terminal.print("Ultrasonic2 = ");
Terminal.print(distance2);
Terminal.println(" cm");
// Ultrasonic sensor measeures the depth of the machine if this distance1 increased above
100 cm this means that the door is opened
// The machine will tell the user to stand in front of the camera then the machine will take a
photo for him and uplaoad it on twitter
if (distance1 < 40) {
Terminal.println("Machine is filled");
else
{
// Reset the flag
isMessageSent = false;
// Wait for 5 seconds while the user stand in front of the camera
TextToSpeech.say("Please stand in front of the camera After Your donation");
OneSheeld.delay(5500);
TextToSpeech.say("If you want to share you photo with community please long press the
Bush button");
OneSheeld.delay(7500);
if (buttonState == HIGH) {
TextToSpeech.say("You have pressed the push button Please stand behind the red line");
OneSheeld.delay(6000);
Camera.setFlash(ON);
// Take the picture.
Camera.rearCapture();
Terminal.println("Photo taken");
OneSheeld.delay(3000);
TextToSpeech.say("Yor photo has been taken");
OneSheeld.delay(7000);
× 1
CASE200x120x75mm Plastic
Electronic Project Cover Enclosure × 1
Green Round Cap Push Button
Switch × 1
AC 16A/250V 20A/125V
Illuminated SPST Boat Rocker
Switch × 1
EasyEDA
LibreCAD
Overview
Controls
On switching on power, our station in standby mode. It is mean that heater
do not connected and you can see iron handle current temperature on LED
display.
To start working need a long press on button 3 (Mode/ Standby). After this
station enters to last working mode stored in EEPROM memory.
There is two working mode named "CLASS 1" and "CLASS 2".
CLASS 1 is temperature control working mode. It is possible to set
desired temperature by two buttons 1 and 2 (UP and DOWN). Short press
change units for 1 and long press for 5. These values you can change in
sketch file:
const byte pinHeater = 2; //pin for irf520 module
const uint16_t minTemp = 50;//temperature minimum
const uint16_t maxTemp = 700;//temperature maximum
const uint16_t measInterval = 500; //measurement interval ms. over 500
const byte shortPressStep = 1; //temperature step on button's short press
const byte autoPressStep = 5; //temperature step on button's long press
On the right half of LED display you can see defined temperature and in
the left side real temperature of iron readied by thermocouple K-type.
SCHEMATICS
CODE
//-- Libraries include
#include "LedControl.h" //max7219 7 segment display driver
#include "max6675.h" //thermocouple driver
#include "sav_button.h" //buttons library
#include "EEPROM.h" //Memory Storage
//-- PushButtons-----------------------------
const byte pinButtonUp = 4;
const byte pinButtonDown = 5;
const byte pinButtonOk = 6;
SButton Up (pinButtonUp, 50, 0, 800, 100);
SButton Down (pinButtonDown, 50, 0, 800, 100);
SButton Ok (pinButtonOk, 50, 1000, 4000, 250);
byte logo[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77, 0x05, 0x3d,
0x1c, 0x10, 0x15, 0x1d, 0x00, 0x5b, 0x1d, 0x30, 0x3d, 0x4f, 0x05,
0x00, 0x5b, 0x0f, 0x77, 0x0f, 0x10, 0x1d, 0x15, 0x00, 0xed, 0x7e}; //Arduino Solder
station 1_0
byte class1[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4e, 0x0e, 0x77, 0x5b,
0x5b, 0x00, 0x00, 0x30}; //CLASS 1
byte class2[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4e, 0x0e, 0x77, 0x5b,
0x5b, 0x00, 0x00, 0x6d}; //CLASS 2
byte stby[] = {0x5b, 0x0f, 0x1f, 0x3b, 0x00, 0x00, 0x00, 0x00}; //STDBY
else {
}
led.setDigit(0, 1 + 4 * group, ones, false);
if ( tens==0 && hundreds==0) led.setChar(0,2+4*group, ' ', false);
else led.setDigit(0, 2 + 4 * group, tens, false);
if (hundreds == 0) led.setChar(0, 3 + 4 * group, ' ', false);
else led.setDigit(0, 3 + 4 * group, hundreds, false);
}
}
// Read config from EEPROM
void readConf(){
uint16_t t;
byte p, m;
EEPROM.get(tempAddr, t);
if (minTemp<=t && t<=maxTemp) reqTemp = t;
EEPROM.get(powerAddr, p);
if (p>=0 && p<=100) power = p;
EEPROM.get(modeAddr, m);
if (m==0 || m==1) mode = m;
}
switch (mode){
case 0:
if ((reqTemp - vStep) >= minTemp) {
reqTemp -= vStep;
isChanged = true;
}
break;
case 1:
if ((int(power) - int(vStep)) >= 0) {
power -= vStep;
isChanged = true;
}
break;
}
}
void standByMode(){
SoftPWMSet(pinHeater,0);
led.setIntensity(0, 1);
for (byte i=0; i<5; i++) led.setRow(0,(7-i),stby[i]);
writeInfo(temp, 0, CELSIUS);
switch( Ok.Loop() ){
case SB_LONG_CLICK:
standBy = false;
led.setIntensity(0, 15);
if (mode == 0){
ShowString(class1, sizeof(class1));
isChanged = true;
}
else if (mode == 1){
ShowString(class2, sizeof(class2));
isChanged = true;
}
break;
}
}
void setup() {
led.shutdown(0, false);
led.setIntensity(0,15);
led.clearDisplay(0);
Up.begin();
Down.begin();
Ok.begin();
readConf();
//Serial.begin(9600);
}
void loop() {
if ((millis()-measTime) > measInterval){
temp = tc.readCelsius();
measTime = millis();
// Serial.println(temp);
}
if (standBy) standByMode();
else{
switch( Up.Loop() ){
case SB_CLICK:
unitsUp(shortPressStep);
break;
/*case SB_LONG_CLICK:
break;*/
case SB_AUTO_CLICK:
unitsUp(autoPressStep);
break;
}
switch( Down.Loop() ){
case SB_CLICK:
unitsDown(shortPressStep);
break;
/*case SB_LONG_CLICK:
break;*/
case SB_AUTO_CLICK:
unitsDown(autoPressStep);
break;
}
switch( Ok.Loop() ){
case SB_CLICK:
if (mode == 0){
mode = 1;
ShowString(class2, sizeof(class2));
isChanged = true;
}
else if (mode == 1){
mode = 0;
ShowString(class1, sizeof(class1));
isChanged = true;
}
break;
case SB_LONG_CLICK:
standBy=true;
break;
/*case SB_AUTO_CLICK:
break;*/
}
if (isChanged) {
if (mode == 0) writeInfo(reqTemp, 0, CELSIUS);
if (mode == 1) writeInfo(power, 0, PERCENT);
saveConf();
isChanged = false;
}
setTemp();
writeInfo(temp, 1, CELSIUS);
}
}
× 1
× 1
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
#include <LiquidCrystal.h>
// Integer Bibliothek
int hintergrundLichtPIN = 8; // Hintergrundlicht PIN
int hintergrundLichtWert = 49; // Hintergrund Wert = Höher => Heller
int kontrastPIN = 9; // Kontrast PIN
int kontrastWert = 49; // Kontrast Wert = Kleiner => mehr Kontrast
int analogWert;
void setup() {
// Computer Schnittstellen-Verbindung
Serial.begin(9600);
}
void loop() {
}
97) Smart Home Arduino In 30 Minutes Posting in Ubidots
× 1
LED (green)
× 1
Buzzer
× 1
Note that the scheme used, connect the cathode on GND (ground) and
the anode in a 220 ohm resistor, +/- 5% and turn it to the Arduino pin 4.
We're almost there , the timer tah running there?
Others - Buzzer
The final link is the simplest , used a buzzer , which is triggered when
the PIR sensor recognizes movement in the environment , therefore,
beyond the LED warn visually , have a buzz that warns the presence of
movement, this can be used to control access or as a primitive alarm,
giving the idea of how to integrate all these features at once .
The buzzer has a positive pole , which usually in addition to their
greater attachment terminal, a markup on top ( +) indicating the same
and a negative pole, usually a lower leg GND (ground ) .
The connection is simple, the lower leg binds to the GND (ground ),
and the greater leg (+) in Arduino pin 2 .
Ready, is mounted all the physical part of your Smart Home Mini
system , now let's make the magic happen.
Download the available code , open the Arduino IDE and upload it to
your Arduino and see the operation .
Remember that to send the data from the sensors , need to set in your
account Ubidots the variables will be three variables , humidity ,
temperature and movement , once you have the data of these variables
add fields the indicated code , set data LOCAL NETWORK of its
Ethernet Shield and see how simple it is .
SCHEMATICS
CODE
#include <DHT.h>
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
//SD Card
File dataFiles;
//Declarao das variveis referentes aos pinos digitais - ALARME + PIR.
int pinBuzzer = 2;
int pinSensorPIR = 3;
int pinLed = 4;
int valorSensorPIR = 0;
void setup() {
// start the Ethernet connection using a fixed IP address and DNS server:
Ethernet.begin(mac, ip, myDns);
// print the Ethernet board/shield's IP address:
Serial.print("Conexao com a REDE LOCAL - IP: ");
Serial.println(Ethernet.localIP());
delay(1000);
if (Ethernet.begin(mac) == 0) {
Serial.println("Falha na Conexao com a REDE Local");
// no point in carrying on, so do nothing forevermore:
for(;;);
}
// SD Card - Iniciando
Serial.println("Inicializando SD card...");
if (!SD.begin(4)) {
Serial.println("Falha na Inicializacao do SD Card!");
Serial.println("Falha no Modo DATA LOGGER SD Card!");
return;
}
Serial.println("Inicializacao Completa");
Serial.println("Modo DATA LOGGER Inicializado com Sucesso");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
dataFiles = SD.open("test.txt", FILE_WRITE);
void loop()
{
int value_temperatura = t;
int value_umidade = h;
int value_sensorPIR = valorSensorPIR;
save_value(String(value_temperatura));
save_value_umidade(String(value_umidade));
save_value_sensorPIR(String(value_sensorPIR));
}
}
//Temperatura
client.println("POST /api/v1.6/variables/"+idvariable+"/values HTTP/1.1");
Serial.println("POST /api/v1.6/variables/"+idvariable+"/values HTTP/1.1");
client.println("Content-Type: application/json");
Serial.println("Content-Type: application/json");
client.println("Content-Length: "+String(num));
Serial.println("Content-Length: "+String(num));
client.println("X-Auth-Token: "+token);
Serial.println("X-Auth-Token: "+token);
client.println("Host: things.ubidots.com\n");
Serial.println("Host: things.ubidots.com\n");
client.print(var);
Serial.print(var+"\n");
}
else
{
// if you didn't get a connection to the server:
Serial.println("Falha na Gravacao - Variavel 2 - Temperatura");
}
if (!client.connected())
{
Serial.println();
Serial.println("DESCONECTANDO...");
client.stop();
}
if (client.available())
{
char c = client.read();
Serial.print(c);
}
client.flush();
client.stop();
if (!client.connected())
{
Serial.println();
Serial.println("DESCONECTANDO...");
client.stop();
}
if (client.available())
{
char c = client.read();
Serial.print(c);
}
client.flush();
client.stop();
//Temperatura
client.println("POST /api/v1.6/variables/"+idvariable_sensorPIR+"/values HTTP/1.1");
Serial.println("POST /api/v1.6/variables/"+idvariable_sensorPIR+"/values HTTP/1.1");
client.println("Content-Type: application/json");
Serial.println("Content-Type: application/json");
client.println("Content-Length: "+String(num));
Serial.println("Content-Length: "+String(num));
client.println("X-Auth-Token: "+token);
Serial.println("X-Auth-Token: "+token);
client.println("Host: things.ubidots.com\n");
Serial.println("Host: things.ubidots.com\n");
client.print(var3);
Serial.print(var3+"\n");
}
else
{
// if you didn't get a connection to the server:
Serial.println("Falha na Gravacao - Variavel 1 - Humidade");
}
if (!client.connected())
{
Serial.println();
Serial.println("DESCONECTANDO...");
client.stop();
}
if (client.available())
{
char c = client.read();
Serial.print(c);
}
client.flush();
client.stop();
}
//Alarme de Presena
void ligarAlarme() {
//Ligando o led
digitalWrite(pinLed, HIGH);
if (valorSensorPIR != 1){
desligarAlarme();
}
}
void desligarAlarme() {
//Desligando o led
digitalWrite(pinLed, LOW);
//Desligando o buzzer
noTone(pinBuzzer);
}
Arduino IDE
PowToon
Example situation:
It's raining heavily, winds from the North.
Today you have to work at 9:30 AM, tomorrow at 9:00 AM.
You prefer going by bicycle, and you live more than 10 km away.
In general, you take 40 minutes to prepare yourself.
It's raining, more people will go to their jobs and school by bus, train and
car. If you yourself are still going by bicycle or on foot, this won't affect
you very much, but the opposite is true because of the wind... You'll
probably get slowed down a lot either way!
Let's say that you have to be woken up 10 minutes earlier than normal:
8:20 AM
How we do It
Here you can see how to configure the MFC. (Sorry for the bad quality!)
Currently, you don't see the completed version of the code in the video.
That is because we ran into difficulties quite a lot while making it.
The Arduino UNO we were using did not have sufficient PROGMEM and
RAM for the code. If you try to reproduce, we recommend you use any
board with the same size as the UNO, but with more storage. Also use a
more modern LCD TFT Shield than we did.
The program will ask you the following things:
How long do you usually take to get ready? (In minutes)
What means of transport do you use? (Walk / Bicycle / Car)
Examples of questions that could be added in the future are:
What's the name of your google calendar?
Where do you live?
Where do you work?
Do you want to use the snooze function? How long in between? (In
minutes)
Leave the screen on at all times?
The list goes on and on!
The answers could be saved in the EEPROM of the Arduino, so you don't
need to answer them twice!
When you answered the questions successfully, it will authenticate with
google. Go to the link (provided in the serial monitor) with your favorite
browser. Click on 'Allow'. Now the MFC is connected to your google
account, which allows it you check your calendar.
We expect that the first event in your calendar is 'going to work or school'.
You will be woken up with time to completely prepare yourself in the
morning, and be on time, of course. Your calendar gets checked every 5
minutes, so don't you worry about missing a newly made appointment.
Air Quality
In the images below, you can see the air qualities (top left of the screen). It
can detect 4 grades.
"Goed" / "Good": No worries, you'll sleep well.
"Aanvaardbaar" / "Acceptable": Could be better...
"Slecht" / "Bad": You should open your window...
"Leef je nog?!" / "How are you still alive?!": No explanation needed...
An alarm goes off when the grade gets worse than "Aanvaardbaar" /
"Acceptable". The sound gets louder when the quality degrades.
"Good"
"Acceptable"
"Bad"
SCHEMATICS
CODE
MFC - Air qualityArduino
This code gives a representation of how the air quality and time can
be displayed. This code in combination with 'MFC- Alarm' code is our
finished program.
//-----------------RTC----------------------------//
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 rtc;
enum Dagen {
Zondag,
Maandag,
Dinsdag,
Woensdag,
Donderdag,
Vrijdag,
Zaterdag
};
char scherm_bitbuffer[133];
//-----------------LCD----------------------------//
#include <SparkFunColorLCDShield.h>
#define BACKGROUND WHITE // Achtergrond
#define COLOR BLACK // This is the color of the clock face, and digital clock
#define COLOR_2 BLUE
LCDShield lcd;
char Uur[3];
char Minuten[3];
char Seconden[3];
char Dag[3];
char Maand[3];
char Jaar[3];
char Tijd_Nu[9];
char Tijd_alarm[6];
//-----------------AirQuality---------------------//
#include"AirQuality.h"
#include"Arduino.h"
AirQuality airqualitysensor;
int current_quality =-1;
//-------------------------------------------------------------------------------------//
void setup () {
pinMode(3, OUTPUT);
analogWrite(3, 0);
Serial.begin(9600);
airqualitysensor.init(14);
//-----------------RTC----------------------------//
#ifndef ESP8266
while (!Serial);
#endif
Serial.begin(9600);
if (! rtc.begin()) {
Serial.println("Couldn't find RTC ");
lcd.setStr("Couldn't find RTC ", 20, 10, COLOR, BACKGROUND);
while (1);
}
if (! rtc.isrunning()) {
Serial.println("RTC is NOT running!");
lcd.setStr("RTC werkt niet! ", 20, 10, COLOR_2, BACKGROUND);
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}
}
//-------------------------------------------------------------------------------------//
void loop () {
//tijd.
//weekdag.
lcd.setStr(daysOfTheWeek[now.dayOfTheWeek()], 70, 10, COLOR, BACKGROUND);
//datum.
lcd.setStr(itoa(now.day(), Dag, 10), 103, 10, COLOR, BACKGROUND);
lcd.setStr("/", 101 , 28, COLOR, BACKGROUND);
lcd.setStr(itoa(now.month(), Maand, 10), 103, 37, COLOR, BACKGROUND);
lcd.setStr("/", 101, 55, COLOR, BACKGROUND);
lcd.setStr(itoa(now.year(), Jaar, 10), 103, 61, COLOR, BACKGROUND);
delay(500);
//-----------------airquality---------------------//
current_quality=airqualitysensor.slope();
if (current_quality >= 0) // if a valid data returned.
{
if (current_quality==0) {
lcd.setStr("Leef je nog?! ", 5, 5, COLOR, BACKGROUND);
analogWrite(3, 20);
}
else if (current_quality==1) {
lcd.setStr("Slecht ", 5, 5, COLOR, BACKGROUND);
analogWrite(3, 20);
}
else if (current_quality==2) {
lcd.setStr("Aanvaardbaar ", 5, 5, COLOR, BACKGROUND);
analogWrite(3, 0);
}
else if (current_quality ==3){
lcd.setStr("Goed ", 5, 5, COLOR, BACKGROUND);
analogWrite(3, 0);
}
}
}
ISR(TIMER1_OVF_vect)
{
if(airqualitysensor.counter==61)//set 2 seconds as a detected duty
{
airqualitysensor.last_vol=airqualitysensor.first_vol;
airqualitysensor.first_vol=analogRead(A0);
airqualitysensor.counter=0;
airqualitysensor.timer_index=1;
PORTB=PORTB^0x20;
}
else
{
airqualitysensor.counter++;
}
MFC - AlarmArduino
This code gives a representation of how the prog will work and how
your calendar is read. This code in combination with 'MFC - Air
quality' code is our finished program.
#include <avr/pgmspace.h>
#include <SPI.h>
#include <Temboo.h>
#include <Wire.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include "RTClib.h"
// #include "SparkFunColorLCDShield.h"
//////////////////////////////////////////////////////////////////////////////
char cBuffer_s_0[5];
char cBuffer_s_1[5];
char cBuffer_s_2[34];
char cBuffer_s_3[24];
char cBuffer_s_4[24];
char cBuffer_s_5[24];
char cBuffer_l_0[42];
char cBuffer_l_1[56];
char* cBuffer[8] = {
cBuffer_s_0,
cBuffer_s_1,
cBuffer_s_2,
cBuffer_s_3,
cBuffer_s_4,
cBuffer_s_5,
cBuffer_l_0,
cBuffer_l_1
};
String sBuffer;
String CallbackID;
String AccessToken;
DateTime* AccessToken_Time;
String RefreshToken;
String CalendarID;
DateTime* ReadCalendar_Time;
int Count;
bool Setup;
int MFC_WifiStatus;
WiFiClient MFC_WifiClient(255);
RTC_DS1307 MFC_Time;
DateTime* Now_Time;
// LCDShield MFC_LCDColorShield;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
enum PROGMEMTEXT_LIST {
OK,
FAIL,
ADJUSTED,
UNEXPECTEDERROR,
DAYSOFTHEWEEK_OFFSET,
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRYDAY,
SATURDAY,
MONTHSOFTHEYEAR_OFFSET,
JANUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER,
WALK,
BICYCLE,
CAR,
HTTP_CODE,
HTTP_CODE_SERIALPRINT,
RTC_DETECTION,
RTC_CONFIGURATION,
WIFI_SHIELD,
WIFI_CONNECTION,
WIFI_SSID,
WIFI_PASSWORD,
GOOGLE_INITIALIZEOAUTH,
GOOGLE_FINALIZEOAUTH,
GOOGLE_SEARCHCALENDAR,
GOOGLE_READCALENDAR,
GOOGLE_DISTANCEMATRIX,
ACCOUNT,
APP_NAME,
APP_KEY,
INITIALIZEMFC,
FINALIZEMFC,
SEARCHCALENDARMFC,
READCALENDARMFC,
INITIALIZEOAUTH,
FINALIZEOAUTH,
SEARCHCALENDARSBYNAME,
GETNEXTEVENT,
WALKINGDISTANCEMATRIX,
BICYCLINGDISTANCEMATRIX,
DRIVINGDISTANCEMATRIX,
SCOPE,
SCOPE_VALUE,
CALLBACKID,
// CALLBACKID_VALUE,
CALENDARNAME,
CALENDARNAME_VALUE,
CALENDARID,
//CALENDARID_VALUE,
ACCESSTOKEN,
// ACCESSTOKEN_VALUE,
REFRESHTOKEN,
// REFRESHTOKEN_VALUE,
ORIGIN,
ORIGIN_VALUE,
DESTINATION,
DESTINATION_VALUE,
PROGMEMTEXT_LIST_SIZE
};
PROGMEMTEXT_LIST MeansOfTransport;
unsigned long UserPrepTime;
unsigned long CurrentPrepTime;
////////////////////////////////////////////////////////////////////////////////
PROGMEMTEXT_COMMON_OK,
PROGMEMTEXT_COMMON_FAIL,
PROGMEMTEXT_COMMON_ADJUSTED,
PROGMEMTEXT_COMMON_UNEXPECTEDERROR,
PROGMEMTEXT_COMMON_DAYSOFTHEWEEK_OFFSET,
PROGMEMTEXT_COMMON_SUNDAY,
PROGMEMTEXT_COMMON_MONDAY,
PROGMEMTEXT_COMMON_TUESDAY,
PROGMEMTEXT_COMMON_WEDNESDAY,
PROGMEMTEXT_COMMON_THURSDAY,
PROGMEMTEXT_COMMON_FRYDAY,
PROGMEMTEXT_COMMON_SATURDAY,
PROGMEMTEXT_COMMON_MONTHSOFTHEYEAR_OFFSET,
PROGMEMTEXT_COMMON_JANUARY,
PROGMEMTEXT_COMMON_FEBRUARY,
PROGMEMTEXT_COMMON_MARCH,
PROGMEMTEXT_COMMON_APRIL,
PROGMEMTEXT_COMMON_MAY,
PROGMEMTEXT_COMMON_JUNE,
PROGMEMTEXT_COMMON_JULY,
PROGMEMTEXT_COMMON_AUGUST,
PROGMEMTEXT_COMMON_SEPTEMBER,
PROGMEMTEXT_COMMON_OCTOBER,
PROGMEMTEXT_COMMON_NOVEMBER,
PROGMEMTEXT_COMMON_DECEMBER,
PROGMEMTEXT_COMMON_WALK,
PROGMEMTEXT_COMMON_BICYCLE,
PROGMEMTEXT_COMMON_CAR,
PROGMEMTEXT_COMMON_HTTPCODE,
PROGMEMTEXT_COMMON_HTTPCODESERIALPRINT,
PROGMEMTEXT_COMMON_RTCDETECTION,
PROGMEMTEXT_COMMON_RTCCONFIGURATION,
PROGMEMTEXT_COMMON_WIFISHIELD,
PROGMEMTEXT_COMMON_WIFICONNECTION,
PROGMEMTEXT_COMMON_WIFISSID,
PROGMEMTEXT_COMMON_WIFIPASSWORD,
PROGMEMTEXT_COMMON_GOOGLEINITIALIZEOAUTH,
PROGMEMTEXT_COMMON_GOOGLEFINALIZEOAUTH,
PROGMEMTEXT_COMMON_GOOGLESEARCHCALENDAR,
PROGMEMTEXT_COMMON_GOOGLEREADCALENDAR,
PROGMEMTEXT_COMMON_GOOGLEDISTANCEMATRIX,
PROGMEMTEXT_TEMBOO_ACCOUNT,
PROGMEMTEXT_TEMBOO_APPNAME,
PROGMEMTEXT_TEMBOO_APPKEY,
PROGMEMTEXT_TEMBOO_PROFILE_INITIALIZEMFC,
PROGMEMTEXT_TEMBOO_PROFILE_FINALIZEMFC,
PROGMEMTEXT_TEMBOO_PROFILE_SEARCHCALENDARMFC,
PROGMEMTEXT_TEMBOO_PROFILE_READCALENDARMFC,
PROGMEMTEXT_TEMBOO_CHOREO_INITIALIZEOAUTH,
PROGMEMTEXT_TEMBOO_CHOREO_FINALIZEOAUTH,
PROGMEMTEXT_TEMBOO_CHOREO_SEARCHCALENDARSBYNAME,
PROGMEMTEXT_TEMBOO_CHOREO_GETNEXTEVENT,
PROGMEMTEXT_TEMBOO_CHOREO_WALKINGDISTANCEMATRIX,
PROGMEMTEXT_TEMBOO_CHOREO_BICYCLINGDISTANCEMATRIX,
PROGMEMTEXT_TEMBOO_CHOREO_DRIVINGDISTANCEMATRIX,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_SCOPE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_SCOPE_VALUE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_CALLBACKID,
// PROGMEMTEXT_TEMBOO_CHOREO_INPUT_CALLBACKID_VALUE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_CALENDARNAME,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_CALENDARNAME_VALUE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_CALENDARID,
// PROGMEMTEXT_TEMBOO_CHOREO_INPUT_CALENDARID_VALUE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_ACCESSTOKEN,
// PROGMEMTEXT_TEMBOO_CHOREO_INPUT_ACCESSTOKEN_VALUE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_REFRESHTOKEN,
// PROGMEMTEXT_TEMBOO_CHOREO_INPUT_REFRESHTOKEN_VALUE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_ORIGIN,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_ORIGIN_VALUE,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_DESTINATION,
PROGMEMTEXT_TEMBOO_CHOREO_INPUT_DESTINATION_VALUE,
PROGMEMTEXT
};
////////////////////////////////////////////////////////////////////////////////
void setup() {
Serial.begin(57600);
while(!Serial);
pinMode(3, OUTPUT);
analogWrite(3, 0);
/*
MFC_LCDColorShield.init(PHILIPS);
MFC_LCDColorShield.contrast(50);
MFC_LCDColorShield.clear(WHITE);
*/
RTC();
Wifi();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void loop() {
if(Setup == 0) {
while(!Serial.available());
sBuffer = Serial.readString();
Serial.print(sBuffer);
while(!Serial.available());
sBuffer = Serial.readString();
if(sBuffer.c_str() == getPROGMEMTEXT(PROGMEMTEXT_LIST::WALK))
MeansOfTransport = PROGMEMTEXT_LIST::WALKINGDISTANCEMATRIX;
else
MeansOfTransport = PROGMEMTEXT_LIST::DRIVINGDISTANCEMATRIX;
Serial.println(sBuffer);
Initialize();
Finalize();
SearchCalendar();
ReadCalendar();
Setup = 1;
}
delete Now_Time;
Now_Time = new DateTime(MFC_Time.now());
ReadCalendar();
DistanceMatrix();
}
/*
MFC_LCDColorShield.setStr(itoa(Now_Time->hour(), cBuffer[7], 10), 44, 10, BLACK,
WHITE);
MFC_LCDColorShield.setStr(":", 44, 26, BLACK, WHITE);
MFC_LCDColorShield.setStr(itoa(Now_Time->minute(), cBuffer[7], 10), 44, 34, BLACK,
WHITE);
MFC_LCDColorShield.setStr(":", 44, 42, BLACK, WHITE);
MFC_LCDColorShield.setStr(itoa(Now_Time->second(), cBuffer[7], 10), 44, 58, BLACK,
WHITE);
MFC_LCDColorShield.setStr(getPROGMEMTEXT_DayOfTheWeek(Now_Time-
>dayOfTheWeek()), 70, 10, COLOR, BACKGROUND);
delay(1000);
Count++;
}
////////////////////////////////////////////////////////////////////////////////
void RTC(void) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::RTC_DETECTION));
if (MFC_Time.begin()) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
} else {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::RTC_CONFIGURATION));
if (MFC_Time.isrunning()) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
} else {
MFC_Time.adjust(DateTime(F(__DATE__), F(__TIME__)));
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::ADJUSTED));
}
}
void Wifi(void) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::WIFI_SHIELD));
if (WiFi.status() != WL_NO_SHIELD) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
} else {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::WIFI_CONNECTION));
MFC_WifiStatus = WL_IDLE_STATUS;
if (MFC_WifiStatus == WL_CONNECTED) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
} else {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
}
////////////////////////////////////////////////////////////////////////////////
void Initialize(void) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::GOOGLE_INITIALIZEOAUTH
TembooChoreo InitializeOAuthChoreo(MFC_WifiClient);
InitializeOAuthChoreo.begin();
InitializeOAuthChoreo.setAccountName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::ACCOUNT
0));
InitializeOAuthChoreo.setAppKeyName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_NAME
1));
InitializeOAuthChoreo.setAppKey(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_KEY
2));
InitializeOAuthChoreo.setProfile(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::INITIALIZEMFC
3));
InitializeOAuthChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::SCOPE,
4), getPROGMEMTEXT_i(PROGMEMTEXT_LIST::SCOPE_VALUE, 6));
InitializeOAuthChoreo.setChoreo(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::INITIALIZEOAUTH
7));
if(InitializeOAuthChoreo.run() == 0) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
while(InitializeOAuthChoreo.available()) {
InitializeOAuthChoreo.readStringUntil('\x1F');
InitializeOAuthChoreo.readStringUntil('\x1E');
InitializeOAuthChoreo.readStringUntil('\x1F');
Serial.println(F("\nNavigate to this web-page and click \"Allow\"."));
Serial.println(InitializeOAuthChoreo.readStringUntil('\x1E'));
while(!Serial.available());
InitializeOAuthChoreo.readStringUntil('\x1F');
CallbackID = InitializeOAuthChoreo.readStringUntil('\x1E');
CallbackID.trim();
// Serial.print((char)InitializeOAuthChoreo.read());
}
} else {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
InitializeOAuthChoreo.close();
}
////////////////////////////////////////////////////////////////////////////////
void Finalize(void) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::GOOGLE_FINALIZEOAUTH));
TembooChoreo FinalizeOAuthChoreo(MFC_WifiClient);
FinalizeOAuthChoreo.begin();
FinalizeOAuthChoreo.setAccountName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::ACCOUNT
0));
FinalizeOAuthChoreo.setAppKeyName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_NAME
1));
FinalizeOAuthChoreo.setAppKey(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_KEY
2));
FinalizeOAuthChoreo.setProfile(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::FINALIZEMFC
3));
FinalizeOAuthChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::CALLBACKID
4), CallbackID);
FinalizeOAuthChoreo.setChoreo(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::FINALIZEOAUTH
7));
if(FinalizeOAuthChoreo.run() == 0) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
delete Now_Time;
Now_Time = new DateTime(MFC_Time.now());
delete AccessToken_Time;
AccessToken_Time = new DateTime(Now_Time->year(), Now_Time->month(),
Now_Time->day(), Now_Time->hour() + 1, Now_Time->minute(), Now_Time->second());
while(FinalizeOAuthChoreo.available()) {
FinalizeOAuthChoreo.readStringUntil('\x1F');
FinalizeOAuthChoreo.readStringUntil('\x1E');
FinalizeOAuthChoreo.readStringUntil('\x1F');
RefreshToken = FinalizeOAuthChoreo.readStringUntil('\x1E');
RefreshToken.trim();
FinalizeOAuthChoreo.readStringUntil('\x1F');
FinalizeOAuthChoreo.readStringUntil('\x1E');
FinalizeOAuthChoreo.readStringUntil('\x1F');
FinalizeOAuthChoreo.readStringUntil('\x1E');
FinalizeOAuthChoreo.readStringUntil('\x1F');
AccessToken = FinalizeOAuthChoreo.readStringUntil('\x1E');
AccessToken.trim();
// Serial.print((char)FinalizeOAuthChoreo.read());
}
} else {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
FinalizeOAuthChoreo.close();
}
////////////////////////////////////////////////////////////////////////////////
void SearchCalendar(void) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::GOOGLE_SEARCHCALENDAR
TembooChoreo SearchCalendarChoreo(MFC_WifiClient);
SearchCalendarChoreo.begin();
SearchCalendarChoreo.setAccountName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::ACCOUNT
0));
SearchCalendarChoreo.setAppKeyName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_NAME
1));
SearchCalendarChoreo.setAppKey(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_KEY
2));
delete Now_Time;
Now_Time = new DateTime(MFC_Time.now());
delete AccessToken_Time;
AccessToken_Time = new DateTime(Now_Time->year(), Now_Time->month(),
Now_Time->day(), Now_Time->hour() + 1, Now_Time->minute(), Now_Time->second());
SearchCalendarChoreo.setProfile(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::SEARCHCALENDAR
3));
SearchCalendarChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::REFRESHTOKEN
4), RefreshToken);
}
SearchCalendarChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::CALENDARNAME
5), getPROGMEMTEXT_i(PROGMEMTEXT_LIST::CALENDARNAME_VALUE, 6));
SearchCalendarChoreo.setChoreo(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::SEARCHCALENDA
7));
if(SearchCalendarChoreo.run() == 0) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
while(SearchCalendarChoreo.available()) {
SearchCalendarChoreo.readStringUntil('\x1F');
SearchCalendarChoreo.readStringUntil('\x1E');
SearchCalendarChoreo.readStringUntil('\x1F');
SearchCalendarChoreo.readStringUntil('\x1E');
SearchCalendarChoreo.readStringUntil('\x1F');
sBuffer = SearchCalendarChoreo.readStringUntil('\x1E');
sBuffer.trim();
if(sBuffer !=
getPROGMEMTEXT(PROGMEMTEXT_LIST::PROGMEMTEXT_LIST_SIZE))
AccessToken = sBuffer;
SearchCalendarChoreo.readStringUntil('\x1F');
SearchCalendarChoreo.readStringUntil('\x1E');
SearchCalendarChoreo.readStringUntil('\x1F');
SearchCalendarChoreo.readStringUntil('\x1E');
SearchCalendarChoreo.readStringUntil('\x1F');
CalendarID = SearchCalendarChoreo.readStringUntil('\x1E');
CalendarID.trim();
SearchCalendarChoreo.readStringUntil('\x1F');
SearchCalendarChoreo.readStringUntil('\x1E');
// Serial.print((char)SearchCalendarChoreo.read());
}
} else {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
SearchCalendarChoreo.close();
}
////////////////////////////////////////////////////////////////////////////////
void ReadCalendar(void) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::GOOGLE_READCALENDAR));
TembooChoreo ReadCalendarChoreo(MFC_WifiClient);
ReadCalendarChoreo.begin();
ReadCalendarChoreo.setAccountName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::ACCOUNT
0));
ReadCalendarChoreo.setAppKeyName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_NAME
1));
ReadCalendarChoreo.setAppKey(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_KEY
2));
delete Now_Time;
Now_Time = new DateTime(MFC_Time.now());
delete AccessToken_Time;
AccessToken_Time = new DateTime(Now_Time->year(), Now_Time->month(),
Now_Time->day(), Now_Time->hour() + 1, Now_Time->minute(), Now_Time->second());
ReadCalendarChoreo.setProfile(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::READCALENDARMF
3));
ReadCalendarChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::REFRESHTOKEN
4), RefreshToken);
}
ReadCalendarChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::CALENDARID
6), CalendarID);
ReadCalendarChoreo.setChoreo(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::GETNEXTEVENT
7));
if(ReadCalendarChoreo.run() == 0) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
while(ReadCalendarChoreo.available()) {
ReadCalendarChoreo.readStringUntil('\x1F');
ReadCalendarChoreo.readStringUntil('\x1E');
ReadCalendarChoreo.readStringUntil('\x1F');
ReadCalendarChoreo.readStringUntil('\x1E');
ReadCalendarChoreo.readStringUntil('\x1F');
sBuffer = ReadCalendarChoreo.readStringUntil('\x1E');
sBuffer.trim();
if(sBuffer !=
getPROGMEMTEXT(PROGMEMTEXT_LIST::PROGMEMTEXT_LIST_SIZE)) {
sBuffer[4] = '\0';
sBuffer[7] = '\0';
sBuffer[10] = '\0';
sBuffer[13] = '\0';
sBuffer[16] = '\0';
sBuffer[19] = '\0';
delete ReadCalendar_Time;
ReadCalendar_Time = new DateTime(atoi(&sBuffer[0]), atoi(&sBuffer[5]),
atoi(&sBuffer[8]), atoi(&sBuffer[11]), atoi(&sBuffer[14]), atoi(&sBuffer[17]));
Serial.println();
}
else {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::UNEXPECTEDERROR));
while(true);
}
ReadCalendarChoreo.readStringUntil('\x1F');
sBuffer = ReadCalendarChoreo.readStringUntil('\x1E');
sBuffer.trim();
if(sBuffer !=
getPROGMEMTEXT(PROGMEMTEXT_LIST::PROGMEMTEXT_LIST_SIZE))
AccessToken = sBuffer;
sBuffer = getPROGMEMTEXT(PROGMEMTEXT_LIST::PROGMEMTEXT_LIST_SIZE);
ReadCalendarChoreo.readStringUntil('\x1F');
ReadCalendarChoreo.readStringUntil('\x1E');
ReadCalendarChoreo.readStringUntil('\x1F');
ReadCalendarChoreo.readStringUntil('\x1E');
//Serial.print((char)ReadCalendarChoreo.read());
}
} else {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
ReadCalendarChoreo.close();
}
////////////////////////////////////////////////////////////////////////////////
void DistanceMatrix(void) {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::GOOGLE_DISTANCEMATRIX
TembooChoreo DistanceMatrixChoreo(MFC_WifiClient);
DistanceMatrixChoreo.begin();
DistanceMatrixChoreo.setAccountName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::ACCOUNT
0));
DistanceMatrixChoreo.setAppKeyName(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_NAME
1));
DistanceMatrixChoreo.setAppKey(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::APP_KEY
2));
DistanceMatrixChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::ORIGIN
3), getPROGMEMTEXT_i(PROGMEMTEXT_LIST::ORIGIN_VALUE, 4));
DistanceMatrixChoreo.addInput(getPROGMEMTEXT_i(PROGMEMTEXT_LIST::DESTINATION
5), getPROGMEMTEXT_i(PROGMEMTEXT_LIST::DESTINATION_VALUE, 6));
DistanceMatrixChoreo.setChoreo(getPROGMEMTEXT_i(MeansOfTransport, 7));
DistanceMatrixChoreo.run();
if(DistanceMatrixChoreo.run() == 0) {
Serial.println(getPROGMEMTEXT(PROGMEMTEXT_LIST::OK));
while(DistanceMatrixChoreo.available()) {
DistanceMatrixChoreo.readStringUntil('\x1F');
DistanceMatrixChoreo.readStringUntil('\x1E');
DistanceMatrixChoreo.readStringUntil('\x1F');
sBuffer = DistanceMatrixChoreo.readStringUntil('\x1E');
sBuffer.trim();
DistanceMatrixChoreo.readStringUntil('\x1F');
DistanceMatrixChoreo.readStringUntil('\x1E');
// Serial.print((char)DistanceMatrixChoreo.read());
}
} else {
Serial.print(getPROGMEMTEXT(PROGMEMTEXT_LIST::FAIL));
while(true);
}
DistanceMatrixChoreo.close();
}
99) Arduino Smart Humidifer
COMPONENTS AND SUPPLIES
Basic Bread board - 16.5*5.5 cm
× 1
× 1
Now connect the LCD display to the arduino board and test it. LCD
should display the relative humidity and temperature. If everything
works well now it is the time to connect water atomization to the
system. To do that first connect the driver board to the arduino board,
then connect ultrasonic transducer to the driver board.
Take a cup filled with water and put some tissue into the water. Put
ultrasonic transducer onto tissue. Note that the bottom side is the side
with hollow which is supposed to face downside. Let bottom of
transducer plate sink into the water and keep top side above water. The
function of tissue is lead water to the transducer and keep upper side of
transducer above water.
Power up the system, If you see vapor produced then congratulation!
You made it, experiment with it!!!
Notes that do not touch transducer interface pins directly because peak
output voltage of Drier board can be 65V.
SCHEMATICS
CODE
#include <LiquidCrystal.h>
//int humidityPin=A0;
//int Thgm20Pin=A1;
int atomizationPin = 2;
unsigned int sensorValue2 = 0; // variable to store the value coming from
the sensor
unsigned int sensorValue3 = 0; // variable to store the value coming from
the sensor
void setup() {
Serial.begin(9600);
pinMode(atomizationPin, OUTPUT);
lcd.begin(16, 2);
}
void loop() {
for (byte i=0;i<nsum;i++)
{ // read 10 values for T & H
sensorValue2 += analogRead(A0);
sensorValue3 += analogRead(A1);
}
// average the value
int sensorValue2Avg=sensorValue2/nsum;
float RH= 0.1515*sensorValue2Avg-12.0;
int sensorValue3Avg=sensorValue3/nsum;
float Vt=(float) sensorValue3Avg*5.0/1023.0;
float R=(5.0-Vt)*10.0/Vt; // convert the value to relative humidity
float TinC=281.583*pow(1.0230,(1.0/R))*pow(R,-0.1227)-150.6614;
float TinF=TinC*(9.0/5.0)+32; // convert the temperature to fahrenheit
// print to serial monitor
Serial.print(RH,0);
Serial.println(" %RH");
Serial.print(TinC,1);
Serial.println(" deg C");
Serial.print(TinF,1);
Serial.println(" deg F");
Serial.print(R);
// print the value to lcd display
lcd.setCursor(0, 0);
lcd.print("%RH = ");
lcd.setCursor(6, 0);
lcd.print(R);
lcd.setCursor(0, 1);
lcd.print("T = ");
lcd.setCursor(5, 1);
lcd.print(TinC);
//
// if relatie humidity less than 40 % then turn on humidifire
// for 10sec.
if(R < 50){
digitalWrite(atomizationPin, HIGH);
delay(10000);
digitalWrite(atomizationPin, LOW);
sensorValue2=0;
sensorValue3=0;
delay(5000)
}
100) Arduino Advent Candle
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
3 mm LED: Red
× 25
RTC DS3231
× 1
× 1
× 1
Slide Switch
× 1
× 1
Driller
SCHEMATICS
CODE
#include "Wire.h"
#include "pitches.h"
#define DS3231_I2C_ADDRESS 0x68
digitalWrite(anodes[myAnode], HIGH);
digitalWrite(cathods[myCathode], LOW);
// jingle bells
int melody[] = {
NOTE_E3, NOTE_E3, NOTE_E3,
NOTE_E3, NOTE_E3, NOTE_E3,
NOTE_E3, NOTE_G3, NOTE_C3, NOTE_D3,
NOTE_E3,
NOTE_F3, NOTE_F3, NOTE_F3, NOTE_F3,
NOTE_F3, NOTE_E3, NOTE_E3, NOTE_E3, NOTE_E3,
NOTE_E3, NOTE_D3, NOTE_D3, NOTE_E3,
NOTE_D3, NOTE_G3,
NOTE_E3, NOTE_E3, NOTE_E3,
NOTE_E3, NOTE_E3, NOTE_E3,
NOTE_E3, NOTE_G3, NOTE_C3, NOTE_D3,
NOTE_E3,
NOTE_F3, NOTE_F3, NOTE_F3, NOTE_F3,
NOTE_F3, NOTE_E3, NOTE_E3, NOTE_E3, NOTE_E3,
NOTE_G3, NOTE_G3, NOTE_F3, NOTE_D3,
NOTE_C3
};
// play music
for (int thisNote = 0; thisNote < 51; thisNote++) {
led_on((thisNote % today)+1);
// setup
void setup() {
Wire.begin();
Serial.begin(9600);
pinMode(BUTTON, INPUT_PULLUP);
// switch off all
for (int i = 0; i < 5; i++) {
pinMode(cathods[i], OUTPUT);
pinMode(anodes[i], OUTPUT);
digitalWrite(cathods[i], LOW);
digitalWrite(anodes[i], LOW);
}
}
// loop
void loop() {
if (myDelay == 1) {
loop_interval = 5000;
} else {
loop_interval = myDelay * today * 5;
}
// play song on press button
int sensorVal = digitalRead(BUTTON);
if (sensorVal == LOW) {
Serial.println("Button pressed, starting music");
play(today);
}
× 1
Ultimaker 3
Attach resistors
Start hooking up wires for connection to the LEDs and pushbutton
On/Off. Solder wire connections to the LEDs, use heat-shrink tubing if
needed.
Attach the push button On/Off switch. It does not need to be glued in
place.
Place the LEDs into the flat LED holder through the back of the front
plate. They will snap into place.
Connect both front and back panel. Power using Arduino cable or 9v
battery. Push button, enjoy!
SCHEMATICS
CODE
/*
DIY Code Red Button
Created by David Escobar
Date: 04/14/17
*/
void setup() {
pinMode(ledOn, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
}
void loop() {
blink();
}
void blink(){
digitalWrite(ledOn, HIGH);
digitalWrite(led1, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
delay(250);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
delay(100);
}
× 1
Relay (generic)
× 1
NECESSARY TOOLS AND MACHINES
Old Ice Maker
APPS AND ONLINE SERVICES
Arduino IDE
ardublock
My Ice Maker
arduino and relays
Ice maker in operation
SCHEMATICS
CODE
void setup()
{
pinMode( 4 , INPUT);
pinMode( 5 , INPUT);
pinMode( 6 , INPUT);
pinMode( 4 , OUTPUT);
pinMode( 5 , OUTPUT);
pinMode( 6 , OUTPUT);
pinMode( 8 , OUTPUT);
pinMode( 9 , OUTPUT);
pinMode( 10 , OUTPUT);
pinMode( 11 , OUTPUT);
digitalWrite( 4 , LOW );
digitalWrite( 5 , LOW );
digitalWrite( 6 , LOW );
digitalWrite( 8 , HIGH );
digitalWrite( 9 , HIGH );
digitalWrite( 10 , HIGH );
digitalWrite( 11 , HIGH );
void loop()
{
if ( digitalRead( 4))
{
digitalWrite( 8 , LOW );
}
if ( digitalRead( 5))
{
digitalWrite( 8 , HIGH );
digitalWrite( 9 , LOW );
delay( 40000 );
digitalWrite( 9 , HIGH );
digitalWrite( 10 , LOW );
delay( 700000 );
digitalWrite( 8 , LOW );
delay( 5000 );
}
if ( digitalRead( 6))
{
digitalWrite( 8 , HIGH );
delay( 5000 );
digitalWrite( 11 , LOW );
delay( 30000 );
digitalWrite( 11 , HIGH );
digitalWrite( 8 , LOW );
delay( 10000 );
}
}
× 1
× 1
Schematic
Code
/* Graph
A simple example of communication from the Arduino board to the
computer: The value of analog input 0 is sent out the serial port. We call
this "serial" communication because the connection appears to both the
Arduino and the computer as a serial port, even though it may actually
use a USB cable. Bytes are sent one after another (serially) from the
Arduino to the computer.
You can use the Arduino Serial Monitor to view the sent data, or it can
be read by Processing, PD, Max/MSP, or any other program capable of
reading data from a serial port. The Processing code below graphs the
data received so you can see the value of the analog input changing over
time.
The circuit: - any analog input sensor attached to analog in pin 0*/
void setup() { // initialize the serial communication: Serial.begin(9600);}
void loop() { // send the value of analog input 0:
Serial.println(analogRead(A0)); // wait a bit for the analog-to-digital
converter to stabilize after the last // reading: delay(2);}
/* Processing code for this example
// Graphing sketch
// This program takes ASCII-encoded strings from the serial port at 9600
baud // and graphs them. It expects values in the range 0 to 1023,
followed by a // newline, or newline and carriage return
import processing.serial.*;
Serial myPort; // The serial port int xPos = 1; // horizontal
position of the graph float inByte = 0;
void setup () { // set the window size: size(400, 300);
// List all the available serial ports // if using Processing 2.1 or later,
use Serial.printArray() println(Serial.list());
// I know that the first port in the serial list on my Mac is always my //
Arduino, so I open Serial.list()[0]. // Open whatever port is the one
you're using. myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set initial background: background(0); }
void draw () { // draw the line: stroke(127, 34, 255); line(xPos,
height, xPos, height - inByte);
// at the edge of the screen, go back to the beginning: if (xPos >=
width) { xPos = 0; background(0); } else { // increment the
horizontal position: xPos++; } }
void serialEvent (Serial myPort) { // get the ASCII string: String
inString = myPort.readStringUntil('\n');
if (inString != null) { // trim off any whitespace: inString =
trim(inString); // convert to an int and map to the screen height:
inByte = float(inString); println(inByte); inByte = map(inByte, 0,
1023, 0, height); } }
*/
/* Max/MSP v5 patch for this example
----------begin_max5_patcher---------
-1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJITRTxj+6
----------end_max5_patcher-----------
*/
Processing Sketch
Using the Processing sketch in the code sample above, you'll get a graph
of the sensor's value. As you change the value of the analog sensor, you'll
get a graph something like this:
SCHEMATICS
CODE
/* Graph
You can use the Arduino Serial Monitor to view the sent data, or it can be
read by Processing, PD, Max/MSP, or any other program capable of
reading data
from a serial port. The Processing code below graphs the data received so
you
can see the value of the analog input changing over time.
The circuit:
- any analog input sensor attached to analog in pin 0
*/
void setup() {
// initialize the serial communication:
Serial.begin(9600);
}
void loop() {
// send the value of analog input 0:
Serial.println(analogRead(A0));
// wait a bit for the analog-to-digital converter to stabilize after the last
// reading:
delay(2);
}
// Graphing sketch
// This program takes ASCII-encoded strings from the serial port at 9600
baud
// and graphs them. It expects values in the range 0 to 1023, followed by a
// newline, or newline and carriage return
import processing.serial.*;
void setup () {
// set the window size:
size(400, 300);
// I know that the first port in the serial list on my Mac is always my
// Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
void draw () {
// draw the line:
stroke(127, 34, 255);
line(xPos, height, xPos, height - inByte);
if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int and map to the screen height:
inByte = float(inString);
println(inByte);
inByte = map(inByte, 0, 1023, 0, height);
}
}
*/
----------begin_max5_patcher----------
1591.3oc0YszbaaCD9r7uBL5RalQUAO3CvdyS5zVenWZxs5NcfHgjPCIfJIT
RTxj+6AOHkoTDooroUs0AQPR73a+1cwtK3WtZxzEpOwqlB9YveAlL4KWMYh6
Q1GLo99ISKXeJMmU451zTUQAWpmNy+NM+SZ2y+sR1l02JuU9t0hJvFlNcMPy
dOuBv.U5Rgb0LPpRpYBooM3529latArTUVvzZdFPtsXAuDrrTU.f.sBffXxL
vGE50lIHkUVJXq3fRtdaoDvjYfbgjujaFJSCzq4.tLaN.bi1tJefWpqbO0uz
1IjIABoluxrJ1guxh2JfPO2B5zRNyBCLDFcqbwNvuv9fHCb8bvevyyEU2JKT
YhkBSWPAfq2TZ6YhqmuMUo0feUn+rYpY4YtY+cFw3lUJdCMYAapZqzwUHX8S
crjAd+SIOU6UBAwIygy.Q1+HAA1KH6EveWOFQlitUK92ehfal9kFhUxJ3tWc
sgpxadigWExbt1o7Ps5dk3yttivyg20W0VcSmg1G90qtx92rAZbH4ez.ruy1
nhmaDPidE07J+5n2sg6E6oKXxUSmc20o6E3SPRDbrkXnPGUYE.i5nCNB9TxQ
jG.G0kCTZtH88f07Rt0ZMMWUw8VvbKVAaTk6GyoraPdZff7rQTejBN54lgyv
HE0Ft7AvIvvgvIwO23jBdUkYOuSvIFSiNcjFhiSsUBwsUCh1AgfNSBAeNDBZ
DIDqY.f8.YjfjV1HAn9XDTxyNFYatVTkKx3kcK9GraZpI5jv7GOx+Z37Xh82
LSKHIDmDXaESoXRngIZQDKVkpxUkMCyXCQhcCK1z.G457gi3TzMz4RFD515F
G3bIQQwcP3SOF0zlkGhiCBQ1kOHHFFlXaEBQIQnCwv9QF1LxPZ.A4jR5cyQs
vbvHMJsLll01We+rE2LazX6zYmCraRrsPFwKg1ANBZFY.IAihr8Ox.aH0oAL
hB8nQVw0FSJiZeunOykbT6t3r.NP8.iL+bnwNiXuVMNJH9H9YCm89CFXPBER
bz422p8.O4dg6kRxdyjDqRwMIHTbT3QFLskxJ8tbmQK4tm0XGeZWF7wKKtYY
aTAF.XPNFaaQBinQMJ4QLF0aNHF0JtYuHSxoUZfZY6.UU2ejJTb8lQw8Fo5k
Rv6e2PI+fOM71o2ecY1VgTYdCSxxUqLokuYq9jYJi6lxPgD2NIPePLB0mwbG
YA9Rgxdiu1k5xiLlSU6JVnx6wzg3sYHwTesB8Z5D7RiGZpXyvDNJY.DQX3.H
hvmcUN4bP1yCkhpTle2P37jtBsKrLWcMScEmltOPv22ZfAqQAdKr9HzATQwZ
q18PrUGt6Tst2XMCRUfGuhXs6ccn23YloomMqcTiC5iMGPsHsHRWhWFlaenV
XcqwgCQiGGJzptyS2ZMODBz6fGza0bzmXBj7+DA94bvpR01MffAlueO7HwcI
pWCwmzJdvi9ILgflLAFmyXB6O7ML0YbD26lenmcGxjVsZUN+A6pUK7AtTrPg
M+eRYG0qD9j4I7eEbco8Xh6WcO.or9XDC6UCiewbXHkh6xm5LiPEkzpJDRTu
mEB44Fgz4NCtJvX.SM1vo2SlTCZGAe7GZu6ahdRyzFOhYZ+mbVVSYptBw.K1
tboIkatIA7c1cTKD1u.honLYV04VkluHsXe0szv9pQCE9Ro3jaVB1o15pz2X
zYoBvO5KXCAe0LCYJybE8ZODf4fV8t9qW0zYxq.YJfTosj1bv0xc.SaC0+AV
9V9L.KKyV3SyTcRtmzi6rO.O16USvts4B5xe9EymDvebK0eMfW6+NIsNlE2m
eqRyJ0utRq13+RjmqYKN1e.4d61jjdsauXe3.2p6jgi9hsNIv97CoyJ01xzl
c3ZhUCtSHx3UZgjoEJYqNY+hYs5zZQVFW19L3JDYaTlMLqAAt1G2yXlnFg9a
53L1FJVcv.cOX0dh7mCVGCLce7GFcQwDdH5Ta3nyAS0pQbHxegr+tGIZORgM
RnMj5vGl1Fs16drnk7Tf1XOLgv1n0d2iEsCxR.eQsNOZ4FGF7whofgfI3kES
1kCeOX5L2rifbdu0A9ae2X.V33B1Z+.Bj1FrP5iFrCYCG5EUWSG.hhunHJd.
HJ5hhnng3h9HPj4lud02.1bxGw.
-----------end_max5_patcher-----------
*/
× 1
DC motor (generic)
× 2
9V battery (generic)
× 3
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
int inByte;
void setup()
{
Serial.begin(9600);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
pinMode(14, OUTPUT);
pinMode(15, OUTPUT);
}
void loop()
{
if (Serial.available() > 0)
{
inByte = Serial.read();
switch (inByte)
{
case '1':
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
Serial.println("FRONT");
break;
case '2':
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
Serial.println("BACK");
break;
case '3':
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
Serial.println("LEFT");
break;
case '4':
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
Serial.println("RIGHT");
break;
case '5':
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
Serial.println("STOP");
break;
case 'A':
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
Serial.println("JOINT 1 CLOCK");
delay(200);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
break;
case 'B':
digitalWrite(6, HIGH );
digitalWrite(7, LOW);
Serial.println("JOINT 1 ANTICLOCK");
delay(200);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
break;
case 'C':
digitalWrite(8, LOW);
digitalWrite(9, HIGH);
Serial.println("JOINT 2 CLOCK");
delay(200);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
break;
case 'D':
digitalWrite(8, HIGH);
digitalWrite(9, LOW);
Serial.println("JOINT 2 ANTICLOCK");
delay(200);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
break;
case 'E':
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
Serial.println("JOINT 3 CLOCK");
delay(200);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
break;
case 'F':
digitalWrite(10, HIGH);
digitalWrite(11, LOW);
Serial.println("JOINT 3 ANTICLOCK");
delay(200);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
break;
case 'G':
digitalWrite(12, LOW);
digitalWrite(13, HIGH);
Serial.println("JOINT 4 CLOCK");
delay(200);
digitalWrite(12, LOW);
digitalWrite(13, LOW);
break;
case 'H':
digitalWrite(12, HIGH);
digitalWrite(13, LOW);
Serial.println("JOINT 4 ANTICLOCK");
delay(200);
digitalWrite(12, LOW);
digitalWrite(13, LOW);
break;
case 'I':
digitalWrite(14, LOW);
digitalWrite(15, HIGH);
Serial.println("JOINT 5 CLOCK");
delay(200);
digitalWrite(14, LOW);
digitalWrite(15, LOW);
break;
case 'J':
digitalWrite(14, HIGH);
digitalWrite(15, LOW);
Serial.println("JOINT 5 ANTICLOCK");
delay(200);
digitalWrite(14, LOW);
digitalWrite(15, LOW);
break;
}
}}
105) Arduino Atari Joystick Linking for Robotics Control
× 2
× 1
× 2
IR receiver (generic)
Be sure to check if you need to
× 1
install an inline resistor. Some
have them built in.
Single Turn Potentiometer- 10k
ohms
× 2
For LCD brightness and contrast
control
9V battery (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
For use with robotics control when completed as a whole project. The
joysticks are recovered from a bygone era of my time, '80s when
computers were just taking off. Anyway, these joysticks are infrared,
they work, and both have different signals, but on the same timings
frequency.
One of them is a master having the reset, next, and select menu buttons
on it. The other does not.
The oldie but goodie joysticks
Now to the usage video. These joysticks send out some funky monkey
types of signals as you will see, I traced it down to three variables that
needed to be worked out.
Receive the IR signal from one of the joysticks.
Set a slight delay to allow the IR device to decipher the signal, for
these joysticks it was around 15 to 20 milliseconds.
Await the joysticks "End of Transmission" code. This set sends out a
third IR pulse at the end, and it is always the same. It is an end of
activity signal of sorts.
SCHEMATICS
CODE
#include <IRremote.h>
#include <LiquidCrystal.h>
int RECV_PIN = 2;
int CONFIRM_PIN = 3;
IRrecv irrecv(RECV_PIN);
decode_results results;
LiquidCrystal lcd(22,23,27,26,25,24);
void setup()
{
pinMode(CONFIRM_PIN, OUTPUT);
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" IR Recieve and ");
lcd.setCursor(0, 1);
lcd.print("then output test");
delay(2000);
lcd.clear();
}
void loop() {
digitalWrite(CONFIRM_PIN, LOW);
lcd.setCursor(0, 0);
lcd.print("Ready to Recieve");
lcd.setCursor(0, 1);
lcd.print("Press any button");
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
Serial.println(results.value, DEC);
digitalWrite(CONFIRM_PIN, HIGH);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" HEX = ");
lcd.print(results.value, HEX);
lcd.setCursor(0, 1);
lcd.print(" DEC = ");
lcd.print(results.value, DEC);
delay(3000);
irrecv.resume(); // Receive the next value
}
}
106) Arduino LED Temperature Indicator
× 1
LED (generic)
Any color
× 3
Temperature Sensor
× 1
× 16
ABOUT THIS PROJECT
Arduino Uno/Genuino
Breadboard
Jumper wires (generic)
3 220Ω resistors
3 LEDs (any color)
A temperature sensor (mine is an LM35, but most should work)
Step 2: Put Parts in Place
Follow Picture
Step 3: Wire It Up
Wire Set-up
Wire it up:
>Red LED goes to digital pin 4 through one of the resistors, and
ground
>Green LED goes to digital pin 3 though a resistor, and ground
>Blue LED goes to digital pin 2 through a resistor, and ground
>Pin one (the pin on the left) of the temperature sensor goes to 5v
>Pin two (the pin in the middle) of the temperature sensor goes to
analog pin A2
>pin three (the pin on the right) of the temperature sensor goes to
ground
Step 4 : Put Code
SCHEMATICS
CODE
const int hot = 87; //set hot parameter
const int cold = 75; //set cold parameter
void setup() {
pinMode(A2, INPUT); //sensor
pinMode(2, OUTPUT); //blue
pinMode(3, OUTPUT); //green
pinMode(4, OUTPUT); //red
Serial.begin(9600);
}
void loop() {
int sensor = analogRead(A2);
float voltage = (sensor / 1024.0) * 5.0;
float tempC = (voltage - .5) * 100;
float tempF = (tempC * 1.8) + 32;
Serial.print("temp: ");
Serial.print(tempF);
if (tempF < cold) { //cold
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
Serial.println(" It's Cold.");
}
else if (tempF >= hot) { //hot
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
Serial.println(" It's Hot.");
}
else { //fine
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
Serial.println(" It's Fine.");
}
delay(10);
}
× 1
Years ago, just for fun, I wrote an excel macro to solve Sudoku puzzles on
a desktop computer. It occurred to me that this could be incorporated into
an Arduino touchscreen device. The perfect fit for this was an Arduino
Uno and a compatible 2.8-inch TFT touchscreen shield.
SCHEMATICS
CODE
colcoord[9] = { 10, 34, 58, 90, 114, 138, 170, 194, 218 };
rowcoord[9] = { 8, 33, 58, 88, 113, 138, 170, 194, 218 };
int location = 1;
*/
#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
// optional
#define LCD_RESET A4
const byte colcoord[9] = { 10, 34, 58, 90, 114, 138, 170, 194, 218 };
const byte rowcoord[9] = { 8, 33, 58, 88, 113, 138, 170, 194, 218 };
byte location = 1;
byte sudoku[82][14];
byte touchlocation = 0; // Used to track the array value that the stylis is closest to in the
Sudoku 9x9 framework
byte tempreading = 0;
void setup(void) {
// Serial.begin(9600);
// Serial.println(F("Paint!"));
tft.reset();
tft.begin(identifier);
tft.setRotation(1);
tft.fillScreen(BLACK);
byte g = 70;
tft.setTextColor(WHITE); tft.setTextSize(2);
tft.setCursor(25, 170); tft.println("Play, Create, Solve");
tft.setTextColor(GREEN); tft.setTextSize(1);
tft.setCursor(25, 200); tft.println("By TechKiwiGadgets 2019");
delay(4000);
tft.fillScreen(BLACK);
// Test Display by showing all values in the puzzle - White are Solved , Blue are others
tft.setTextSize(2);
for (byte a = 1; a < 82; a++) {
drawbuttons();
pinMode(13, OUTPUT);
// testText();
#define MINPRESSURE 5
#define MAXPRESSURE 1000
// tft.begin(identifier);
void loop()
{
// if sharing pins, you'll need to fix the directions of the touchscreen pins
pinMode(XM, OUTPUT);
pinMode(YP, OUTPUT);
// we have some minimum pressure we consider 'valid'
// pressure of 0 means no pressing!
/*
Serial.print("X = "); Serial.print(p.x);
Serial.print("\tY = "); Serial.print(p.y);
Serial.print("\tPressure = "); Serial.println(p.z);
*/
// scale from 0->1023 to tft.width
p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240);
p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320); // Original Code
/*
Serial.print("X = "); Serial.print(p.x);
Serial.print("\tY = "); Serial.print(p.y);
Serial.print("\tPressure = "); Serial.println(p.z);
*/
// Calculate the position of the screen touch based on the input values of p.x and p.y
} else
if ((p.x > 54) && (p.x < 80)) { // Coloumn 3
} else
if ((p.x > 81) && (p.x < 107)) { // Coloumn 4
} else
if ((p.x > 108) && (p.x < 133)) { // Coloumn 5
} else
if ((p.x > 134) && (p.x < 160)) { // Coloumn 6
} else
if ((p.x > 161) && (p.x < 187)) { // Coloumn 7
} else
if ((p.x > 188) && (p.x < 213)) { // Coloumn 8
// debounce function to remove issue with first touch screen reading being spurious
if (debounce == false) {
touchlocation = 0;
debounce = true;
}
/*
Serial.print("Y = "); Serial.print(p.x);
Serial.print("\tX = "); Serial.print(p.y);
Serial.print("\tLocation = "); Serial.println(touchlocation);
*/
// Only increment if has not been solved, Debounce by checking if this is the second time
the same range is selected
if ((tempreading == touchlocation)&&(sudoku[touchlocation][0]==0)||(tempreading ==
touchlocation)&&(sudoku[touchlocation][0]==2)) {
sudoku[touchlocation][1]++;
if (sudoku[touchlocation][1] > 9) {
sudoku[touchlocation][1] = 0;
}
// Test to see if changing an item can be classified as solved
if (sudoku[touchlocation][1]!=0) {
sudoku[touchlocation][0]=2; // Set to Solved if a manually changed number however
flag as manual change with va,ue of 2
} else {
sudoku[touchlocation][0]=0; // Set to Not Solved if 0
}
// Finally reset all of the data values in this location that have been manually changed to
unsolved
for (byte u = 1; u < 82; u++) {
// If preprogrammed from a game then leave values otherwise reset data to baseline
if (sudoku[u][0]!=1){
for (byte q = 4; q < 13; q++) {
sudoku[u][q]=q-3;
}
}
}
}
// tft.setTextColor(WHITE); tft.setTextSize(1);
// tft.setCursor(250, 80); tft.println(touchlocation);
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[touchlocation][3], sudoku[touchlocation][2], 15, 15, BLACK);
tft.setTextSize(2);
if (tempreading == touchlocation) {
delay(delay1);
}
tempreading = touchlocation; // take a first sample then repeat and compare to debounce
delay(delay1/2);
//Button 3
tft.fillCircle(280, 150, 20, WHITE);
tft.setTextColor(BLACK); tft.setTextSize(1);
tft.setCursor(268, 147); tft.println("HELP");
delay(delay1/2);
helpbutton(); // Run algorythm and test for incorrect locations then highlight in red
// reversesolve();
delay(800);// Display the changes before reverting to original colors
//Button 4
tft.fillCircle(280, 210, 20, WHITE);
tft.setTextColor(BLACK); tft.setTextSize(1);
tft.setCursor(266, 207); tft.println("SOLVE");
delay(delay1/2);
reversesolvecolor();
uniquecandidate(); // Test
solvealigndata();
reversesolvecolor();
reversesolvecolor();
uniquecandidate(); // Test
solvealigndata();
reversesolvecolor();
reversesolvecolor();
uniquecandidate(); // Test
solvealigndata();
reversesolvecolor();
reversesolvecolor();
uniquecandidate(); // Test
solvealigndata();
reversesolvecolor();
/*
Serial.print("Y = "); Serial.print(p.x);
Serial.print("\tX = "); Serial.println(p.y);
*/
p.z = 0;// Force the sensor value below threshold to avoid ghost values
}
void loadtestpuzzle1(){
if (puzzlenum == 1 ){
// Load Numbers
sudoku[1][1] = 2; sudoku[3][1] = 9; sudoku[19][1] = 3; sudoku[21][1] = 5;
} else
if (puzzlenum == 2 ){
// Load Numbers
sudoku[1][1] = 4; sudoku[10][1] = 2; sudoku[19][1] = 1;
} else
if (puzzlenum == 3 ){
// Load Numbers
sudoku[12][1] = 8; sudoku[19][1] = 4;
sudoku[70][0] = 1; sudoku[63][0] = 1;
} else
if (puzzlenum == 4 ){
// Load Numbers
sudoku[3][1] = 6; sudoku[12][1] = 2;
sudoku[70][1] = 8; sudoku[79][1] = 5;
sudoku[70][0] = 1; sudoku[79][0] = 1;
} else
if (puzzlenum == 5 ){
// Load Numbers
sudoku[2][1] = 3; sudoku[3][1] = 2; sudoku[12][1] = 6; sudoku[21][1] = 9;
sudoku[4][1] = 9; sudoku[5][1] = 8; sudoku[22][1] = 2;
sudoku[17][1] = 3; sudoku[27][1] = 7;
sudoku[30][1] = 7; sudoku[47][1] = 9;
sudoku[35][1] = 5; sudoku[52][1] = 6;
sudoku[55][1] = 2; sudoku[65][1] = 6;
sudoku[17][0] = 1; sudoku[27][0] = 1;
sudoku[30][0] = 1; sudoku[47][0] = 1;
sudoku[35][0] = 1; sudoku[52][0] = 1;
sudoku[55][0] = 1; sudoku[65][0] = 1;
}
void refreshdisplay() { //Refresh the display once a value has changed
tft.setTextSize(2);
}
}
void drawscreen(){
// tft.fillScreen(BLACK);
// Setup Screen
GREEN = 0x07E0;
void resetmatrix(){ // Initialize the sudoku matrix by setting all locations to zero and
loading in the coordinates for each touch location
byte hole = 1;
for (byte a = 0; a < 9; a++) {
for (byte b = 0; b < 9; b++) {
sudoku[hole][0] = 0; // Solve Flag
sudoku[hole][1] = 0; // Display Value
sudoku[hole][2] = colcoord[a]; // Matrix Column coordinate
sudoku[hole][3] = rowcoord[b]; // Matrix Row coordinate
sudoku[hole][4] = 1; // V1
sudoku[hole][5] = 2; // V2
sudoku[hole][6] = 3; // V3
sudoku[hole][7] = 4; // V4
sudoku[hole][8] = 5; // V5
sudoku[hole][9] = 6; // V6
sudoku[hole][10] = 7; // V7
sudoku[hole][11] = 8; // V8
sudoku[hole][12] = 9; // V9
hole++;
}
}
}
void drawbuttons() {
// Setup Buttons
GREEN = 0x07E0;
//Button 1
tft.drawCircle(280, 30, 24, GREEN);
tft.fillCircle(280, 30, 20, GREEN);
tft.setTextColor(BLACK); tft.setTextSize(1);
tft.setCursor(268, 27); tft.println("HOME");
//Button 2
tft.drawCircle(280, 90, 24, YELLOW);
tft.fillCircle(280, 90, 20, YELLOW);
tft.setTextColor(BLACK); tft.setTextSize(1);
tft.setCursor(268, 87); tft.println("PLAY");
//Button 3
tft.drawCircle(280, 150, 24, MAGENTA);
tft.fillCircle(280, 150, 20, MAGENTA);
tft.setTextColor(BLACK); tft.setTextSize(1);
tft.setCursor(268, 147); tft.println("HELP");
//Button 4
tft.drawCircle(280, 210, 24, BLUE);
tft.fillCircle(280, 210, 20, BLUE);
tft.setTextColor(BLACK); tft.setTextSize(1);
tft.setCursor(266, 207); tft.println("SOLVE");
void solvealigndata(){ // Once a location is marked as solved then all data in that location
nees to be set to Zero
if (sudoku[a][0] > 0) { // If location solved then zero out all data in array except correct
value
/*
Serial.print(a); Serial.print(" ");
Serial.print(sudoku[a][4]);
Serial.print(sudoku[a][5]);
Serial.print(sudoku[a][6]);
Serial.print(sudoku[a][7]);
Serial.print(sudoku[a][8]);
Serial.print(sudoku[a][9]);
Serial.print(sudoku[a][10]);
Serial.print(sudoku[a][11]);
Serial.println(sudoku[a][12]);
*/
sudoku[a][4] = 0; // V1
sudoku[a][5] = 0; // V2
sudoku[a][6] = 0; // V3
sudoku[a][7] = 0; // V4
sudoku[a][8] = 0; // V5
sudoku[a][9] = 0; // V6
sudoku[a][10] = 0; // V7
sudoku[a][11] = 0; // V8
sudoku[a][12] = 0; // V9
/*
Serial.print(a); Serial.print(" ");
Serial.print(sudoku[a][4]);
Serial.print(sudoku[a][5]);
Serial.print(sudoku[a][6]);
Serial.print(sudoku[a][7]);
Serial.print(sudoku[a][8]);
Serial.print(sudoku[a][9]);
Serial.print(sudoku[a][10]);
Serial.print(sudoku[a][11]);
Serial.println(sudoku[a][12]);
*/
}
}
void reversesolve(){ // subroutine to reverse engineer solved locations in the matrix and
label themas solved
byte tempcount = 0;
for (byte a = 1; a < 82; a++) { // Cycle through all locations
/*
Serial.print(a); Serial.print(" ");
Serial.print(sudoku[a][4]);
Serial.print(sudoku[a][5]);
Serial.print(sudoku[a][6]);
Serial.print(sudoku[a][7]);
Serial.print(sudoku[a][8]);
Serial.print(sudoku[a][9]);
Serial.print(sudoku[a][10]);
Serial.print(sudoku[a][11]);
Serial.println(sudoku[a][12]);
*/
if (tempcount == 8){ // If only one valid result then find again then mark location as solved
for (byte c = 4; c < 13; c++) { // Read each and identify the only solution
if (sudoku[a][c] > 0) {
sudoku[a][0] = 1; // Set Solved Location Flag
sudoku[a][1] = sudoku[a][c]; // Set value
}
}
}
}
/*
Serial.print(a); Serial.print(" ");
Serial.print(sudoku[a][4]);
Serial.print(sudoku[a][5]);
Serial.print(sudoku[a][6]);
Serial.print(sudoku[a][7]);
Serial.print(sudoku[a][8]);
Serial.print(sudoku[a][9]);
Serial.print(sudoku[a][10]);
Serial.print(sudoku[a][11]);
Serial.println(sudoku[a][12]);
*/
}
}
void reversesolvecolor(){ // subroutine to reverse engineer solved locations in the matrix
and label themas solved
byte tempcount = 0;
for (byte a = 1; a < 82; a++) { // Cycle through all locations
/*
Serial.print(a); Serial.print(" ");
Serial.print(sudoku[a][4]);
Serial.print(sudoku[a][5]);
Serial.print(sudoku[a][6]);
Serial.print(sudoku[a][7]);
Serial.print(sudoku[a][8]);
Serial.print(sudoku[a][9]);
Serial.print(sudoku[a][10]);
Serial.print(sudoku[a][11]);
Serial.println(sudoku[a][12]);
*/
// Read each and count the number that have been elimated
tempcount = 0;
for (byte b = 4; b < 13; b++) {
if (sudoku[a][b] == 0) {// If equal to 0 then count
tempcount++;
}
}
if (tempcount == 8){ // If only one valid result then find again then mark location as solved
for (byte c = 4; c < 13; c++) { // Read each and identify the only solution
if (sudoku[a][c] > 0) {
sudoku[a][0] = 2; // Set Solved Location Flag
sudoku[a][1] = sudoku[a][c]; // Set value
}
}
}
}
/*
Serial.print(a); Serial.print(" ");
Serial.print(sudoku[a][4]);
Serial.print(sudoku[a][5]);
Serial.print(sudoku[a][6]);
Serial.print(sudoku[a][7]);
Serial.print(sudoku[a][8]);
Serial.print(sudoku[a][9]);
Serial.print(sudoku[a][10]);
Serial.print(sudoku[a][11]);
Serial.println(sudoku[a][12]);
*/
}
}
/*
for (byte d = 1; d < 82; d++) { // Cycle through all locations
Serial.print(d); Serial.print(" ");
Serial.print(sudoku[d][4]);
Serial.print(sudoku[d][5]);
Serial.print(sudoku[d][6]);
Serial.print(sudoku[d][7]);
Serial.print(sudoku[d][8]);
Serial.print(sudoku[d][9]);
Serial.print(sudoku[d][10]);
Serial.print(sudoku[d][11]);
Serial.println(sudoku[d][12]);
}
*/
// ROW 1 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 1; a < 10; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 1; r < 10; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 2 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 10; a < 19; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 10; r < 19; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 3 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 19; a < 28; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 19; r < 28; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 4 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 28; a < 37; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 28; r < 37; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 5 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 37; a < 46; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 37; r < 46; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 6 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 46; a < 55; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 46; r < 55; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 7 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 55; a < 64; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 55; r < 64; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 8 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 64; a < 73; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 64; r < 73; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// ROW 9 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 73; a < 82; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 73; r < 82; r++) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
/*
for (byte e = 1; e < 82; e++) { // Cycle through all locations
Serial.print(e); Serial.print(" ");
Serial.print(sudoku[e][4]);
Serial.print(sudoku[e][5]);
Serial.print(sudoku[e][6]);
Serial.print(sudoku[e][7]);
Serial.print(sudoku[e][8]);
Serial.print(sudoku[e][9]);
Serial.print(sudoku[e][10]);
Serial.print(sudoku[e][11]);
Serial.println(sudoku[e][12]);
}
*/
}
Serial.print(sudoku[d][4]);
Serial.print(sudoku[d][5]);
Serial.print(sudoku[d][6]);
Serial.print(sudoku[d][7]);
Serial.print(sudoku[d][8]);
Serial.print(sudoku[d][9]);
Serial.print(sudoku[d][10]);
Serial.print(sudoku[d][11]);
Serial.println(sudoku[d][12]);
}
*/
// COL 1 ************************
// Step through each of Col locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 1; a < 74; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 1; r < 74; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 2 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 2; a < 75; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 2; r < 75; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 3 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 3; a < 76; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 3; r < 76; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 4 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 4; a < 77; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 4; r < 77; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 5 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 5; a < 78; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 5; r < 78; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 6 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 6; a < 79; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 6; r < 79; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 7 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 7; a < 80; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 7; r < 80; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 8 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 8; a < 81; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 8; r < 81; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
// COL 9 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 9; a < 82; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 9; r < 83; r=r+9) {
if ((sudoku[r][sudoku[a][1]+3] == sudoku[a][1] )&& (a!=r)) {
sudoku[r][sudoku[a][1]+3] = 0;
}
}
}
}
/*
for (byte e = 1; e < 82; e++) { // Cycle through all locations
Serial.print(e); Serial.print(" ");
Serial.print(sudoku[e][4]);
Serial.print(sudoku[e][5]);
Serial.print(sudoku[e][6]);
Serial.print(sudoku[e][7]);
Serial.print(sudoku[e][8]);
Serial.print(sudoku[e][9]);
Serial.print(sudoku[e][10]);
Serial.print(sudoku[e][11]);
Serial.println(sudoku[e][12]);
}
*/
}
*/
}
}
}
}
/*
void loadpaneldata(){ // Load specifc Panel identification Data into the Array for each of
the 81 locations
// Load Numbers
// Panel 1
sudoku[1][13] = 1; sudoku[2][13] = 1; sudoku[3][13] = 1;
sudoku[10][13] = 1; sudoku[11][13] = 1; sudoku[12][13] = 1;
sudoku[19][13] = 1; sudoku[20][13] = 1; sudoku[21][13] = 1;
// Panel 2
sudoku[4][13] = 2; sudoku[5][13] = 2; sudoku[6][13] = 2;
sudoku[13][13] = 2; sudoku[14][13] = 2; sudoku[15][13] = 2;
sudoku[22][13] = 2; sudoku[23][13] = 2; sudoku[24][13] = 2;
// Panel 3
sudoku[7][13] = 3; sudoku[8][13] = 3; sudoku[9][13] = 3;
sudoku[16][13] = 3; sudoku[17][13] = 3; sudoku[18][13] = 3;
sudoku[25][13] = 3; sudoku[26][13] = 3; sudoku[27][13] = 3;
// Panel 4
sudoku[28][13] = 4; sudoku[29][13] = 4; sudoku[30][13] = 4;
sudoku[37][13] = 4; sudoku[38][13] = 4; sudoku[39][13] = 4;
sudoku[46][13] = 4; sudoku[47][13] = 4; sudoku[48][13] = 4;
// Panel 5
sudoku[31][13] = 5; sudoku[32][13] = 5; sudoku[33][13] = 5;
sudoku[40][13] = 5; sudoku[41][13] = 5; sudoku[42][13] = 5;
sudoku[49][13] = 5; sudoku[50][13] = 5; sudoku[51][13] = 5;
// Panel 6
sudoku[34][13] = 6; sudoku[35][13] = 6; sudoku[36][13] = 6;
sudoku[43][13] = 6; sudoku[44][13] = 6; sudoku[45][13] = 6;
sudoku[52][13] = 6; sudoku[53][13] = 6; sudoku[54][13] = 6;
// Panel 7
sudoku[55][13] = 7; sudoku[56][13] = 7; sudoku[57][13] = 7;
sudoku[64][13] = 7; sudoku[65][13] = 7; sudoku[66][13] = 7;
sudoku[73][13] = 7; sudoku[74][13] = 7; sudoku[75][13] = 7;
// Panel 8
sudoku[58][13] = 8; sudoku[59][13] = 8; sudoku[60][13] = 8;
sudoku[67][13] = 8; sudoku[68][13] = 8; sudoku[69][13] = 8;
sudoku[76][13] = 8; sudoku[77][13] = 8; sudoku[78][13] = 8;
// Panel 9
sudoku[61][13] = 9; sudoku[62][13] = 9; sudoku[63][13] = 9;
sudoku[70][13] = 9; sudoku[71][13] = 9; sudoku[72][13] = 9;
sudoku[79][13] = 9; sudoku[80][13] = 9; sudoku[81][13] = 9;
// Used to identify and highlight errors in a current matrix - use solve method however
instead of solving outcome just highlight conflicts in red
void helpbutton(){
// Horizontal *********************
// ROW 1 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 1; a < 10; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 1; r < 10; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 2 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 10; a < 19; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 10; r < 19; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 3 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 19; a < 28; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 19; r < 28; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 4 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 28; a < 37; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 28; r < 37; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 5 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 37; a < 46; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 37; r < 46; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 6 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 46; a < 55; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 46; r < 55; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 7 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 55; a < 64; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 55; r < 64; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 8 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 64; a < 73; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 64; r < 73; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// ROW 9 ************************
// Step through each of ROW locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 73; a < 82; a++) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 73; r < 82; r++) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// Vertical ****************
// COL 1 ************************
// Step through each of Col locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 1; a < 74; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 1; r < 74; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 2 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 2; a < 75; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 2; r < 75; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 3 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 3; a < 76; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 3; r < 76; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 4 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 4; a < 77; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 4; r < 77; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 5 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 5; a < 78; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 5; r < 78; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 6 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 6; a < 79; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 6; r < 79; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 7 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 7; a < 80; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 7; r < 80; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 8 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 8; a < 81; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 8; r < 81; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// COL 9 ************************
// Step through each of COL locations and delete duplicates of the Solved location. Ignore
the current location you are solving for
for (byte a = 9; a < 82; a=a+9) { // Cycle through all locations
if (sudoku[a][0] > 0) { // Identify the locations that are already solved and delete any
occurences that are already in scope of enquiry
for (byte r = 9; r < 83; r=r+9) {
if ((sudoku[a][1] == sudoku[r][1] ) && (a!=r)) { // Current location is not a master value
and it is duplicate then color RED
// Refresh only the location concerned with new value and show colour coded
//First Clear Location
tft.fillRect(sudoku[a][3], sudoku[a][2], 15, 15, BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor( sudoku[a][3], sudoku[a][2]); tft.println(sudoku[a][1]);
}
}
}
}
// Panels *******************
}
}
}
}
// Horizontal conflict help function - Step through data and identify manually changed
locations as conflicts in RED. Leave items set at WHITE as WHITE
// Vertical conflict help function - Step through data and identify manually changed
locations as conflicts in RED. Leave items set at WHITE as WHITE
// Panel conflict help function - Step through data and identify manually changed locations
as conflicts in RED. Leave items set at WHITE as WHITE
void uniquecandidate() { // Each panel, row and column on a Sudoku board must contain
every number between 1 and 9.
// Therefore, if a number, say 4, can only be put in a single cell within a block/column/row,
then that number is guaranteed to fit there.
/*
*/
byte tempcount = 0;
for (byte v = 1; v < 10; v++) { // Step through all possible unique location values in each
panel
Buzzer
× 1
IR receiver (generic)
× 1
JustBoom IR Remote
× 1
× 1
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
This clock only works for the Elegoo remote as shown below:
Story
Have you ever fallen right back to sleep after snoozing your alarm
clock? That's because you're still bran-dead when you hit that snooze
button. A simple way to prevent this is to wake your brain up with a
simple math problem.
Earlier this year, I bought the Elegoo Starter Kit UNO R3 Project with
the hope of being able to make some cool stuff that I once saw like
robot or toy car. This is one of my very first project using Arduino Uno
R3 and since I've just started it, the clock itself looks like crap. But it's
still better than nothing, right? Link to the kit is here.
Libraries
For this little project, there's a few libraries you need to download and
format as you can see below:
https://github.com/z3t0/Arduino-IRremote.
*For the IRremote library, you'll have to go to boarddefs.h, find the
following segment of code:
// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
// ATmega48, ATmega88, ATmega168, ATmega328
//#define IR_USE_TIMER1 // tx = pin 9
#define IR_USE_TIMER2 // tx = pin 3
and change it to:
// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
// ATmega48, ATmega88, ATmega168, ATmega328
#define IR_USE_TIMER1 // tx = pin 9
//#define IR_USE_TIMER2 // tx = pin 3
https://github.com/arduino-libraries/LiquidCrystal
https://github.com/adafruit/RTClib
The cardboard box
Choose and cut whatever cardboard that fits your circuit best. For me, I
just cut a random amazon delivery box, and it works great!
The circuit
Assemble your circuit according to the following image
To save some place because my goal is making an as small and
compact an alarm clock as possible, I use the Arduino Prototype Shield
v.5 that comes with the kit I bought. You can choose to use or not to
use the board.
Fits perfectly! :)
Tips
- When compiling the code, don't hit verify (the check icon) but hit
upload (the arrow icon) instead.
- When you upload, if you want the clock to have the right time on it,
then don't unplug it from the computer or unplug after connect it to
external battery.
- If you unplug it and then connect it to the power source, the time
shows is the time when you last upload it.
Remote Controller
+ ST/REPT: Hit it if you want to set Alarm. If you've entered "Set
hour," hit it again to set minute and again to set second. Hit it one last
time to finish setting up alarm
+ The red power button: This button is programmed as a backspace
button. Hit it once you've finished setting alarm and want to change
(since this remote is a really crappy one, hit power button multiple
times until the second line of the LCD indicating the alarm turns off),
or when you're typing the wrong answer for the simple math problem
(hit it until the answer turns into zero)
+ Apart from number buttons, ST/REPT and red power button, other
buttons have no use.
SCHEMATICS
CODE
#include <IRremote.h>
#include <IRremoteInt.h>
#include <LiquidCrystal.h>
#include "RTClib.h"
/**
* Go to boarddefs.h
* // Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
* #else
* #define IR_USE_TIMER1 tx = pin 9
* //#define IR_USE_TIMER2 // tx = pin 3
*/
#include <stdlib.h>
RTC_DS1307 rtc;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int buzzerPin = 10;
int RECV_PIN = 9;
IRrecv irrecv(RECV_PIN);
decode_results results;
long num[10] = {0xFF6897, 0xFF30CF, 0xFF18E7, 0xFF7A85, 0xFF10EF, 0xFF38C7,
0xFF5AA5, 0xFF42BD, 0xFF4AB5, 0xFF52AD};
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int setAlarm = 0;
void setup() {
lcd.begin(16, 2);
Serial.begin(9600);
irrecv.enableIRIn();
if(rtc.begin()&&rtc.isrunning()){
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
DateTime now = rtc.now();
lcd.setCursor(0, 0);
if(now.hour()<10)lcd.print("0");
lcd.print(now.hour());
lcd.print(':');
if(now.minute()<10)lcd.print("0");
lcd.print(now.minute());
lcd.print(':');
if(now.second()<10)lcd.print("0");
lcd.print(now.second());
lcd.print(" ");
getAlarm();
}
void getAlarm(){
int ques1 = rand()%100+1;
int ques2 = rand()%100+1;
int ans = ques1 + ques2;
if (irrecv.decode(&results)){
Serial.println(results.value, HEX);
irrecv.resume();
if(results.value==0xFFB04F){
setAlarm=1;
}else if(results.value==0xFFFFFFFF){
setAlarm = setAlarm;
}
}
if(digitalRead(buzzerPin)==HIGH){
setAlarm=5;
}
while(setAlarm==1){
lcd.setCursor(0,0);
lcd.print("Set Hour");
lcd.setCursor(0,1);
if(irrecv.decode(&results)){
for(int i = 0; i<10; i++){
if(results.value==num[i]){
a = a*10+i;
}else if(results.value==0xFFFFFFFF){
a = a;
}
irrecv.resume();
}
if(a<24){
lcd.print(a);
if(results.value==0xFFB04F){
setAlarm=2;
}
}else{
lcd.clear();
setAlarm = 1;
a=0;
}
}
}
while(setAlarm==2){
lcd.setCursor(0,0);
lcd.print("Set Minute");
lcd.setCursor(0,1);
if(irrecv.decode(&results)){
for(int i = 0; i<10; i++){
if(results.value==num[i]){
b = b*10+i;
}else if(results.value==0xFFFFFFFF){
b = b;
}else if(results.value==0xFFB04F){
setAlarm++;
}
irrecv.resume();
}
lcd.print(a);
lcd.print(':');
if(b<60){
lcd.print(b);
if(results.value==0xFFB04F){
setAlarm=3;
}
}else{
lcd.clear();
setAlarm = 2;
b=0;
}
}
}
while(setAlarm==3){
lcd.setCursor(0,0);
lcd.print("Set Second");
lcd.setCursor(0,1);
if(irrecv.decode(&results)){
for(int i = 0; i<10; i++){
if(results.value==num[i]){
c = c*10+i;
}else if(results.value==0xFFFFFFFF){
c = c;
}else if(results.value==0xFFB04F){
setAlarm++;
}
irrecv.resume();
}
lcd.print(a);
lcd.print(':');
lcd.print(b);
lcd.print(':');
if(c<60){
lcd.print(c);
if(results.value==0xFFB04F){
setAlarm=4;
}
}else{
lcd.clear();
setAlarm = 3;
c=0;
}
}
}
while(setAlarm==4){
lcd.setCursor(0,1);
lcd.print("Alarm-");
if(a<10)lcd.print("0");
lcd.print(a);
lcd.print(':');
if(b<10)lcd.print("0");
lcd.print(b);
lcd.print(':');
if(c<10)lcd.print("0");
lcd.print(c);
if(results.value==0xFFB04F){
setAlarm=0;
}
}
DateTime now = rtc.now();
if(now.hour()==a && now.minute()==b && now.second()==c){
tone(buzzerPin, 100);
a=0;
b=0;
c=0;
}
if(irrecv.decode(&results)){
if(results.value==0xFFA25D){
a=0;
b=0;
c=0;
lcd.setCursor(0,1);
lcd.clear();
}
}
while(setAlarm==5){
lcd.setCursor(0,0);
lcd.print(ques1);
lcd.print('+');
lcd.print(ques2);
lcd.print(" ");
if(irrecv.decode(&results)){
for(int i = 0; i<10; i++){
if(results.value==num[i]){
d = d*10+i;
}else if(results.value==0xFFA25D){
d=0;
lcd.print(" ");
}
irrecv.resume();
}
lcd.print(d);
}
if(d==ans){
noTone(buzzerPin);
setAlarm=0;
lcd.setCursor(0,1);
lcd.clear();
d=0;
}
}
}
109) Arduino Gesture Mouse
COMPONENTS AND SUPPLIES
Arduino Leonardo
× 1
Breadboard (generic)
× 1
× 1
Adafruit Joystick
× 1
APPS AND ONLINE SERVICES
Arduino IDE
1. Leonardo:
Arduino Leonardo is an old board but the only compatible board for
this project. It has the required SCL and SDA pin for connection of
MPU6050.
Connections: Connect the 5V and GND to breadboard.
2. Joystick:
Use: We use the joystick as a keyboard. While playing a game,we use it
move the character in front or back or sideways,etc.
Connections: Connect the GND and 5V in the same line as that of
Leonardo as shown in the schematics. Connect the VRX to A1 (Analog
Pin 1) and VRY to A0 of Leonardo.
3. MPU6050:
Use: The MPU6050 is a 6 DOF (Degrees of Freedom) or a six axis
IMU sensor, which means that it gives six values as output. Three
values from the accelerometer and three from the gyroscope. It is
basically used as a mouse.
Connections: Connect the GND and VCC in the railing as in
schematics. Connect the SCL and SDA to SCL and SDA of Leonardo.
4. Button:
Use: Used as a fire button while playing any game.
Connections: Connect the button pin to Digital Pin 1 and other to GND.
Connect everything according to the schematics. Upload the code to
Leonardo and watch the fun!
Note: To switch on the joystick, press it down once.
SCHEMATICS
CODE
#include <Keyboard.h>
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>
#include <Mouse.h>
#define LBUT 7
#define RBUT 5
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
MPU6050 mpu;
int16_t ax, ay, az, gx, gy, gz;
int angleToDistance(int a)
{
if (a < -80)
{
return -40;
}
else if (a < -65) {
return -20;
}
else if (a < -50) {
return -10;
}
else if (a < -15) {
return -5;
}
else if (a < -5) {
return -1;
}
else if (a > 80) {
return 40;
}
else if (a > 65) {
return 20;
}
else if (a > 15) {
return 10;
}
else if (a > 5) {
return 1;
}
}
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
Keyboard.begin();
Mouse.begin();
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
Keyboard.releaseAll();
Keyboard.press('a'); //for a
Keyboard.releaseAll();
}
Keyboard.press('d'); //for d
Keyboard.releaseAll();
}
}
void keyboard()
{
xPosition = analogRead(xPin);
yPosition = analogRead(yPin);
buttonState = digitalRead(buttonPin);
Serial.print("X: ");
Serial.print(xPosition);
Serial.print(" | Y: ");
Serial.print(yPosition);
Serial.print(" | Button: ");
Serial.println(buttonState);
Keyboard.releaseAll();
Keyboard.press('a'); //for a
Keyboard.releaseAll();
}
}
}
void fire()
{
× 1
SCHEMATICS
CODE
/*
A Power Router is a device that detects any homemade electrical energy in exceed. If so
several actions can be taken :
- with the Triac function: gradually switch on a resistive load that will take all the
exceed energy. This load must be resistive (edison light, water heat, etc...) due to
the power factor which must stay near 1.
- with the SSR function: prevent against any exceed by performing a load shedding : just
before injection in the public power grid, either a load can be add to increase
consumtion, or a power generator (solar panel, wind turbine) can be stopped.
This device is actually in operation in two homes with a power load of 350W and 1000W.
Materials :
1* Arduino Uno R3 - IDE version 1.8.7
1* AC current sensor 20A/25mA
1* AC-AC 230V-2.5V transformer
1* LCD 1602 with I2C extension
1* shield : see manual documentation for wiring implementation
1* triac dimming module with zero-cross detection
3* push-buttons
1* SSR + 1* transistor NPN, 1* transistor PNP, few resistors, capacitors...
Pinup :
- pin A0 (analog 0) => AC current sensor
- pin A1 (analog 1) => AC voltage sensor
- pin A4 (analog 4) => SDA output for LCD
- pin A5 (analog 5) => SCL output for LCD
- pin 2 (numeric 2) => zero-cross detection
- pin 3 (numeric 3) => output to a LED which indicate pwm
- pin 4 (numeric 4) => input from push-button "entry"
- pin 5 (numeric 5) => input from push-button "+"
- pin 6 (numeric 6) => input from push-button "-"
- pin 10 (numeric 10) => pwm output that drives the Triac
- pin 11 (numeric 11) => output to load shedding
- pin 13 (numeric 13) => overflow LED alarm
*/
#include <EEPROM.h>
#include <avr/wdt.h> // documentation: https://tushev.org/articles/arduino/5/arduino-and-
watchdog-timer
#include <TimerOne.h> // library to install:
http://www.arduino.cc/playground/Code/Timer1
#include <LiquidCrystal_I2C.h> // https://github.com/fdebrabander/Arduino-
LiquidCrystal-I2C-library
// calibration variables:
// Calibration of measures which depend of the hardware. Must be done once at the
beginning :
// first: ajust Vcalibration for reading 230V on the console
// after: Icalibration by comparing with a multimeter
// optional: phasecalibration can be adjust with the help of a powermeter
int limitP = 1; // hysteresis of tolerance for the Triac action: if 1 => sensibility is
+1W/-1W
int delestON = 1; // threshold to start the load shedding
int delestOFF = 350; // value to stop the load shedding
bool etat_delest_repos = HIGH; // inactive state of the load shedding: HIGH for switched
on
byte dimmax = 128; // max value of dim that shuttoff the Triac
byte dim = dimmax; // Dimming level (0-128) 0 = on, 128 = 0ff
char periodStep = 75; // value of the timer (65 for 60Hz, 78 for 50Hz, in s)
// according the formula (500000/AC_freq)/NumSteps = periodStep
// 78*128=10ms=1/2 period 50Hz but in fact 75 works better
volatile int i = 0; // Variable to use as a counter
volatile bool zero_cross = false; // zero-cross detected for driving the Triac
volatile bool zero_cross_flag = false; // zero-cross detected for power calcultion
int readV, memo_readV, readI; // voltage and current in bits (0 1023 bits)
float rPower, V, I, sqV, sumV = 0, sqI, sumI = 0, instP, sumP = 0;
byte zero_crossCount = 0; // halp-period counter
// other variables
// documentation : http://arduino-info.wikispaces.com/LCD-Blue-I2C
// Set the pins on the I2C chip used for LCD connections:
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// => pinup for I2C with l'Arduino Uno R3 : SDA = A4, SCL = A5
//
// SETUP
//_____________________________________________________________________________________
// EEPROM functions are used to calculate how many time the device has rebooted
// EEPROM stored values are of type char.
// default values in case of first use are set to 255
unsigned char reboot_high = EEPROM.read(0); // to get the high value of the number
unsigned char reboot_low = EEPROM.read(1); // to get the low value of the number
unsigned int reboot = (reboot_high << 8) + reboot_low;
reboot++;
EEPROM.update(0, highByte(reboot));
EEPROM.update(1, lowByte(reboot));
// LCD initialisation
lcd.begin(); // initialize the lcd for 16 chars 2 lines
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("POWER ROUTER");
lcd.setCursor(0, 1);
lcd.print("is starting !");
// console initialisation
Serial.begin(250000);
Serial.println ();
Serial.print("PLEASE NOTE : ");
Serial.print(reboot);
Serial.println(" total number of reboots");
Serial.println();
Serial.println("Ready to start ...");
Serial.println ();
delay(500);
if( VERBOSE == true ) Serial.print(" Pu (W) || dimstep | dim || load shedding");
else Serial.println("It is working now !");
Serial.println();
} // End setup
//
// ZERO CROSS DETECT : zero-cross interrupt
//_____________________________________________________________________________________
//
// DIM CHECK : drive the Triac
//_____________________________________________________________________________________
void dim_check() { // Function will fire the triac at the proper time
if(zero_cross == true && dim < dimmax) // First check to make sure the zero-cross has
{ // happened else do nothing
if(i>dim) { // i is a counter that defines the fire delay. higher is dim longer i will
count
digitalWrite(triacPin, HIGH); // and later the triac will fire
delayMicroseconds(50); // Pause briefly to ensure the triac turned on
digitalWrite(triacPin, LOW); // Turn off the Triac gate, but the triac stays switch on
until OV
i = 0; // Reset the counter for the next cycle
zero_cross = false;
}
else i++; // If the dimming value has not been reached, increase it
} // End zero_cross check
} // End dim_check function
//
// LOOP
//_____________________________________________________________________________________
// 2nd part: dim and dimstep calculation to drive the Triac, and load shedding management
//_____________________________________________________________________________________
//
// dimstep calculation: higher is the power to take in charge, higher will be dimstep
if( rPower > 0 ) { dimstep = rPower/10/reactancelevel + 1; }
else { dimstep = 1 - rPower/10/reactancelevel; }
if( rPower > limitP ) { // injection increases, the delay to fire the Triac decreases
if( dim > dimstep ) dim -= dimstep; else dim = 0;
}
else if( rPower < -limitP ) { // injection decreases, the delay to fire the Triac decreases
if( dim + dimstep < dimmax ) dim += dimstep; else dim = dimmax;
}
// console display
if( CALIBRATION == true ) {
Serial.print(V);
Serial.print(" | ");
Serial.print(I/1000);
Serial.print(" | ");
Serial.print(rPower);
Serial.println();
}
if( VERBOSE == true ) {
Serial.print(rPower);
Serial.print(" || ");
Serial.print(dimstep);
Serial.print(" | ");
Serial.print(dim);
Serial.print(" || ");
Serial.print(" load shedding : ");
Serial.print(delestage);
Serial.print(" seconds : ");
Serial.println(temps_actuel - loadsheddingcounter);
}
else delay(1); // required for stability
nogrid:
wdt_reset(); // watchdog reset
//
// NEXT_WINDOWS : next windows procedure
//_____________________________________________________________________________________
void next_windows() {
//
// PUSH_BUTTON : return value depending of the state of the 3 push-buttons
//_____________________________________________________________________________________
byte push_button() {
if( digitalRead(pushEntryPin) == 0 ) {
count_before_timeout = 0; // reset the timeout counter
lcd.backlight(); // switch on display
return 1;
}
if( digitalRead(pushPlusPin) == 0 ) {
count_before_timeout = 0; // reset the timeout counter
lcd.backlight(); // switch on display
refresh_tempo = 1; // temporary lower display update duration
return 2;
}
if( digitalRead(pushMinusPin) == 0 ) {
count_before_timeout = 0; // reset the timeout counter
lcd.backlight(); // switch on display
refresh_tempo = 1; // temporary lower display update duration
return 3;
}
refresh_tempo = 2; // go back to initial value
return 0;
} // end of push_button function
111) Arduino Serial to LANC
COMPONENTS AND SUPPLIES
SparkFun Arduino Pro Mini 328 -
5V/16MHz
× 1
SCHEMATICS
All the hardware you need for this project, you can skip the push
button (not used). The NPN transistor can be almost any small-signal
type.
CODE
/*
Arduino LANC<->RS232 interface
For communicating with cameras via LANC
For the interface circuit interface see
------------------------------------------------------------------------------------------
Comments regarding service mode for Sony second generation D8 camcorders:
DCR-TRV8000E, DCR-TRV8100E, DCR-TRV120E, DCR-TRV125E, DCR-TRV320E,
DCR-TRV325E
DCR-TRV420E, DCR-TRV520E, DCR-TRV620E, DCR-TRV725E
LANC message layout when reading/writing EEPROM(8 bytes each sent with LSB first)
B0 B1 B2 B3 B4 B5 B6 B7
The following commands is used to navigate the EEPROM and change data
B1 B2
FFh 00h = Read command, tells you current page:address:data without changing anything
FFh 67h = Increase page by 1
FFh 65h = Decrase page by 1
FFh 38h = Increase address by 1
FFh 36h = Decrase address by 1
FFh 34h = Increase data by 1
FFh 30h = Decrase data by 1
FFh 32h = STORE command
------------------------------------------------------------------------------------------
*/
// The code uses fast I/O write because its time critical,
// therefore setting pins are done by writing directly to the registers:
#define cmdPinON (PORTD = B10000000) // Set digtal pin 7 (PD7)
#define cmdPinOFF (PORTD = B00000000) // Reset digtal pin 7 (PD7)
#define ledON (PORTB = B00100000) // Set LED pin 13 (PB5)
#define ledOFF (PORTB = B00000000) // Reset LED pin 13 (PB5)
#define lancPinREAD (PINB & B00001000) // Reads pin 11 (PB3)
#define lancPin 11
int bitDura = 104; // Duration of one LANC bit in microseconds, orginal 104
int halfbitDura = 52; // Half of bitDura
byte strPointer = 0; // Index when receiving chars
char inString[5]; // A string to hold incoming data
char outString[25]; // A string to hold outgoing data
boolean strComplete = false; // Indicator to see if the string is complete
boolean lancCmd[16]; // Array for the lancCmd in bits
boolean lancMessage[64]; // Array for the complete LANC message in bits
void setup() {
DDRD = DDRD | B10000000; // Config cmdPin as output
DDRB = DDRB & B11110111; // Config lancPin as input
DDRB = DDRB | B00100000; // Config ledPin as output
pinMode(lancPin, INPUT); // Listens to the LANC line, used for pulseIn function
cmdPinOFF; // Reset LANC control pin so that the LANC line is
unaffected(HIGH)
Serial.begin(57600); // Start serial port
Serial.println("Welcome to the Arduino LANC-RS232 interface");
Serial.println("Send two bytes in hex form etc. 02AF and wait for reply from camera");
}
void loop() {
void bitarraytohexchar() {
// The bit array lancMessage contains the whole LANC message (8 bytes) with LSB first
// This function converts them to hex chars and stores them in outString (16 chars)
byte temp = 0;
outString[24] = '\n';
boolean hexchartobitarray() {
// The hex code in char (4 chars) is located in inString
// This function fills the lancCmd array with the bits in the order they should be sent
// First byte 1 then byte 2 but with LSB first for both bytes
return 1;
}
int i = 0;
int bytenr = 0;
while (repeats) {
i = 0;
bytenr = 0;
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read(); // Get the new byte
inString[strPointer++] = inChar; // Add it to the input string
if ((inChar == '\n') || (inChar == '\r') || (strPointer > 4)) { // If the incoming character is a
newline, carriage return or 4 bytes has been received flag so the main loop can act
strComplete = true;
strPointer = 0;
}
}
}
int pow2(int x) {
switch (x) {
case 0:
return 1;
break;
case 1:
return 2;
break;
case 2:
return 4;
break;
case 3:
return 8;
break;
case 4:
return 16;
break;
case 5:
return 32;
break;
case 6:
return 64;
break;
case 7:
return 128;
break;
default:
return 0;
break;
}
}
× 1
LEDs
× 4
× 4
Buzzer
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
android apps
void setup() {
pinMode(light_FR, OUTPUT);
pinMode(light_FL, OUTPUT);
pinMode(light_BR, OUTPUT);
pinMode(light_BL, OUTPUT);
pinMode(horn_Buzz, OUTPUT);
pinMode(ENA_m1, OUTPUT);
pinMode(ENB_m1, OUTPUT);
pinMode(ENA_m2, OUTPUT);
pinMode(ENB_m2, OUTPUT);
pinMode(IN_11, OUTPUT);
pinMode(IN_12, OUTPUT);
pinMode(IN_13, OUTPUT);
pinMode(IN_14, OUTPUT);
pinMode(IN_21, OUTPUT);
pinMode(IN_22, OUTPUT);
pinMode(IN_23, OUTPUT);
pinMode(IN_24, OUTPUT);
Serial.begin(9600);
void goAhead(){
digitalWrite(IN_11, LOW);
digitalWrite(IN_12, HIGH);
analogWrite(ENA_m1, speedCar);
digitalWrite(IN_13, HIGH);
digitalWrite(IN_14, LOW);
analogWrite(ENB_m1, speedCar);
digitalWrite(IN_21, HIGH);
digitalWrite(IN_22, LOW);
analogWrite(ENA_m2, speedCar);
digitalWrite(IN_23, LOW);
digitalWrite(IN_24, HIGH);
analogWrite(ENB_m2, speedCar);
void goBack(){
digitalWrite(IN_13, LOW);
digitalWrite(IN_14, HIGH);
analogWrite(ENB_m1, speedCar);
digitalWrite(IN_21, LOW);
digitalWrite(IN_22, HIGH);
analogWrite(ENA_m2, speedCar);
digitalWrite(IN_23, HIGH);
digitalWrite(IN_24, LOW);
analogWrite(ENB_m2, speedCar);
void goRight(){
digitalWrite(IN_11, LOW);
digitalWrite(IN_12, HIGH);
analogWrite(ENA_m1, speedCar);
digitalWrite(IN_13, HIGH);
digitalWrite(IN_14, LOW);
analogWrite(ENB_m1, speedCar);
digitalWrite(IN_21, LOW);
digitalWrite(IN_22, HIGH);
analogWrite(ENA_m2, speedCar);
digitalWrite(IN_23, HIGH);
digitalWrite(IN_24, LOW);
analogWrite(ENB_m2, speedCar);
void goLeft(){
digitalWrite(IN_11, HIGH);
digitalWrite(IN_12, LOW);
analogWrite(ENA_m1, speedCar);
digitalWrite(IN_13, LOW);
digitalWrite(IN_14, HIGH);
analogWrite(ENB_m1, speedCar);
digitalWrite(IN_21, HIGH);
digitalWrite(IN_22, LOW);
analogWrite(ENA_m2, speedCar);
digitalWrite(IN_23, LOW);
digitalWrite(IN_24, HIGH);
analogWrite(ENB_m2, speedCar);
void goAheadRight(){
digitalWrite(IN_11, HIGH);
digitalWrite(IN_12, LOW);
analogWrite(ENA_m1, speedCar/speed_Coeff);
digitalWrite(IN_13, LOW);
digitalWrite(IN_14, HIGH);
analogWrite(ENB_m1, speedCar/speed_Coeff);
digitalWrite(IN_21, LOW);
digitalWrite(IN_22, HIGH);
analogWrite(ENA_m2, speedCar);
digitalWrite(IN_23, HIGH);
digitalWrite(IN_24, LOW);
analogWrite(ENB_m2, speedCar);
void goAheadLeft(){
digitalWrite(IN_11, HIGH);
digitalWrite(IN_12, LOW);
analogWrite(ENA_m1, speedCar);
digitalWrite(IN_13, LOW);
digitalWrite(IN_14, HIGH);
analogWrite(ENB_m1, speedCar);
digitalWrite(IN_21, LOW);
digitalWrite(IN_22, HIGH);
analogWrite(ENA_m2, speedCar/speed_Coeff);
digitalWrite(IN_23, HIGH);
digitalWrite(IN_24, LOW);
analogWrite(ENB_m2, speedCar/speed_Coeff);
void goBackRight(){
digitalWrite(IN_11, LOW);
digitalWrite(IN_12, HIGH);
analogWrite(ENA_m1, speedCar/speed_Coeff);
digitalWrite(IN_13, HIGH);
digitalWrite(IN_14, LOW);
analogWrite(ENB_m1, speedCar/speed_Coeff);
digitalWrite(IN_21, HIGH);
digitalWrite(IN_22, LOW);
analogWrite(ENA_m2, speedCar);
digitalWrite(IN_23, LOW);
digitalWrite(IN_24, HIGH);
analogWrite(ENB_m2, speedCar);
void goBackLeft(){
digitalWrite(IN_11, LOW);
digitalWrite(IN_12, HIGH);
analogWrite(ENA_m1, speedCar);
digitalWrite(IN_13, HIGH);
digitalWrite(IN_14, LOW);
analogWrite(ENB_m1, speedCar);
digitalWrite(IN_21, HIGH);
digitalWrite(IN_22, LOW);
analogWrite(ENA_m2, speedCar/speed_Coeff);
digitalWrite(IN_23, LOW);
digitalWrite(IN_24, HIGH);
analogWrite(ENB_m2, speedCar/speed_Coeff);
void stopRobot(){
digitalWrite(IN_11, LOW);
digitalWrite(IN_12, LOW);
analogWrite(ENA_m1, speedCar);
digitalWrite(IN_13, LOW);
digitalWrite(IN_14, LOW);
analogWrite(ENB_m1, speedCar);
digitalWrite(IN_21, LOW);
digitalWrite(IN_22, LOW);
analogWrite(ENA_m2, speedCar);
digitalWrite(IN_23, LOW);
digitalWrite(IN_24, LOW);
analogWrite(ENB_m2, speedCar);
void loop(){
if (Serial.available() > 0) {
command = Serial.read();
stopRobot(); //Initialize with motors stopped.
if (lightFront) {digitalWrite(light_FR, HIGH); digitalWrite(light_FL, HIGH);}
if (!lightFront) {digitalWrite(light_FR, LOW); digitalWrite(light_FL, LOW);}
if (lightBack) {digitalWrite(light_BR, HIGH); digitalWrite(light_BL, HIGH);}
if (!lightBack) {digitalWrite(light_BR, LOW); digitalWrite(light_BL, LOW);}
if (horn) {digitalWrite(horn_Buzz, HIGH);}
if (!horn) {digitalWrite(horn_Buzz, LOW);}
switch (command) {
case 'F':goAhead();break;
case 'B':goBack();break;
case 'L':goLeft();break;
case 'R':goRight();break;
case 'I':goAheadRight();break;
case 'G':goAheadLeft();break;
case 'J':goBackRight();break;
case 'H':goBackLeft();break;
case '0':speedCar = 100;break;
case '1':speedCar = 115;break;
case '2':speedCar = 130;break;
case '3':speedCar = 145;break;
case '4':speedCar = 160;break;
case '5':speedCar = 175;break;
case '6':speedCar = 190;break;
case '7':speedCar = 205;break;
case '8':speedCar = 220;break;
case '9':speedCar = 235;break;
case 'q':speedCar = 255;break;
case 'W':lightFront = true;break;
case 'w':lightFront = false;break;
case 'U':lightBack = true;break;
case 'u':lightBack = false;break;
case 'V':horn = true;break;
case 'v':horn = false;break;
}
}
}
113) Arduino Control Servo Power with a Transistor projet
× 1
× 1
I was looking for an easy way to "cut" the power to a servo when it was
not in use to conserve power and was surprised to see so few articles
and blog posts on the subject. I found some, but usually using the
wrong transistor or mechanical relays. I've found this method as the
most elegant approach and thought it worth sharing. I'm not an
electronics engineer, but from what I've read, this is the proper way to
provide high current to a device using an Arduino.
SCHEMATICS
CODE
#include <Servo.h>
Servo servo;
int powerControl = 8;
int servoPin = 10;
void setup() {
//Debug
Serial.begin(9600);
void loop() {
/*--------------------------------
ATTACH servo signal to pin 10, turn
ON servo power and MOVE (0 to 180)
--------------------------------*/
/*--------------------------------
ATTACH servo signal to pin 10, turn
ON servo power and MOVE (0 to 180)
--------------------------------*/
/*--------------------------------
Turn OFF servo, DETACH pin 10 and
WAIT for 1 second
--------------------------------*/
× 1
Hello, and welcome, this fast tutorial is about the PAJ7620 hand
gestures sensor, it permits your hand gestures to be detected by the
Arduino board, and then you can use it to control lights, robots (cool
stuff), HMI, games… using IR LED and optical CMOS array, it can
detect up to 15 gestures.
This one costs around $2-3 only but is not efficient (as you can see in
the video) as the thermal imaging arrays that can much detect complex
gestures cost around $30-40.
The gestures that can be detected are: right, left, up, down, forward,
backward, clockwise, counter-lockwise and waving. Those are the
basic 9 then you can add right-left, left-right, up-down, down-up,
forward-backward, backward-forward. (Check the video to know the
differences).
There are two ways of detecting:
Near, which is on 5-15 cm distance with 60° angle
Far, on 15-30 cm distance with 30° angle
For this project I’m going to interface it with Arduino Uno board, and
I’ll use a LCD i²c screen to show the gesture detected, using this
method you can adapt it to whatever project you’re working on.
Parts
Uno board
LCD i²c (Optional)
PAJ7620
Test
The tests are straight forward, just plug and start moving your hands.
Direct test with the Serial Monitor
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include "paj7620.h"
#define I2C_ADDR 0x27 //I2C adress, you should use the code to scan the adress first
(0x27) here
#define BACKLIGHT_PIN 3 // Declaring LCD Pins
#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);
void setup() {
paj7620Init();
lcd.begin (16,2);
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
lcd.setBacklight(HIGH); //Lighting backlight
void printing(){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Gesture Sensor");
lcd.setCursor(0,1);
}
void loop() {
switch (data) // When different gestures be detected, the variable 'data' will be set
to different values by paj7620ReadReg(0x43, 1, &data).
{
case GES_RIGHT_FLAG:
delay(GES_ENTRY_TIME);
paj7620ReadReg(0x43, 1, &data);
if(data == GES_FORWARD_FLAG)
{
printing();
lcd.print("Forward");
delay(GES_QUIT_TIME);
}
else if(data == GES_BACKWARD_FLAG)
{
printing();
lcd.print("Backward");
delay(GES_QUIT_TIME);
}
else
{
printing();
lcd.print("Right");
}
break;
case GES_LEFT_FLAG:
delay(GES_ENTRY_TIME);
paj7620ReadReg(0x43, 1, &data);
if(data == GES_FORWARD_FLAG)
{
printing();
lcd.print("Forward");
delay(GES_QUIT_TIME);
}
else if(data == GES_BACKWARD_FLAG)
{
printing();
lcd.print("Backward");
delay(GES_QUIT_TIME);
}
else
{
printing();
lcd.print("Left");
}
break;
case GES_UP_FLAG:
delay(GES_ENTRY_TIME);
paj7620ReadReg(0x43, 1, &data);
if(data == GES_FORWARD_FLAG)
{
printing();
lcd.print("Forward");
delay(GES_QUIT_TIME);
}
else if(data == GES_BACKWARD_FLAG)
{
printing();
lcd.print("Backward");
delay(GES_QUIT_TIME);
}
else
{
printing();
lcd.print("Up");
}
break;
case GES_DOWN_FLAG:
delay(GES_ENTRY_TIME);
paj7620ReadReg(0x43, 1, &data);
if(data == GES_FORWARD_FLAG)
{
printing();
lcd.print("Forward");
delay(GES_QUIT_TIME);
}
else if(data == GES_BACKWARD_FLAG)
{
printing();
lcd.print("Backward");
delay(GES_QUIT_TIME);
}
else
{
printing();
lcd.print("Down");
}
break;
case GES_FORWARD_FLAG:
printing();
lcd.print("Forward");
delay(GES_QUIT_TIME);
break;
case GES_BACKWARD_FLAG:
printing();
lcd.print("Backward");
delay(GES_QUIT_TIME);
break;
case GES_CLOCKWISE_FLAG:
printing();
lcd.print("Clockwise");
break;
case GES_COUNT_CLOCKWISE_FLAG:
printing();
lcd.print("anti-clockwise");
break;
default:
paj7620ReadReg(0x44, 1, &data1);
if (data1 == GES_WAVE_FLAG)
{
printing();
lcd.print("wave");
}
break;
}
}
delay(100);
}
115) Arduino Servo Motor Control with Remote projet
× 1
× 1
IR receiver (generic)
× 1
JustBoom IR Remote
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
With this simple Arduino project you can control servo using a remote
control. All you need is an Arduino Uno board (or similar), a servo
motor (doesn't have to be very powerful), a TV remote, IR receiver
(TS0P1738) and a small piece of cardboard.
Decoding IR Signals:
First you need to connect the parts as per the given circuit diagram:
SCHEMATICS
CODE
#include <IRremote.h>
#include <Servo.h>
int IRpin = 11; // pin for the IR sensor
IRrecv irrecv(IRpin);
decode_results results;
Servo myservo;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
if (irrecv.decode(&results))
{
irrecv.resume(); // Receive the next value
}
if (results.value == 33441975) // change according to your IR remote button number
{
myservo.write(0);
delay(15);
}
if (results.value == 33446055) // change according to your IR remote button number
{
myservo.write(30);
delay(15);
}
}
116) Arduino Simon Says projet
Arduino Nano R3
Other Arduino boards work just × 1
fine.
LED (generic)
Four 5mm LEDs. Preferably Red,
× 1
Blue, Yellow and Green.
Resistor 1k ohm
Pulldown resistors for the buttons.
× 1
Breadboard (generic)
× 1
Buzzer
OPTIONAL: If you want sound.
× 1
I will provide you the code and the wiring instructions, if you have all
the components ready it shouldn't take more than 30 minutes. This is
also the first time I'm writing a guide on Hackster, if you think I'm
wrong on some aspects or if you think it can be improved please leave
feedback in the comment section.
Wiring Instructions
I use 1k pulldown resistors for the buttons, 100 ohm resistor for the
Piezzo Buzzer and 330 ohm resistors for the LEDs. Start by putting on
the buttons and the LEDs first, then add the resistors and finally add
the jumper wires.
The following pins on the Arduino are used:
/* Pin settings */
static const int Game::MICROPHONE_PIN = 12;
static const int Game::BLUE_PIN = 11;
static const int Game::RED_PIN = 10;
static const int Game::GREEN_PIN = 9;
static const int Game::YELLOW_PIN = 8;
static const int Game::BLUE_BUTTON_PIN = 7;
static const int Game::RED_BUTTON_PIN = 6;
static const int Game::GREEN_BUTTON_PIN = 5;
static const int Game::YELLOW_BUTTON_PIN = 4;
You can then customize the tone frequencies or the level seed. In the
setup function:
randomSeed(0);
If you replace 0 with 1 then all the levels will be randomized, if you
change it back to 0 then the game will play like before the change. In
the video I also added a reset button which connects the Arduino's RST
pin to GND.
Code
The code is written in C++ and it uses classes, if you see this for the
first time, don't be afraid, they're like containers for functions and
variables. If you want to learn more search for a C++ tutorial on
classes.
SCHEMATICS
CODE
/*
* To add a reset button connect: reset -> button <- pulldown resistor ground.
* The buttons have 1k pulldown resitors.
* The leds have a 220 ohm resistor.
*
* Will use the following numbers for colors, pins and notes
* 0 - Yellow
* 1 - Green
* 2 - Red
* 3 - Blue
*
*/
/*
* The game class, handles everything.
*/
class Game {
private:
int debounce(int last, int buttonPin);
void playNote(int note, int noteSpeed) const;
void flashLed(int led, int flashSpeed) const;
public:
static const int RED_PIN;
static const int BLUE_PIN;
static const int GREEN_PIN;
static const int YELLOW_PIN;
static const int MICROPHONE_PIN;
static const int RED_BUTTON_PIN;
static const int BLUE_BUTTON_PIN;
static const int GREEN_BUTTON_PIN;
static const int YELLOW_BUTTON_PIN;
static const int RED_TONE;
static const int BLUE_TONE;
static const int GREEN_TONE;
static const int YELLOW_TONE;
static const int GAMEOVER_TONE;
int gameLevel[200];
int gameSpeed;
int lastButtonValue;
int currentLevel;
int gameIsOver;
double gameDifficulty;
enum color { YELLOW, GREEN, RED, BLUE };
public:
Game();
Game(int);
void playLevel();
int userInput();
int gameOver();
int getNote(int note) const;
int pinToColorCode(int);
int colorCodeToPin(int);
int readButton(int buttonPin);
};
/* Pin settings */
static const int Game::MICROPHONE_PIN = 12;
static const int Game::BLUE_PIN = 11;
static const int Game::RED_PIN = 10;
static const int Game::GREEN_PIN = 9;
static const int Game::YELLOW_PIN = 8;
static const int Game::BLUE_BUTTON_PIN = 7;
static const int Game::RED_BUTTON_PIN = 6;
static const int Game::GREEN_BUTTON_PIN = 5;
static const int Game::YELLOW_BUTTON_PIN = 4;
/* Tone frequencies */
static const int Game::RED_TONE = 200;
static const int Game::BLUE_TONE = 400;
static const int Game::YELLOW_TONE = 600;
static const int Game::GREEN_TONE = 800;
static const int Game::GAMEOVER_TONE = 1000;
/*
* Makes sure the button is pressed only once.
*/
int Game::debounce(int last, int buttonPin) {
int current = digitalRead(buttonPin);
if (last != current)
{
delay(5);
current = digitalRead(buttonPin);
}
return current;
}
/*
* Plays a note.
* Receives the button number and plays the corresponding note.
*/
void Game::playNote(int note, int noteSpeed) const {
Serial.print("playNote: Playing note: ");
Serial.print(note);
Serial.print(" with speed: ");
Serial.println(noteSpeed);
note = Game::getNote(note);
/*
* Returns the corresponding color code based on pin.
*/
int Game::colorCodeToPin(int value) {
int ret_val = -1;
switch(value) {
case RED:
ret_val = Game::RED_PIN;
break;
case GREEN:
ret_val = Game::GREEN_PIN;
break;
case BLUE:
ret_val = Game::BLUE_PIN;
break;
case YELLOW:
ret_val = Game::YELLOW_PIN;
break;
default:
Serial.println("colorCodeToPin: Invalid value!");
delay(1000);
exit(0);
}
return ret_val;
}
/*
* Converts the button pin to a color code.
*/
int Game::pinToColorCode(int value) {
int ret_val = -1;
switch(value) {
case Game::RED_BUTTON_PIN:
ret_val = RED;
break;
case Game::GREEN_BUTTON_PIN:
ret_val = GREEN;
break;
case Game::BLUE_BUTTON_PIN:
ret_val = BLUE;
break;
case Game::YELLOW_BUTTON_PIN:
ret_val = YELLOW;
break;
default:
Serial.println("pinToColorCode: Invalid value!");
delay(1000);
exit(0);
}
return ret_val;
}
/*
* The the corresponding note based on the color code it receives.
*/
int Game::getNote(int note) const {
int return_value = -1;
switch(note) {
case YELLOW:
return_value = Game::YELLOW_TONE;
break;
case GREEN:
return_value = Game::GREEN_TONE;
break;
case RED:
return_value = Game::RED_TONE;
break;
case BLUE:
return_value = Game::BLUE_TONE;
break;
case 4:
return_value = Game::GAMEOVER_TONE;
break;
default:
Serial.println("playNote: Error! Invalid note!");
delay(1000);
exit(0);
}
return return_value;
}
/*
* Flashes a led. Receives the led code and sets it to the corresponding pin.
*/
void Game::flashLed(int led, int flashSpeed) const {
Serial.print("flashLed: Flashing LED: ");
Serial.print(led);
Serial.print(" with speed: ");
Serial.println(flashSpeed);
led = Game::colorCodeToPin(led);
digitalWrite(led, HIGH);
delay(flashSpeed);
digitalWrite(led, LOW);
}
/*
* Plays the next level.
*/
void Game::playLevel() {
Serial.print("playLevel: Playing on level: ");
Serial.println(Game::currentLevel);
Game::gameLevel[Game::currentLevel] = random(0, 4); // Create a random move every
time. 0 to 4 exclusive.
++Game::currentLevel;
int nextDificulty = Game::gameDifficulty * Game::currentLevel;
if (Game::gameSpeed - nextDificulty >= 10) {
Game::gameSpeed -= nextDificulty; // decrease the speed;
}
/*
* Reads the button value and returns the following codes:
* 0 - Yellow 1 - Green 2 - Red 3 - Blue
*/
int Game::readButton(int buttonPin) {
int currentButtonValue = Game::debounce(Game::lastButtonValue, buttonPin);
int return_value = -1;
if (lastButtonValue == LOW && currentButtonValue > LOW) {
return_value = Game::pinToColorCode(buttonPin);
}
Game::lastButtonValue = currentButtonValue;
if (return_value >= 0) {
Serial.print("readButton: Received signal from button number: ");
Serial.println(return_value);
}
return return_value;
}
int Game::gameOver() {
Serial.println("game_is_over: Checking if game is over!");
if (Game::gameIsOver) {
Serial.println("game_is_over: Game is over!");
}
return Game::gameIsOver;
}
/*
* Gets the user button presses and checks them to see if they're good.
*/
int Game::userInput() {
for (int i = 0; i < Game::currentLevel; ++i) {
Serial.println("userInput: User is pressing.");
int buttonPressed = -1;
while(true) {
buttonPressed = readButton(Game::RED_BUTTON_PIN);
if (buttonPressed != -1) { break; }
buttonPressed = readButton(Game::GREEN_BUTTON_PIN);
if (buttonPressed != -1) { break; }
buttonPressed = readButton(Game::YELLOW_BUTTON_PIN);
if (buttonPressed != -1) { break; }
buttonPressed = readButton(Game::BLUE_BUTTON_PIN);
if (buttonPressed != -1) { break; }
}
if (buttonPressed != gameLevel[i]) {
Game::playNote(4, 100); // game over note, and game over note speed.
Game::flashLed(buttonPressed, 1000);
return 0;
}
Game::playNote(buttonPressed, Game::gameSpeed);
Game::flashLed(buttonPressed, Game::gameSpeed);
}
delay(500);
return 1;
}
void loop() {
if (g.gameOver()) {
delay(1000); // Wait for serial to finish printing.
/*
On Arduino exit(0) disables the interrupts
and goes in an infinite loop.
On your PC exit(0) closes the program and
tries to clean up resources.
*/
exit(0);
}
g.playLevel();
if (g.userInput() == 0) {
g.gameIsOver = 1;
}
}
117) Arduino Adjusting Clock on 128X64 Monochrome Display projet
COMPONENTS AND SUPPLIES
Maxim Integrated DS3231MPMB1
Peripheral Module
× 1
Breadboard (generic)
× 1
× 1
× 1
Arduino Nano R3
× 1
APPS AND ONLINE SERVICES
Arduino IDE
And if long push (more 3-4 seconds), clock enter in adjust mode, first
for year.
After you push again button, you can adjust mounth (rotate left for
decrease value and rotate right for encrease the value).
Then minutes.
SCHEMATICS
CODE
#include <Wire.h>
#include "RTClib.h"
#include <Encoder.h> // from http://www.pjrc.com/teensy/td_libs_Encoder.html
Encoder knob(3, 2); //encoder connected to pins 2 and 3 (and ground)
#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to
program the Zero!
#define Serial SerialUSB
#endif
RTC_DS1307 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
//char daysOfTheWeek[7][12] = {"Duminica", "Luni", "Marti", "Miercuri", "Joi", "Vineri",
"Sambata"};
#include "U8glib.h"
// setup u8g object, please remove comment from one of the following constructor calls
// IMPORTANT NOTE: The complete list of supported devices is here:
http://code.google.com/p/u8glib/wiki/device
// U8GLIB_ST7920_128X64_1X u8g(13, 11, 10); // SPI Com: SCK = en = 13, MOSI = rw
= 11, CS = di = 10
// se orginal code for your LCD!!!!!!
//U8GLIB_KS0108_128 u8g(8, 9, 10, 11, 4, 5, 6, 7, 13, 2, 3, A5, 12); // 8Bit Com:
D0..D7: 8,9,10,11,4,5,6,7 en=18, cs1=14, cs2=15,di=17,rw=16
U8GLIB_ST7920_128X64_1X u8g(7, 6, 5 ,8); //Enable, RW, RS, RESET
int X = 0;
int Y = 0;
int I = 0;
int X2 = 0;
int Y2 = 0;
int X3 = 0;
int Y3 = 0;
int Timer = 0;
int Minutt = 0;
int Sekund = 0;
float Vinkel = 0;
int an = 0;
int luna = 0;
int zi = 0;
int zis = 0;
//the variables provide the holding values for the set clock routine
int setyeartemp;
int setmonthtemp;
int setdaytemp;
int setoretemp;
int setzitemp;
int setminstemp;
int setsecs = 0;
int maxday; // maximum number of days in the given month
int TimeMins; // number of seconds since midnight
int TimerMode = 2; //mode 0=Off 1=On 2=Auto
int TimeOut = 10;
int TimeOutCounter;
#include <stdlib.h>
char tmp_string[8];
void draw(void) {
// graphic commands to redraw the complete screen should be placed here
// u8g.setFont(u8g_font_6x10);
//u8g.setFont(u8g_font_osb21);
TegnKlokkeBg();
DateTime now = rtc.now();
TegnViser(Timer-1, 12.0, 15); // Omdreinig, Omdreiningstall / omdreining, radius
TegnViser(Minutt-5, 60.0, 24); // Omdreinig, Omdreiningstall / omdreining, radius
// TegnViser(Sekund, 60-deics, 27); // Omdreinig, Omdreiningstall / omdreining, radius
TegnViser(Sekund-6, 60.0, 27);
// TegnViser(Sekund, 60.0, 27);
u8g.setFont(u8g_font_6x10);
u8g.setPrintPos(2*deics + deics2, 63);
if (zi < 10) u8g.print("0");
u8g.print(zi);
u8g.print("/");
if (luna < 10) u8g.print("0");
u8g.print(luna);
u8g.print("/");
//u8g.print(an-2000);
u8g.print(an);
// u8g.setFont(u8g_font_unifont);
// u8g.setFontPosTop();
u8g.drawStr(55-deics, 4+deigrec, "12");
u8g.drawStr(83-deics, 25+deigrec, "3");
u8g.drawStr(60-deics, 45+deigrec, "6");
u8g.drawStr(39-deics, 25+deigrec, "9");
void setup(void) {
#ifndef ESP8266
while (!Serial); // for Leonardo/Micro/Zero
#endif
Serial.begin(9600);
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
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(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
void loop(void) {
//u8g.setFont(u8g_font_unifont);
u8g.setFont(u8g_font_6x10);
DateTime now = rtc.now();
Timer = now.hour(), DEC;
Minutt = now.minute(), DEC;
Sekund = now.second(), DEC;
Serial.print(Timer);
Serial.print(':');
Serial.print(Minutt);
Serial.print(':');
Serial.print(Sekund);
Serial.print(" - ");
an = now.year(), DEC;
Serial.print(an);
Serial.print('/');
luna = now.month(), DEC;
Serial.print(luna);
Serial.print('/');
zi = now.day(), DEC;
Serial.print(zi);
Serial.print(" (");
zis = now.dayOfTheWeek();
Serial.print(daysOfTheWeek[zis]);
Serial.println(") ");
// picture loop
u8g.firstPage();
do {
draw();
} while( u8g.nextPage() );
// rebuild the picture after some delay
delay(100);
pushlength = pushlengthset;
pushlength = getpushlength();
delay (10);
void draw1(void) {
// graphic commands to redraw the complete screen should be placed here
//u8g.setFont(u8g_font_unifont);
//u8g.setFont(u8g_font_osb21);
u8g.drawStr( 10, 32, "Thx to niq_ro!");
}
//sets the clock
void setclock (){
// u8g.setFont(u8g_font_unifont);
setyear ();
setmonth ();
setday ();
// setzi();
setore ();
setmins ();
rtc.adjust(DateTime(setyeartemp,setmonthtemp,setdaytemp,setoretemp,setminstemp,setsecs));
delay (1000);
}
int setmonth () {
pushlength = pushlengthset;
pushlength = getpushlength ();
if (pushlength != pushlengthset) {
return setmonthtemp;
}
// lcd.setCursor (0,1);
knob.write(0);
delay (50);
knobval=knob.read();
if (knobval < -1) {
knobval = -1;
}
if (knobval > 1) {
knobval = 1;
}
setmonthtemp=setmonthtemp + knobval;
if (setmonthtemp < 1) {// month must be between 1 and 12
setmonthtemp = 1;
}
if (setmonthtemp > 12) {
setmonthtemp=12;
}
itoa(setmonthtemp, tmp_string, 10);
u8g.firstPage();
do {
u8g.drawStr( 0, 20, "Set Month");
u8g.drawStr(25, 40, tmp_string);
} while( u8g.nextPage() );
setmonth();
}
int setday () {
if (setmonthtemp == 4 || setmonthtemp == 5 || setmonthtemp == 9 || setmonthtemp == 11) {
//30 days hath September, April June and November
maxday = 30;
}
else {
maxday = 31; //... all the others have 31
}
if (setmonthtemp ==2 && setyeartemp % 4 ==0) { //... Except February alone, and that has
28 days clear, and 29 in a leap year.
maxday = 29;
}
if (setmonthtemp ==2 && setyeartemp % 4 !=0) {
maxday = 28;
}
pushlength = pushlengthset;
pushlength = getpushlength ();
if (pushlength != pushlengthset) {
return setdaytemp;
}
knob.write(0);
delay (50);
knobval=knob.read();
if (knobval < -1) {
knobval = -1;
}
if (knobval > 1) {
knobval = 1;
}
setdaytemp = setdaytemp+ knobval;
if (setdaytemp < 1) {
setdaytemp = 1;
}
if (setdaytemp > maxday) {
setdaytemp = maxday;
}
itoa(setdaytemp, tmp_string, 10);
u8g.firstPage();
do {
u8g.drawStr( 0, 20, "Set Day");
u8g.drawStr(25, 40, tmp_string);
} while( u8g.nextPage() );
setday();
}
int setzi () {
pushlength = pushlengthset;
pushlength = getpushlength ();
if (pushlength != pushlengthset) {
return setzitemp;
}
knob.write(0);
delay (50);
knobval=knob.read();
if (knobval < -1) {
knobval = -1;
}
if (knobval > 1) {
knobval = 1;
}
setzitemp=setzitemp + knobval;
if (setzitemp < 0) {// month must be between 0 and 6
setzitemp = 0;
}
if (setzitemp > 6) {
setzitemp=6;
}
itoa(setzitemp, tmp_string, 10);
u8g.firstPage();
do {
u8g.drawStr( 0, 20, "Set Day of Week");
u8g.drawStr(25, 40, tmp_string);
u8g.drawStr(0,60, daysOfTheWeek[setzitemp]);
} while( u8g.nextPage() );
setzi();
}
int setore () {
pushlength = pushlengthset;
pushlength = getpushlength ();
if (pushlength != pushlengthset) {
return setoretemp;
}
knob.write(0);
delay (50);
knobval=knob.read();
if (knobval < -1) {
knobval = -1;
delay (50);
}
if (knobval > 1) {
knobval = 1;
delay (50);
}
setoretemp=setoretemp + knobval;
if (setoretemp < 0) {
setoretemp = 0;
}
if (setoretemp > 23) {
setoretemp=23;
}
itoa(setoretemp, tmp_string, 10);
u8g.firstPage();
do {
u8g.drawStr( 0, 20, "Set Hour");
u8g.drawStr(25, 40, tmp_string);
} while( u8g.nextPage() );
setore();
}
int setmins () {
pushlength = pushlengthset;
pushlength = getpushlength ();
if (pushlength != pushlengthset) {
return setminstemp;
}
knob.write(0);
delay (50);
knobval=knob.read();
if (knobval < -1) {
knobval = -1;
delay (50);
}
if (knobval > 1) {
knobval = 1;
delay (50);
}
setminstemp=setminstemp + knobval;
if (setminstemp < 0) {
setminstemp = 0;
}
if (setminstemp > 59) {
setminstemp=59;
}
itoa(setminstemp, tmp_string, 10);
u8g.firstPage();
do {
u8g.drawStr( 0, 20, "Set Minutes");
u8g.drawStr(25, 40, tmp_string);
} while( u8g.nextPage() );
setmins();
}
// see https://arduino.cz/tutorial-uzivani-hodin-realneho-casu-ds1307-a-ds3231-s-arduinem/
// http://tronixstuff.com/2014/12/01/tutorial-using-ds1307-and-ds3231-real-time-clock-
modules-with-arduino/
118) Arduino Alarm Clock projet
× 1
Buzzer
× 1
Thermistor
× 1
× 1
Potentiometer (10K)
× 1
NECESSARY TOOLS AND MACHINES
3D Printer (generic)
SCHEMATICS
CODE
/*
Project: Use DS3231 RTC to print Time, Date.. Use Thermistor for temp.
Ability to set Alarm.
*/
//-----------------------------------------------------------------------------
// Define variables.
Time t;
#define buz 11
int tempPin = 0;
int Hor;
int Min;
int Sec;
int tempC;
int tempF;
int tempCDS3231;
int tempFDS3231;
//-------------------------------------------------------------------------
// Used to fix Date, Time, Day of Week
//--------------------------------------------------------------------------
void setup()
{
Wire.begin();
rtc.begin();
Serial.begin(9600);
pinMode(buz, OUTPUT);
lcd.begin(16,2);
lcd.setCursor(0,0);
t = rtc.getTime();
Hor = t.hour;
Min = t.min;
Sec = t.sec;
//---------------------------------------------------------------------
void loop()
{
int tempReading = analogRead(tempPin);
// This is OK
double tempK = log(10000.0 * ((1024.0 / tempReading - 1)));
tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK
* tempK )) * tempK ); // Temp Kelvin
int tempC = tempK - 273.15; // Convert Kelvin to Celcius
int tempF = (tempC * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
//----------------------------------------------------------------------------------------
---
//Can change the ABOVE tempC and tempF "int" to "float" this can give
you temperatures with two decimal points.
//Can also use "lcd.print(tempF, 1);" BELOW to print with one decimal
place or "lcd.print(tempF, 0);" // print without decimal place
//----------------------------------------------------------------------------------------
---
lcd.setCursor(0,1);
lcd.print(tempF);
lcd.print((char)223); //This creates a Degree symbol
lcd.print("F ");
lcd.print(rtc.getDateStr());
//--------------------------------------------------------------------------
t = rtc.getTime();
Hor = t.hour;
Min = t.min;
Sec = t.sec;
//----------------------------------------------------------------------------------------
---
//Use the BELOW "if" statement to set your desired alarm time
if( Hor == 10 && (Min == 00 || Min == 00)) //Comparing the current
time with the Alarm time
//----------------------------------------------------------------------------------------
---
{
Buzzer();
Buzzer();
lcd.clear();
lcd.print("Alarm ON");
lcd.setCursor(0,1);
lcd.print("Wake Up!!");
Buzzer();
Buzzer();
}
delay(1000);
void Buzzer()
digitalWrite(buz,HIGH);
delay(500);
digitalWrite(buz, LOW);
delay(500);
× 1
× 1
Buzzer
× 1
× 2
× 1
AA Batteries
× 1
NECESSARY TOOLS AND MACHINES
Hot glue gun (generic)
Ardublockly
void setup() {
pinMode(buzzerPin,OUTPUT);
pinMode(redLed,OUTPUT);
myServo.attach(11;
}
void loop() {
moisture = analogRead(A0); //Read the moisture from sensor
moisture = map(moisture,0,1023,100,1); //Map the moisture values to 1-100.
if (moisture < 50) { //If moisture is low
myServo.write(165); //Turn motor to "No water" sign
digitalWrite(redLed,HIGH); //Turn on the led light
tone(buzzerPin, 2000, 500); //Play a buzzer tone for halph a second
delay(1000); //delay for a second
digitalWrite(redLed,LOW); //Turn off the led light
delay(1000); //Delay another second
} else { //If moisture is OK
digitalWrite(redLed,HIGH); //Just turn on the led light
myServo.write(20); //and turn motor to "plant ok" sign
}
}
120) Arduino Light Follower Projet
× 1
mini breadboard - mixed colours × 1
5 LDR
× 1
4mm cardboard
× 1
APPS AND ONLINE SERVICES
Arduino IDE
× 1
Breadboard (generic)
× 1
× 1
Resistor 221 ohm
× 3
× 1
Buzzer
× 1
Tactile Button
× 1
× 1
LED (generic)
× 3
APPS AND ONLINE SERVICES
Arduino IDE
I was in need of an Hour timer that could be started and stopped with a
press of a button. When I got to building and coding it I thought that I
could do more than a simple hour timer. I cobbled together a timer that has
a range from 1 minute to an hour and a half and still only uses 1 button to
control it.
I didn’t want to use an Arduino for the final product but still prototyped it
on the Arduino. I used an ATTINY85 for the final product.
Parts Required
Connect the 5v to the Positive rail and the ground to the ground rail
Grab the 3 LED's and connect the anodes to a positive rail and the
cathodes to 3 separate terminal strips
Place resistors between the led's and another 3 terminal strips
Connect the LED RESISTOR pair to pins 2, 3 and 4
Place the transistor onto the breadboard
Place the buzzer between the collector and the positive rail using a jumper
wire
Connect the resistor to the base of the transistor and another terminal strip
then to pin 5 of the arduino
Connect the emitter of the transistor to the ground rail
I'm using a transistor on the buzzer because I have no idea what my
buzzer's power consumption is and I don't want to draw too much power
from one pin of the arduino.
Place the button between 2 terminal strips,
One end of the button goes to pin 6 of the Arduino and
The other end goes to the ground rail.
Usage
When I first power it up the led flashes, this indicates that the timer it is
counting down.
If I hold the button in for more than 75 milliseconds, at least one of the
LED's will be on. This means that I can choose the time I need.
If I give the button a short press he LED's change. The LED's are a 3 digit
binary number (1 through to 7 and they correspond to the times array).
I can select the time I want to countdown by giving the button a long
press. This will make the timer start counting down.
Once the countdown is complete the buzzer will ring, until you press the
button. It will then switch off.
If I tap the button when in "sleep mode" it starts counting down from the
start of last selected time.
If I want to turn it off at any time, I hold the button down for an extremely
long time and once the led's flash and I release the button, it will then turn
off.
Making it Easier to Read
Unless you can read binary the colors make using the timer 100 times
easier.
When you use a red, green and blue led covered by a diffuser, you
suddenly have 7 colours corresponding to the times in the times array.
Here I also changed the circuit to a common cathode and changed the code
accordingly.
SCHEMATICS
CODE
#define DEVICE ARDUINO // ARDUINO or ATTINY85
#define COMMON_PIN_ANODE 1 // 1 = Common Anode; 0 = Common Cathode
#define ATTINY85 1
#define ARDUINO 0
#define SWITCH_OFF_LENGTH 3
#if DEVICE
//ATTINY85 INCLUDES & DEFINES
#include <avr/sleep.h>
#include <avr/interrupt.h>
#define LED1 0
#define LED2 1
#define LED3 2
#define BUTTON 3
#define BUZZER 4
#else
#define LED1 11
#define LED2 12
#define LED3 13
#define BUTTON 2
#define BUZZER 6
#endif
// PROGRAM STATES
#define CHOOSETIMER 1
#define COUNTDOWN 2
#define BUZZ 3
// BUTTON STATES
#define NO_PRESS 0
#define SHORT_PRESS 1
#define LONG_PRESS 2
#define OFF_PRESS 3
// VARIABLES WOOP!
unsigned long timer = 0;
byte MODE = 2;
byte cdMenu = 1;
int countDown = 45;
int times[] = {0, 60, 300, 900, 1800, 2700, 3600, 5400};
#if DEVICE
void sleep () { // with compliments of
https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-
change-code-example/
delay(500); // BUTTON DEBOUNCE (LONG)
beep(); delay(200);
beep(); delay(200);
beep();
countDown = times[cdMenu]; // RESET TIMER READY FOR WHEN YOU COME
BACK FROM SLEEPING
MODE = COUNTDOWN; // GETTING READY FOR WHEN YOU COME
BACK FROM SLEEPING
sleep_enable(); // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
sei(); // Enable interrupts
sleep_cpu(); // sleep
beep(); delay(200);
beep();
}
ISR(PCINT0_vect) {}
#else
void sleep () {
beep(); delay(200);
beep(); delay(200);
beep();
// EMULATES THE SLEEPING WHEN USING THE ARDUIN (IT SAVES NO POWER)
while (digitalRead(BUTTON));
beep(); delay(200);
beep();
}
#endif
// SELF EXPLANITORY
void beep() {
digitalWrite(BUZZER, HIGH);
delay(30);
digitalWrite(BUZZER, LOW);
}
// SETS ALL LED's PINS TO LOW OR HIGH DEPENDING ON THE LED's COMMON
PIN CONNECTION
void clearDisplay() {
byte leds = 0;
#if COMMON_PIN_ANODE
digitalWrite(LED1, !bitRead(leds, 0));
digitalWrite(LED2, !bitRead(leds, 1));
digitalWrite(LED3, !bitRead(leds, 2));
#else
digitalWrite(LED1, bitRead(leds, 0));
digitalWrite(LED2, bitRead(leds, 1));
digitalWrite(LED3, bitRead(leds, 2));
#endif
}
// SHOW THE TIME SELECTED
void displayTime() {
int leds = 0;
// GET THE INDEX IN THE ARRAY FROM THE countDown VALUE
for (int t = 0; t < 8; t++) {
if (countDown >= times[t]) {
leds = t;
}
}
#if COMMON_PIN_ANODE
digitalWrite(LED1, !bitRead(leds, 0));
digitalWrite(LED2, !bitRead(leds, 1));
digitalWrite(LED3, !bitRead(leds, 2));
#else
digitalWrite(LED1, bitRead(leds, 0));
digitalWrite(LED2, bitRead(leds, 1));
digitalWrite(LED3, bitRead(leds, 2));
#endif
}
// START TIMING
unsigned long timerButton = millis() / 10;
beep();
// BLINK RANDOMLY WHEN THE TIMER VALUE IS LONGER THAN THE SET
VALUE FOR THE SWITCH OFF
if ((millis() / 10 - timerButton) > (SWITCH_OFF_LENGTH * 100)) {
digitalWrite(LED1, bitRead(millis() / 100, 0));
digitalWrite(LED2, bitRead(millis() / 100, 1));
digitalWrite(LED3, bitRead(millis() / 100, 2));
}
}
clearDisplay();
return butLength;
}
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(BUZZER, OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
timer = (millis() / 100);
clearDisplay();
}
void loop() {
int button = buttonCheck();
switch (button) {
case LONG_PRESS:
// CYCLE THROUGH THE MODES
MODE++;
if (MODE >= BUZZ) {
MODE = CHOOSETIMER;
}
break;
case OFF_PRESS:
sleep();
button = NO_PRESS; // FORCE THE BUTTON TO NO_PRESS (I CAN'T
REMEMBER WHY THOUGH)
break;
}
switch (MODE) {
case CHOOSETIMER:
countDown = times[cdMenu]; // SET THE COUNT DOWN TIME FROM THE
ARRAY OF TIMES
if (button == SHORT_PRESS) { // CYCLE TIMES
cdMenu++;
if (cdMenu == 8) {
cdMenu = 1; // skip 0 value in the array
}
countDown = times[cdMenu];
}
displayTime();
break;
case COUNTDOWN:
//EVERY SECCOND FLASH YOUR REMAINING TIME (ROUNDING UP) AND
COUNT DOWN
if (((millis() / 100) - timer) >= 10) {
timer = (millis() / 100);
displayCountDownTime();
delay(50);
clearDisplay();
countDown--;
}
break;
case BUZZ:
// BUZZ!
digitalWrite(BUZZER, HIGH);
// FLASH!
digitalWrite(LED1, bitRead(millis() / 100, 0));
digitalWrite(LED2, bitRead(millis() / 100, 1));
digitalWrite(LED3, bitRead(millis() / 100, 2));
× 1
× 13
× 5
SCHEMATICS
CODE
#include <LedControl.h>
#include <Wire.h>
byte buff[TO_READ] ; //6 bytes buffer for saving data read from the
device
char str[512]; //string buffer to transform data before sending it
int MATRIX_WIDTH = 8;
LedControl lc = LedControl(12, 11, 10, 1); // DIN, CLK, CS, NRDEV
unsigned long delaytime = 50;
int x_key = A1;
int y_key = A0;
int x_pos;
int y_pos;
void setup()
{
// set up a grain object
g = new Grain();
ClearDisplay();
void loop()
{
// The first axis-acceleration-data register
int regAddress = 0x32;
int x, y, z;
// Convert the values into values that can be represented on the matrix
x = map(x, -300, 300, 0, 8);
y = map(y, -300, 300, 0, 8);
z = map(z, -300, 300, 0, 8);
ClearDisplay();
// assign the grain to this location
g->x = x;
g->y = y;
lc.setLed(0, g->x, g->y, true);
int i = 0;
while (Wire.available()) //device may send less than requested
(abnormal)
{
buff[i] = Wire.read(); // receive a byte
i++;
}
Wire.endTransmission(); //end transmission
}
123) Arduino Cheap DIY Laser Alarm Projet
COMPONENTS AND SUPPLIES
× 1
× 1
SCHEMATICS
CODE
int MulticolorLed = 4; // i used the 7 color led, just for the show. You can add any led or led
module.
//you can also remove the led module to save power, if the source comes from a battery.
int Relay = 5;
int LaserEmitter = 6;
int LaserDetector = 7;
int Buzzer = 8;
// here i set up the tones, you can change them @ void loop.
int tones[] = {261, 277, 293, 311, 329, 349, 369, 392, 415, 440, 466, 493, 523 ,554};
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// You can add more tones but i added 14. Just fill in what tone you would like to use, @
void loop you see " tone(Buzzer, tones[12]); " below, digitalWrite(Buzzer, HIGH);
// here you can change the tones by filling in a number between 1 and 14
void setup()
Serial.begin (9600);
pinMode(LaserEmitter, OUTPUT);
pinMode(LaserDetector, INPUT);
pinMode(MulticolorLed, OUTPUT);
pinMode(Buzzer, OUTPUT);
digitalWrite(Buzzer, LOW);
pinMode(Relay, OUTPUT);
digitalWrite(Relay, LOW);
//+++++++++++++++++++++++++++++++++++++++++++
//Part of buzzer tones
for (int i = 0; i < Buzzer; i++)
{
}
void loop()
{
digitalWrite(LaserEmitter, HIGH);
if (val == 0) // Here we set value to 0 with a if statement, because the laser sensor reads a
value of 1 or 0. Its reads value 1 when the laser is aimed at the receiver.
// so value 0 is what we set for this alarm right now. To change the alarm to a alarm that
works the other way around you simply change this value to 1.
// How would it work the other way around? well like a alarm you see in the movies that
protects a diamond.. when the diamond or any item is removed the alarm will go off.
digitalWrite(Buzzer, HIGH); // here the Buzzer is set high in order to make a sound.
tone(Buzzer, tones[6]); //here we set the tone by choosing from number 1 to 14
delay (50);
digitalWrite(Buzzer, LOW); // here we set the buzzer low and next we set noTone for the
buzzer to make a break.
noTone(Buzzer);
delay (50); //this is the delay between each buzzer beep. You can play with the sounds by
choosing from number 1 to 14
digitalWrite(Buzzer, HIGH);
tone(Buzzer, tones[9]);
delay (100);
digitalWrite(Buzzer, LOW);
noTone(Buzzer);
delay (100);
digitalWrite(Buzzer, HIGH);
tone(Buzzer, tones[14]);
delay (50);
digitalWrite(Buzzer, LOW);
noTone(Buzzer);
digitalWrite(MulticolorLed, HIGH); //Here we set the led to high, it will only flash when
the alarm is triggered
delay(250);
digitalWrite(Relay, HIGH); //here we set the relay to high, it will also only turn on when
the laser is not aimed at the laser receiver
delay(100);
}
else //here we use the else statement to turn everything off when the if statement is reading
the laser receivers value of 1
digitalWrite(Relay, LOW);// here everything turns off, so is set to low. This happens when
the laser aims at the Laser receiver.
digitalWrite(Buzzer, LOW);
noTone(Buzzer);
digitalWrite(MulticolorLed, LOW);
× 1
5 mm LED: Red
× 1
5 mm LED: Yellow
× 1
5 mm LED: Green
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Apple Xcode
SCHEMATICS
CODE
#include <math.h>
#include "Boards.h"
#include <SPI.h>
#include <Nordic_nRF8001.h>
#include <RBL_nRF8001.h>
#include "iShield.h"
iShield myiShield;
// momentary switch
const int buttonPin = 2;
int buttonState = 0;
// Position set when the momentary witch is pressed
int currentBackPos;
void setup()
{
// Init. and start BLE library.
ble_begin();
Serial.begin(9600);
ble_set_name("BLEShield");
//pinMode(buzzerPin, OUTPUT);
digitalWrite(LED1,LOW); // Red
digitalWrite(LED2,LOW); // Green
digitalWrite(LED3,LOW); // Yellow
pinMode(2, INPUT); // SwitchButton (to set "normal" position)
}
void loop()
{
// if msg is sent by bluetooth from the app, write it on the console (not
used in that project)
myiShield.readConsole();
String message = myiShield.incomingData();
Serial.println(message);
// To get those values, play with your accelerometer and put the min and
max you find on every x,y,z position
int xMinVal = 265; int yMinVal = 259;int zMinVal = 281;
int xMaxVal = 398; int yMaxVal = 393;int zMaxVal = 413;
xRead = xRead/ave;
yRead = yRead/ave;
zRead = zRead/ave;
// convert to angles
xAng = map(xRead, xMinVal, xMaxVal, -90, 90);
yAng = map(yRead, yMinVal, yMaxVal, -90, 90);
zAng = map(zRead, zMinVal, zMaxVal, -90, 90);
currentBackPos = x;
//if the button is pressed set the value of base position to the current back
position
// this sets a "normal" state that the code will then measure a difference
from.
if (buttonState == HIGH) {
myiShield.writeConsole("button pressed");
refPos = currentBackPos;
digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
}
else {
if(currentBackPos > refPos + 10){
myiShield.writeConsole("warning");
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, HIGH);
}
else{
digitalWrite(LED2, HIGH);
digitalWrite(LED1, LOW);
digitalWrite(LED3, LOW);
}
}
delay(2000);
}
125) Anti Theft Camera System using Arduino Projet
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
void loop() // the loop routine runs over and over again forever:
{
int sensorValue = analogRead(A0); // read the input on analog pin 0:
Serial.println(sensorValue); // print out the value you read:
delay(1); // delay in between reads for stability
× 1
Digilent WS2812 Addressable LED
Strip
This wasn't the actual product × 1
used, but uses the same
technology.
Digilent 5V 4000mA Switching
Power Supply
Again, this wasn't the actual × 1
product used, but serves the same
purpose.
APPS AND ONLINE SERVICES
Arduino IDE
#include <Adafruit_NeoPixel.h>
#include <Stdint.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define stripPin 6
#define stripPinB 9
#define ledTotal 150 // zero indexed, so one less than you need. I.e. 50 leds = 49 here
#define ledTotalB 144 // zero indexed...
#define rowSize 6 // zero indexed...
#define columnSize 41 // zero indexed...
#define charWidth 5 // ** one indexed **
// was 68 with lower case chars, 42 without -- 40 without l/r arrow -- 42 WITH PLUS AND
DOT
byte displayLetters[42][charWidth] = { // [A] = chars/digits contained in array, [B] =
charWidth (no need to add 1, as was 'one indexed' at #define)
{0x3e, 0x51, 0x49, 0x45, 0x3e}, // 0 // , 0x00
{0x00, 0x42, 0x7f, 0x40, 0x00}, // 1
{0x42, 0x61, 0x51, 0x49, 0x46}, // 2
{0x21, 0x41, 0x45, 0x4b, 0x31}, // 3
{0x18, 0x14, 0x12, 0x7f, 0x10}, // 4
{0x27, 0x45, 0x45, 0x45, 0x39}, // 5
{0x3c, 0x4a, 0x49, 0x49, 0x30}, // 6
{0x01, 0x71, 0x09, 0x05, 0x03}, // 7
{0x36, 0x49, 0x49, 0x49, 0x36}, // 8
{0x06, 0x49, 0x49, 0x29, 0x1e}, // 9
const int stockQty = 17; // this is the amount of different stock values to be contained, *!*
ONE indexed *!*
const int stockStepQty = 5; // *!* ONE indexed *!*
int stockStep = 0;
/*String stockNames[stockQty] = {
"MH", "EJ", "SG", "MC", "AS", "JWL", "RP", "HCJ", "JT", "KC", "HCN", "MK", "JWK",
"RB", "KS", "EC", "AW"
};*/
/*int stockValues[stockStepQty][stockQty] = { // dies 3 from end, color wise
{5, 12, 41, 52, 157, 74, 63, 96, 17, 86, 104, 49, 76, 46, 91, 61, 121},
{6, 13, 40, 52, 155, 73, 60, 98, 18, 85, 105, 48, 77, 47, 90, 59, 125},
{6, 12, 39, 53, 155, 75, 58, 99, 18, 84, 104, 46, 78, 46, 88, 60, 123},
{7, 11, 42, 55, 156, 74, 59, 98, 17, 85, 106, 47, 77, 45, 92, 58, 124},
{6, 13, 40, 54, 157, 75, 60, 97, 18, 85, 105, 48, 77, 46, 95, 60, 122}
};*/
Adafruit_NeoPixel strip = Adafruit_NeoPixel(ledTotal + 1, stripPin, NEO_RGB +
NEO_KHZ800);
Adafruit_NeoPixel stripB = Adafruit_NeoPixel(ledTotalB + 1, stripPinB, NEO_RGB +
NEO_KHZ800);
void setup() {
strip.begin();
strip.show();
stripB.begin();
stripB.show();
pinMode(13, OUTPUT);
}
String inputString = "MJC|-5 CDL|-1 HJC^+10 MAK^+2 GJK|-8 EBJ^+5 HJC^+10
JCW^+0.02 ADS|-3 SEG^+5 RFB^+7 KGO^+2 MJH|-0.043 KHS^+0.054 SIC^0.008
EJC^+0.001 AMW^+5 LDK|-7 JCT^+9 JKM^+4 RJP|-4 SKC^+9 JLW|-5 HKC^+5
LMP^+7 ANS^+5 ";
String colString =
"00011100001110000222200002220000111000022200002222000022222200001110000222000022200002
void loop() {
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString[i];
int currentCol, colorMode;// = int(colString[i]) - 48; // minus 48 because int("0") will return
the ascii value of char '0' (48)
int indexValue;
if ((currentChar >= '0') && (currentChar <= '9')) indexValue = currentChar - 48; // 0-9
else if ((currentChar >= 'A') && (currentChar <= 'Z')) indexValue = currentChar - 55; //
upper case
//else if ((currentChar >= 'a') && (currentChar <= 'z')) indexValue = currentChar - 61; //
lower case , check that these are in the right place / the offset is correct, as i may have put
the array chunk back in the wrong place!!
else if ((currentChar == ' ')) indexValue = 36; // space, was 62 when lower case chars
else if ((currentChar == '^')) indexValue = 37; // up arrow, was 63 when lower case chars
else if ((currentChar == '|')) indexValue = 38; // down arrow, was 64 when lower case chars
// else if ((currentChar == '<')) indexValue = 39; // left arrow, was 65 when lower case
chars
// else if ((currentChar == '>')) indexValue = 40; // right arrow, was 66 when lower case
chars
else if ((currentChar == '-')) indexValue = 39; // dash / maintain, was 67 when lower case
chars, 41 with l/r arrows
else if ((currentChar == '+')) indexValue = 40; // plus
else if ((currentChar == '.')) indexValue = 41; // full stop
delay(100);
}
nudgeColumns(0, 0); // - 1 might break things here? or make things go white due to the
lookup default being white
if (currentStatus == 0) currentStatus = 1;
else if (currentStatus == 1) currentStatus = 0;
setStatusIndicator(currentStatus);
displayUpdate(0);
delay(100); // this will be 200 as per the rest once confirmed that the double jump issue is
done!
}
z = columnSize - columnID;
if (columnID % 2) z++;
z = z* (rowSize + 1);
if (columnID % 2) z = z - rowID - 1;
else z = z + rowID;
strip.show();
stripB.show();
}
return outputColor;
}
Arduino Nano R3
× 1
LED (generic)
× 7
Resistor 100 ohm
× 7
× 1
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
int delayTime = 1;
int charBreak = 2.1;
int LED1 = 6;
int LED2 = 5;
int LED3 = 4;
int LED4 = 3;
int LED5 = 2;
void setup(){
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(LED5, OUTPUT);
}
void loop(){
displayString("hello world");
}
× 1
× 1
ky 008 Laser emitter
× 1
Buzzer
× 1
Push Button
× 1
4x4 Keypad matrix you can use 3x4 one for the Version 2
Version 1
This project is based on the module, LASER module, a Buzzer, and a push
button, the idea is very simple, the LASER is constantly projecting light to
the module sensor, when a person or something passes through the light
beam, the sensor will not detect the light anymore (When the light stops,
the LDR will increase resistance, which means less current will pass, and
we’ll get a voltage drop).
Example: At indoor light the sensor will give a value of around “750”
when using the “analogRead” function while using Arduino it’s around
“3.66V” (1023 for 5V), but when you cover the sensor it will show a value
around “10-15” that stands for “40mV”. So it’s better to cover or put the
sensor in a case where only the LASER beams can reach.
Once the LASER beams are cut, the alarm will go off and will not stop
until the push button is pressed even though the module detects the
LASER again.
Below you'll find wiring and code
Version 2
The v2 is pretty much like the v1 just instead of stopping the alarm with a
simple push button, now it requires a passcode entered by the keypad to
stop it, otherwise it won’t.
The passcode is stored in an array, I chosed 4 digits code, you can make it
longer or shorter, just modify the array size, and add or remove values.
short code[4]={'1','3','6','6'};
To turn the alarm off, you should press ‘*’ on the keypad, then enter the
numbers 1, 3, 6, 6, the code will fix the buzzer in a single frequency
(disturbing) sound until you enter 4 digits, if they are correct the alarm
will stop, otherwise it will go off again.
void Getpass(){
tone(13,2000);
for(short i=0 ; i<4 ; i++)
{
char keypressed = myKeypad.waitForKey();
if (keypressed==code[i])
a++;
}
}
Every time you enter a correct digit “a” value increases, if it’s == 4, the
code is considred correct, otherwise the number will never be equal to 4.
if(a==4){
noTone(13);
a=0;
detection=false;
}
SCHEMATICS
Wiring for V1
Wiring for V2
CODE
This code works with the version 1
/* This code is for a LASER Tripwire Alarm based on a light sensor, LASER module and a
push button
* The LASER is constantly sending beams to the sensor, when someone passes the light is
not detected
* and the alarm goes off, and will not stop until you press the button
*/
bool detection;
void setup() {
pinMode(Laser, OUTPUT);
digitalWrite(Laser, HIGH); //Turning on the laser
delay(2000);
}
void loop() {
if(Detect < 500) //The Max value is 760, if someone passes it goes below that (every
value lower than 700 can do the work)
detection = true; //The detection is triggered
if(detection==true)
{
tone(13,2000); //Alarm sequence will go on as long as the detection is true
delay(50); //This alarm has two sounds 2kHz nd 1Khz delayed by 50ms
tone(13,1000);
delay(50);
}
if(Button_state == HIGH) //If the button is pressed the buzzer is turned off and the
detection too
{
detection = false;
noTone(13);
}
/* This code is for a LASER Tripwire Alarm based on a light sensor, LASER module and
keypad
* The LASER is constantly sending beams to the sensor, when someone passes the light is
not detected
* and the alarm goes off, and will not stop until you press '*' and enter the correct code
*/
#include <Keypad.h>
#define Rec 0
#define Laser 2
#define Button 3
bool detection;
short a=0;
short code[4]={'1','3','6','6'}; //pass code stored in a array you can make it longer or shorter
//by changing '4' and add/remove values
void setup() {
pinMode(Laser, OUTPUT);
digitalWrite(Laser, HIGH);
delay(2000);
}
void loop() {
if(detection==true)
{ //Alarm sequence and constantly waiting for '*' to be pressed
tone(13,1000);
delay(50);
tone(13,200);
delay(50);
char keypressed = myKeypad.getKey();
if (keypressed == '*') //if '*' is pressed go to Getpass function
Getpass();
}
if(a==4){ //if a==4 means the code is correct, the alarm is off
noTone(13);
a=0; //setting the a to 0, otherwise the alarm will turn off
automatically
detection=false;
}
5 mm LED: Red
× 1
5 mm LED: Green
× 1
Photo resistor
× 1
× 3
× 1
Buzzer
× 1
Temperature Sensor
× 1
× 1
water level
× 1
hygrometrer
× 2
relay
× 2
lamp holder
× 1
× 1
plug
× 1
water pump
× 1
plexiglass
× 1
zippers
× 4
rubber feet
× 4
connecting wires
× 40
Accessory, Screw
× 36
NECESSARY TOOLS AND MACHINES
welding machine
Multitool, Screwdriver
saw
cutter
sander
int pir=2;
int buzzerPin=3;
int relay1=4;
int relay2=5;
int green=9;
int red=10;
int ldr1;
int ldr2;
int temp;
int waterlevel;
int humidity1;
int humidity2;
void setup(){
Serial.begin(9600);
servo.attach(11);
pinMode(green, OUTPUT);
pinMode(red, OUTPUT);
pinMode(pir, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(waterlevel, INPUT);
pinMode(humidity1, INPUT);
pinMode(humidity2, INPUT);
pinMode(temp, INPUT);
pinMode(ldr1, INPUT);
pinMode(ldr2, INPUT);
}
void loop()
{
temp=analogRead(A2);
temperature =((temp * 0.00488) - 0.5) / 0.01;
detection=digitalRead(pir);
waterlevel=analogRead(A3);
ldr1 = analogRead(A0);
ldr2 = analogRead(A1);
Serial.print("ldr1 is:");
Serial.print(ldr1);
Serial.print(" | ");
Serial.print("ldr2 is:");
Serial.print(ldr2);
Serial.print(" | ");
Serial.print("water level is:");
Serial.println(waterlevel);
Serial.print(" | ");
Serial.print("temperature is:");
Serial.println(temperature);
else{
if(((ldr1+ldr2)/2)>700 && temperature>15 ){
servo.write(90);
digitalWrite(relay1,LOW);
delay(1000);}
if(((ldr1+ldr2)/2)<700 || temperature>15 ){
servo.write(0);
digitalWrite(relay1,HIGH);
delay(1000);}
if(waterlevel<180){
digitalWrite(red,HIGH);
digitalWrite(green,LOW);
digitalWrite(relay2,LOW);
if(detection==HIGH){
for(int i=1; i<5; i++) {
tone(buzzerPin, 1000, 500);
delay(1000);}
delay(5000);}}
else{
digitalWrite(green,HIGH);
digitalWrite(red,LOW);
digitalWrite(relay2, LOW);
do{
digitalWrite(relay2, HIGH);
humidity1=analogRead(A4);
humidity2=analogRead(A5);}
while (((humidity1+humidity2)/2)> 500);
digitalWrite(relay2, LOW);
delay(1000);
}}}
130) Arduino Flashing LED Light and Temperature Data Logger
Projet
COMPONENTS AND SUPPLIES
Solid and/or stranded core wire
(assorted colors) × 1
microSD card
For your computer to read the
× 1
chip, you may need a microSD
card adapter.
LPV60-36 constant voltage
controller × 1
thermal adhesive
× 1
× 1
SCHEMATICS
CODE
#include <Wire.h>
void setup(){ //code within setup will only be carried out once
if (SD.begin()){ //initializes the SD card and library and begins use of the
SPI bus and CS pin
Serial.println("ready"); //if the SD card and library are initialized
successfully, the begin function will return True, and "ready" will be
printed to the Serial Monitor
}
else{
Serial.println("failed"); //if the SD card and library are not initialized
successfully, the begin function will return False, and "failed" will be
printed to the Serial Monitor
return; //the return function will stop the rest of the code from running if
the SD card and library fail to initialize
}
rtc.begin(); //initializes the microcontroller's internal real time clock and
RTC library
rtc.setTime(0,0,0); //sets the time (hour, minute, second)
rtc.setDate(30,6,2018); //sets the date [(day, month, year)]
}
void loop(){
int count = 0;
while (count <= max_count){ //continues the flash cycle for 10 minutes,
or repeats the cycle while the cycle count is less than the number of cycles
in 10 minutes
digitalWrite(gatePin, HIGH); //sends a HIGH signal to the gate of the
MOSFET, powering on the LEDs
delay(delay_HIGH); //keeps the LEDs on for time delay_HIGH
digitalWrite(gatePin, LOW); //sends a LOW signal to the gate of the
MOSFET, powering off the LEDs
delay(delay_LOW); //keeps the LEDs off for time delay_low
count ++; //increments the variable count by one
}
Serial.print(rtc.getDateStr()); //prints the date to the Serial Monitor,
[imported from the internal RTC]
Serial.print(",");
Serial.print(rtc.getTimeStr()); //prints the time to the Serial Monitor,
[imported from the internal RTC]
Serial.print(",");
Serial.println(float(rtc.getTemp())); //prints the temperature to the Serial
Monitor, imported from the DS3231 module
× 1
LCD 16x2
× 1
potenziometer 10K
× 1
× 1
jumpers
× 1
Breadboard (generic)
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
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);
}
132) Arduino 2 Way Intersection with Pedestrian Walk Cycle Projet
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
Tested on the Uno, but easily
× 1
converted for other Arduino
boards
LED (generic)
3 RED, 2 Yellow, 2 Green, and 1 × 8
White
Resistor 1k ohm
× 1
SCHEMATICS
CODE
int WalkRequest = 0; // Variable used to store the state of the Walk Push Button
const int WalkButton = 2;
const int RedPedLED = 6;
const int WhitePedLED = 7;
void setup() {
pinMode(RedPedLED, OUTPUT); // Sets all LED's as OUTPUT
pinMode(WhitePedLED, OUTPUT);
pinMode(Red1LED, OUTPUT);
pinMode(Yellow1LED, OUTPUT);
pinMode(Green1LED, OUTPUT);
pinMode(Red2LED, OUTPUT);
pinMode(Yellow2LED, OUTPUT);
pinMode(Green2LED, OUTPUT);
pinMode(WalkButton, INPUT); // Sets Push Button as INPUT
void loop() {
// put your main code here, to run repeatedly:
// Station 1 Timing
delay(2500); // 2.5 Seconds of Red
digitalWrite(Red1LED, LOW); // Sets Red1 OFF Green ON
digitalWrite(Green1LED, HIGH);
delay(15000); // 15 Seconds of Green
digitalWrite(Green1LED, LOW); // Sets Green1 OFF Yellow ON
digitalWrite(Yellow1LED, HIGH);
delay(3500); // 3.5 Seconds of Yellow
digitalWrite(Yellow1LED, LOW); // Sets Yellow1 OFF Red ON
digitalWrite(Red1LED, HIGH);
// Station 2 Timing
delay(2500); // 2.5 Seconds of Red
digitalWrite(Red2LED, LOW); digitalWrite(Green2LED, HIGH); // Sets Red2 OFF Green
ON
delay(15000); // 15 Seconds of Green
digitalWrite(Green2LED, LOW); digitalWrite(Yellow2LED, HIGH); // Sets Green2 OFF
Yellow ON
delay(3500); // 3.5 Seconds of Yellow
digitalWrite(Yellow2LED, LOW); digitalWrite(Red2LED, HIGH); // Sets Yellow2 OFF
Red ON
void WalkCycle() {
delay(3500); // 3.5 Second delay before "WALK" begins
digitalWrite (WhitePedLED, HIGH); digitalWrite (RedPedLED, LOW); // Turn on White
Pedestrian Light
delay (15000); // 15 Second delay to allow crossing street
digitalWrite (WhitePedLED, LOW); digitalWrite(WalkButton, LOW); // Turn off White
Pedestrian Light
delay(250);
for (int x = 0; x < 5; x++) { // Flash White Ped LED 5X
digitalWrite(WhitePedLED, HIGH);
delay(250);
digitalWrite(WhitePedLED, LOW);
delay(250);
}
digitalWrite(RedPedLED, HIGH);
WalkRequest = 0; // Reset Push Button
asm volatile (" jmp 0"); // Soft-reset of sketch. Makes sure Station 1 "MAIN" always gets
Green after a walk cycle
}
void pin_ISR() {
buttonState = digitalRead(WalkButton);
(WalkRequest = 1); // Walk button has been pressed
// digitalWrite(WhitePedLED, buttonState); // Test Light for Interrupt use only during
testing!
}
133) Arduino Tallking Clock Projet
Resistor 1k ohm
× 3
× 3
Capacitor 22 µF
× 2
× 1
× 1
× 1
× 3
SD Socket
× 1
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, A0, A1, A2, A3);
void setup() {
// put your setup code here, to run once:
pinMode(CS, OUTPUT);
pinMode(mosi, OUTPUT);
pinMode(clk, OUTPUT);
pinMode(ampON, OUTPUT);
pinMode(talk, INPUT_PULLUP);
pinMode(minutes, INPUT_PULLUP);
pinMode(hours, INPUT_PULLUP);
//spi init
SPCR = _BV(SPE) | _BV(MSTR) | _BV(SPR0) | _BV(SPR1); // Enable
spi, Master, set clock rate fck/64
SPSR = _BV(SPI2X); //set clock rate fck/64 = 250KHz
//PWM Timer0
OCR0A = 0;
TCCR0A = _BV(COM0A1) | _BV(WGM01) | _BV(WGM00); //output in
phase, fast PWM mode
TCCR0B = _BV(CS00); // 16MHz/256 = 62.5KHz
pinMode(audio, OUTPUT);
//1000 Hz - timer2
OCR2A =249;
OCR2B = 125;
TCCR2A = _BV(COM2B1) | _BV(COM2B0) | _BV(WGM21) |
_BV(WGM20); //output B in phase, fast PWM mode
TCCR2B = _BV(WGM22) | _BV(CS22); // set prescaler to 64 and start
the timer
pinMode(oc2b, OUTPUT);
//60 sec - timer1
// OCR1A = 0xEA5F;
TCCR1A = _BV(WGM10) | _BV(WGM11) | _BV(COM1A0); //
TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS11) | _BV(CS12);
// input T1, PWM mode
digitalWrite(CS, HIGH);
//digitalWrite(ampON, LOW);
InitSD();
if(sdhc){card = 1;}else{card=512;} //SD or SDHC
fat();
if(BytesPerSector!=512){error();}
void loop()
{
talkPB=digitalRead(talk);
if(talkPB==LOW)
{
//read hours
if(hour < 21) {fn=hour; play();}
else if(hour == 20) {fn=20; play();}
else if(hour > 20) {fn=20; play(); fn=hour-20; play();}
fn=24; play(); //read "hours"
//read minutes
if(minute < 21) {fn=minute; play();}
else if(minute == 20) {fn=20; play();}
else if(minute > 20 && minute < 30) {fn=20; play(); fn=minute-20;
play();}
else if(minute == 30) {fn=21; play();}
else if(minute > 30 && minute < 40) {fn=21; play(); fn=minute-30;
play();}
else if(minute == 40) {fn=22; play();}
else if(minute > 40 && minute < 50) {fn=22; play(); fn=minute-40;
play();}
else if(minute == 50) {fn=23; play();}
else if(minute > 50 && minute < 60) {fn=23; play(); fn=minute-50;
play();}
fn=25; play(); //read "minutes"
fn=26; play(); //read message
OCR0A=0; //audio off
minutesPB=digitalRead(minutes);
if(minutesPB==LOW)
{
minute++;
if(minute>59) {minute=0;}
display();
wait();
}
hoursPB=digitalRead(hours);
if(hoursPB==LOW)
{
hour++;
if(hour>23) {hour=0;}
display();
wait();
}
minute++;
if(minute>59) {minute=0; hour++;}
if(hour>23) hour=0;
display();
}
}
//find the file and play it
void play(void)
{
if(!sdhc){fn += 1;} //if not SDHC first file = 1
if(fn > 15)
{
fn -=16; file(fn*32+20,1); //32 bytes per file descriptor at offset of 20
}
else
{
file(fn*32+20,0); //32 bytes per file descriptor at offset of 20
}
loc=(1 + (DataSector) + (unsigned long)(FileCluster-2) *
SectorsPerCluster) * card ;
ReadSD();
}
//LCD update
void display(void)
{
lcd.setCursor(5, 0); // top left
if(hour<10)lcd.print(" ");
lcd.print(hour);
lcd.print(":");
if(minute<10)lcd.print("0");
lcd.print(minute);
}
//SD error display
void error(void)
{
lcd.setCursor(0, 1); // bottom left
lcd.print("SD ERROR");
lcd.setCursor(0, 0); // top left
}
void ReadSD(void)
{
unsigned int i,r;
unsigned char read_data;
digitalWrite(CS, LOW);
r = Command(18,loc,0xFF); //read multi-sector
if(r != 0) error(); //if command failed error();
while(FileSize--)
{
while(spi(0xFF) != 0xFE); // wait for first byte
for(i=0;i<512;i++){
// 3 rounds of timer 0 = total of time to get 22 khz
while (!(TIFR0 & _BV(OCF0A))){}
TIFR0 = _BV(OCF0A); //TMR0 interrupt reset
while (!(TIFR0 & _BV(OCF0A))){}
TIFR0 = _BV(OCF0A); //TMR0 interrupt reset
while (!(TIFR0 & _BV(OCF0A))){}
digitalWrite(CS, LOW);
r = Command(17,(RootDir+sect)*card,0xFF); //read boot-sector for info
from file entry
if(r != 0) error(); //if command failed
else if(i==offset+8){fs[0]=spi(0xFF);}
else if(i==offset+9){fs[1]=spi(0xFF);}
else if(i==offset+10){fs[2]=spi(0xFF);}
else if(i==offset+11){fs[3]=spi(0xFF);}
else{spi(0xFF);}
}
spi(0xFF); //discard of CRC
spi(0xFF);
digitalWrite(CS, HIGH);
spi(0xFF);
FileCluster = fc[0] | ( (unsigned long)fc[1] << 8 ) | ( (unsigned long)fc[2]
<< 16 ) | ( (unsigned long)fc[3] << 24 );
FileSize = fs[0] | ( (unsigned long)fs[1] << 8 ) | ( (unsigned long)fs[2] <<
16 ) | ( (unsigned long)fs[3] << 24 );
FileSize = FileSize/512-1; //file size in sectors
}
digitalWrite(CS, LOW);
r = Command(17,0,0xFF); //read MBR-sector
if(r != 0) error(); //if command failed
}
spi(0xFF); //discard of CRC
spi(0xFF);
digitalWrite(CS, HIGH);
spi(0xFF);
//convert 4 bytes to long int
BootSector = pfs[0] | ( (unsigned long)pfs[1] << 8 ) | ( (unsigned
long)pfs[2] << 16 ) | ( (unsigned long)pfs[3] << 24 );
digitalWrite(CS, LOW);
r = Command(17,BootSector*card,0xFF); //read boot-sector
if(r != 0) error(); //if command failed
}
spi(0xFF); //discard of CRC
spi(0xFF);
digitalWrite(CS, HIGH);
spi(0xFF);
}
//assemble a 32 bits command
char Command(unsigned char frame1, unsigned long adrs, unsigned char
frame2 )
{
unsigned char i, res;
spi(0xFF);
spi((frame1 | 0x40) & 0x7F); //first 2 bits are 01
spi((adrs & 0xFF000000) >> 24); //first of the 4 bytes address
spi((adrs & 0x00FF0000) >> 16);
spi((adrs & 0x0000FF00) >> 8);
spi(adrs & 0x000000FF);
spi(frame2 | 1); //CRC and last bit 1
void InitSD(void)
{
unsigned char i,r[4];
digitalWrite(CS, HIGH);
for(i=0; i < 10; i++)spi(0xFF); // min 74 clocks
digitalWrite(CS, LOW); // Enabled for spi mode
× 1
Serial.println(results.value);
delay(000);
}
Now upload above code in Arduino and run this code. If everything is
alright your lights will glow and off with your remote buttons. As I am
controlling only one Bulb only but you can control more than one bulb
using different pins and relays and please beware about the AC
Connections. We are going to Launch more interesting clone of this
project soon.
SCHEMATICS
CODE
Arduino check Remote CodeArduino
Check remote codes using this code
/*Created By: Anshul Pareek
*usage : read IR SIGNALS AND PRINT ON SERIAL
*/
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>
int RECV_PIN = 9;
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);
delay(000);
}
135) Arduino Binary Counting Projet
× 1
Solderless Breadboard Full Size
× 1
LED (generic)
× 6
10 ohm resistor
× 2
12 jumper wires
6 LED
1 button switch(tactile)
initiate following steps from photos to build it(for more reference see
circuit diagram).
SCHEMATICS
CODE
int l[]={0,0,0,0,0,0},T=6,a,p;
const int b1=12,b2=13;
void setup() {
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(b1,INPUT);
pinMode(b2,INPUT);
}
void loop() {
p=0;
p=digitalRead(b1) ;
while(digitalRead(b1)!=0)
{
}
delay(100);
a=T-1;
while(a>=0&&p==1)
{
if(l[a]==1)
{
l[a]=0;
a--;
}
else
{
l[a]=1;
p=0;
}
}
p=digitalRead(b2) ;
while(digitalRead(b2)!=0)
{
}
delay(100);
a=T-1;
while(a>=0&&p==1)
{
if(l[a]==0)
{
l[a]=1;
a--;
}
else
{
l[a]=0;
p=0;
}
}
a=T-1;
for(int c=0;c<T;c++)
{
if(l[c]==1)
digitalWrite(T-c+1,HIGH);
else
digitalWrite(T-c+1,LOW);
a--;
}
}
× 1
× 1
× 2
× 20
× 1
× 2
SCHEMATICS
CODE
//function: stopwatch with start/stop(button 1) and reset(button 2)
//start/pause button 1
//add lap function success!!
//improve lap function scuuess!!
#include<LiquidCrystal.h>
LiquidCrystal lcd(12,11,7,6,5,4);
void timeNprint(){
unsigned long curr = millis();
if (curr-pre>interval){
pre=curr;
ms++;
if (ms==10) {sec++;ms=0;}
if (sec==60) {sec=0;minute++;}
lcd.setCursor(0,0);
if (minute<10) lcd.print("0");
lcd.print(minute);
lcd.print(":");
if (sec<10) lcd.print("0");
lcd.print(sec);
lcd.print(":");
lcd.print(ms);
}
}
void printTime(){
lcd.setCursor(9,row);
row=!row;
if (minute<10) lcd.print("0");
lcd.print(minute);
lcd.print(":");
if (sec<10) lcd.print("0");
lcd.print(sec);
lcd.print(":");
lcd.print(ms);
}
void resetNwelcome(){
ms=0;minute=0;sec=0;
lcd.setCursor(0,1);
lcd.print("XW's Stopwatch");
lcd.setCursor(0,0);
lcd.print("Welcome to use");
}
void setup() {
lcd.begin(16,2);
pinMode(2,INPUT);
pinMode(3,INPUT);
}
void loop() {
num_rise=0;
resetNwelcome();
ss1=digitalRead(2);
if (ss1 == HIGH)
{
num_rise++;
last=millis();
lcd.clear();
while(1) //stop
{
switch(num_rise%2)
{
case 0: //pause
ss2=digitalRead(3);
ss1=digitalRead(2);
dur=millis()-last;
if (ss2==HIGH) {reset=1;break;}
else if(ss1==HIGH && dur>300) {
num_rise++;
last=millis();}
break;
case 1:
timeNprint();
ss1=digitalRead(2);dur=millis()-last;
if (ss1==HIGH &&dur>300) {
num_rise++;
last=millis();
}
break;
}
ss2=digitalRead(3);
dur2=millis()-last2;
if(ss2==1 && dur2>300)
{
last2=millis();
printTime();
}
if(reset==1)
{reset=0;lcd.clear();row=0;break;}
}
}
}
137) Arduino Robot Joystick Board Recording Movements Projet
SCHEMATICS
CODE
/* meArm analog joysticks version 1.6.1.4 - UtilStudio.com Jan 2019
Uses two analogue joysticks and four servos.
Second joystick moves gripper up, down, and closes and opens,
button start/stop playing recorded positions.
Press button for 2 seconds to autoplay.
Pins:
Arduino Stick1 Stick2 Base Shoulder Elbow Gripper Record/ Infrared
GND GND GND Brown Brown Brown Brown Auto play sensor
5V VCC VCC Red Red Red Red LED
A0 HOR
A1 VER
PD2 BUTT
A2 HOR
A3 VER
PD4 BUTT
11 Yellow
10 Yellow
9 Yellow
5 Yellow
PD3 X
12 X
*/
//#define infraredSensor true; // Uncomment this line, if you want to use Infrared controller.
/*
And replace codes of infrared controller with your own codes in function
CheckIrController.
Set debug to true and use a Serial monitor of your Arduino IDE to show received codes of
your remote controller.
*/
#include <Servo.h>
int minBase = 0;
int maxBase = 150;
int minShoulder = 25;
int maxShoulder = 135;
int minElbow = 10;
int maxElbow = 118;
int minGripper = 10;
int maxGripper = 61;
uint16_t buff[buffSize];
uint16_t buffAdd[countServo];
int recPos = 0;
int playPos = 0;
int blockPlayPos = 0;
int buffPos = 0;
struct tPlayBuff
{
byte ServoNumber;
byte Angle;
};
tPlayBuff playBuff[countServo];
int playBuffCount = 0;
byte cyclesRecord = 0;
byte cyclesPlay = 0;
int servoTime = 0;
float dx = 0;
float dy = 0;
float dz = 0;
float dg = 0;
Servo servoBase;
Servo servoShoulder;
Servo servoElbow;
Servo servoGripper;
decode_results results;
if (repeatePlaying)
{
record = false;
play = true;
}
else
{
play = false;
}
break;
}
}
}
#endif
void setup() {
Serial.begin(9600);
pinMode(xdirPin, INPUT);
pinMode(ydirPin, INPUT);
pinMode(zdirPin, INPUT);
pinMode(gdirPin, INPUT);
pinMode(pinRecord, INPUT_PULLUP);
pinMode(pinPlay, INPUT_PULLUP);
pinMode(pinLedRecord, OUTPUT);
servoBase.attach(basePin);
servoShoulder.attach(shoulderPin);
servoElbow.attach(elbowPin);
servoGripper.attach(gripperPin);
StartPosition();
digitalWrite(pinLedRecord, HIGH);
delay(1000);
digitalWrite(pinLedRecord, LOW);
}
void loop() {
buttonRecord = digitalRead(pinRecord);
buttonPlay = digitalRead(pinPlay);
dx = 0;
dy = 0;
dz = 0;
dg = 0;
if (debug)
{
Serial.println(results.value, HEX);
}
// Serial.print(buttonRecord);
// Serial.print("\t");
// Serial.println(buttonPlay);
// for testing purposes
if (buttonPlay == LOW)
{
buttonPlayCount++;
if (buttonPlay != buttonPlayLast)
{
if (record)
{
record = false;
}
if (buttonPlay == LOW)
{
play = !play;
repeatePlaying = false;
if (play)
{
// StartPosition();
}
}
buttonPlayLast = buttonPlay;
}
if (buttonRecord != buttonRecordLast)
{
if (buttonRecord == LOW)
{
record = !record;
if (record)
{
play = false;
repeatePlaying = false;
recPos = 0;
cyclesRecord = 0;
}
else
{
if (debug) PrintBuffer();
}
}
buttonRecordLast = buttonRecord;
}
if (repeatePlaying)
{
play = true;
}
posBase += dx;
posShoulder += dy;
posElbow += dz;
posGripper += dg;
if (cyclesPlay > 0)
{
if (play)
{
playPos = blockPlayPos;
}
else
{
play = false;
}
}
}
if (play)
{
if (playPos >= recPos)
{
playPos = 0;
if (repeatePlaying)
{
if (debug)
{
Serial.println("Auto start ");
}
delay(delayBetweenCycles);
// StartPosition();
}
else
{
play = false;
repeatePlaying = false;
}
}
blockPlayPos = playPos;
playBuffCount = 0;
bool endOfData = false;
while (!endOfData)
{
if (playPos >= buffSize - 1) break;
if (playPos >= recPos) break;
playBuff[playBuffCount].ServoNumber = servoNumber;
playBuff[playBuffCount].Angle = angle;
playBuffCount++;
switch (servoNumber)
{
case 0:
posBase = angle;
break;
case 1:
posShoulder = angle;
break;
case 2:
posElbow = angle;
break;
case 3:
posGripper = angle;
dg = posGripper - lastGripper;
break;
}
// if (debug)
// {
// Serial.print("Play data ");
// Serial.print(data, BIN);
// Serial.print(" servo ");
// Serial.print(servoNumber);
// Serial.print(" angle ");
// Serial.print(angle);
// Serial.print(" end=");
// Serial.println(endOfData);
// }
//
playPos++;
break;
}
}
}
}
else
{
cyclesPlay = 0;
}
currentPos[0] = posBase;
currentPos[1] = posShoulder;
currentPos[2] = posElbow;
currentPos[3] = posGripper;
if (currentPos[i] != lastPos[i])
{
positionChanged = true;
MoveServo(servoPin[i], currentPos[i], servoTime);
}
}
}
if (positionChanged)
{
if (record)
{
buffPos = 0;
cyclesRecord = 0;
AddToBuff();
}
}
else
{
if (record)
{
if (recPos > 0)
{
cyclesRecord ++;
if (cyclesRecord > 7)
{
cyclesRecord = 0;
AddToBuff();
added = true;
}
if (!added) {
uint16_t val = cyclesRecord & 7;
val = val << 12;
val = val & 0x7000;
// if (debug)
// {
// Serial.print(" i=");
// Serial.print(i);
// Serial.print(" Buff[i]=");
// Serial.print(buff[i], BIN);
// Serial.print(" val=");
// Serial.println(val, BIN);
// }
first = false;
}
}
}
}
}
lastBase = posBase;
lastShoulder = posShoulder;
lastElbow = posElbow;
lastGripper = posGripper;
if ( repeatePlaying)
{
ledLight = !ledLight;
}
else
{
if (ledLight)
{
ledLight = false;
}
if (record)
{
ledLight = true;
}
};
digitalWrite(pinLedRecord, ledLight);
delay(50);
}
void AddToBuff()
{
for (int i = 0; i < buffPos; i++)
{
buff[recPos + i] = buffAdd[i];
}
recPos += buffPos;
if (debug)
{
if (record) Serial.print(" Record ");
if (play) Serial.print(" Play ");
if (repeatePlaying) Serial.print(" Auto ");
Serial.print("Servo=");
Serial.print(servoNumber, HEX);
Serial.print("\tAngle=");
Serial.print(angle);
Serial.print("\tEnd=");
Serial.print(endOfData);
Serial.print("\tData=");
Serial.print(data, BIN);
Serial.println();
}
}
void StartPosition()
{
int angleBase = servoBase.read();
int angleShoulder = servoShoulder.read();
int angleElbow = servoElbow.read();
int angleGripper = servoGripper.read();
Serial.print(angleBase);
Serial.print("\t");
Serial.print(angleShoulder);
Serial.print("\t");
Serial.print(angleElbow);
Serial.print("\t");
Serial.print(angleGripper);
Serial.println("\t");
posBase = startBase;
posShoulder = startShoulder;
posElbow = startElbow;
posGripper = startGripper;
servoBase.write(posBase);
servoShoulder.write(posShoulder);
servoElbow.write(posElbow);
servoGripper.write(posGripper);
}
× 1
SCHEMATICS
CODE
/* meArm analog joysticks version 1.6.1.4 - UtilStudio.com Jan 2019
Uses two analogue joysticks and four servos.
Second joystick moves gripper up, down, and closes and opens,
button start/stop playing recorded positions.
Press button for 2 seconds to autoplay.
Pins:
Arduino Stick1 Stick2 Base Shoulder Elbow Gripper Record/ Infrared
GND GND GND Brown Brown Brown Brown Auto play sensor
5V VCC VCC Red Red Red Red LED
A0 HOR
A1 VER
PD2 BUTT
A2 HOR
A3 VER
PD4 BUTT
11 Yellow
10 Yellow
9 Yellow
5 Yellow
PD3 X
12 X
*/
//#define infraredSensor true; // Uncomment this line, if you want to use Infrared controller.
/*
And replace codes of infrared controller with your own codes in function
CheckIrController.
Set debug to true and use a Serial monitor of your Arduino IDE to show received codes of
your remote controller.
*/
#include <Servo.h>
int minBase = 0;
int maxBase = 150;
int minShoulder = 25;
int maxShoulder = 135;
int minElbow = 10;
int maxElbow = 118;
int minGripper = 10;
int maxGripper = 61;
uint16_t buff[buffSize];
uint16_t buffAdd[countServo];
int recPos = 0;
int playPos = 0;
int blockPlayPos = 0;
int buffPos = 0;
struct tPlayBuff
{
byte ServoNumber;
byte Angle;
};
tPlayBuff playBuff[countServo];
int playBuffCount = 0;
byte cyclesRecord = 0;
byte cyclesPlay = 0;
int servoTime = 0;
float dx = 0;
float dy = 0;
float dz = 0;
float dg = 0;
Servo servoBase;
Servo servoShoulder;
Servo servoElbow;
Servo servoGripper;
decode_results results;
if (repeatePlaying)
{
record = false;
play = true;
}
else
{
play = false;
}
break;
}
}
}
#endif
void setup() {
Serial.begin(9600);
pinMode(xdirPin, INPUT);
pinMode(ydirPin, INPUT);
pinMode(zdirPin, INPUT);
pinMode(gdirPin, INPUT);
pinMode(pinRecord, INPUT_PULLUP);
pinMode(pinPlay, INPUT_PULLUP);
pinMode(pinLedRecord, OUTPUT);
servoBase.attach(basePin);
servoShoulder.attach(shoulderPin);
servoElbow.attach(elbowPin);
servoGripper.attach(gripperPin);
StartPosition();
digitalWrite(pinLedRecord, HIGH);
delay(1000);
digitalWrite(pinLedRecord, LOW);
}
void loop() {
buttonRecord = digitalRead(pinRecord);
buttonPlay = digitalRead(pinPlay);
dx = 0;
dy = 0;
dz = 0;
dg = 0;
if (debug)
{
Serial.println(results.value, HEX);
}
// Serial.print(buttonRecord);
// Serial.print("\t");
// Serial.println(buttonPlay);
// for testing purposes
if (buttonPlay == LOW)
{
buttonPlayCount++;
if (buttonPlay != buttonPlayLast)
{
if (record)
{
record = false;
}
if (buttonPlay == LOW)
{
play = !play;
repeatePlaying = false;
if (play)
{
// StartPosition();
}
}
buttonPlayLast = buttonPlay;
}
if (buttonRecord != buttonRecordLast)
{
if (buttonRecord == LOW)
{
record = !record;
if (record)
{
play = false;
repeatePlaying = false;
recPos = 0;
cyclesRecord = 0;
}
else
{
if (debug) PrintBuffer();
}
}
buttonRecordLast = buttonRecord;
}
if (repeatePlaying)
{
play = true;
}
posBase += dx;
posShoulder += dy;
posElbow += dz;
posGripper += dg;
if (cyclesPlay > 0)
{
if (play)
{
playPos = blockPlayPos;
}
else
{
play = false;
}
}
}
if (play)
{
if (playPos >= recPos)
{
playPos = 0;
if (repeatePlaying)
{
if (debug)
{
Serial.println("Auto start ");
}
delay(delayBetweenCycles);
// StartPosition();
}
else
{
play = false;
repeatePlaying = false;
}
}
blockPlayPos = playPos;
playBuffCount = 0;
bool endOfData = false;
while (!endOfData)
{
if (playPos >= buffSize - 1) break;
if (playPos >= recPos) break;
playBuff[playBuffCount].ServoNumber = servoNumber;
playBuff[playBuffCount].Angle = angle;
playBuffCount++;
switch (servoNumber)
{
case 0:
posBase = angle;
break;
case 1:
posShoulder = angle;
break;
case 2:
posElbow = angle;
break;
case 3:
posGripper = angle;
dg = posGripper - lastGripper;
break;
}
// if (debug)
// {
// Serial.print("Play data ");
// Serial.print(data, BIN);
// Serial.print(" servo ");
// Serial.print(servoNumber);
// Serial.print(" angle ");
// Serial.print(angle);
// Serial.print(" end=");
// Serial.println(endOfData);
// }
//
playPos++;
break;
}
}
}
}
else
{
cyclesPlay = 0;
}
currentPos[0] = posBase;
currentPos[1] = posShoulder;
currentPos[2] = posElbow;
currentPos[3] = posGripper;
if (currentPos[i] != lastPos[i])
{
positionChanged = true;
MoveServo(servoPin[i], currentPos[i], servoTime);
}
}
}
if (positionChanged)
{
if (record)
{
buffPos = 0;
cyclesRecord = 0;
AddToBuff();
}
}
else
{
if (record)
{
if (recPos > 0)
{
cyclesRecord ++;
if (cyclesRecord > 7)
{
cyclesRecord = 0;
AddToBuff();
added = true;
}
if (!added) {
uint16_t val = cyclesRecord & 7;
val = val << 12;
val = val & 0x7000;
// if (debug)
// {
// Serial.print(" i=");
// Serial.print(i);
// Serial.print(" Buff[i]=");
// Serial.print(buff[i], BIN);
// Serial.print(" val=");
// Serial.println(val, BIN);
// }
first = false;
}
}
}
}
}
lastBase = posBase;
lastShoulder = posShoulder;
lastElbow = posElbow;
lastGripper = posGripper;
if ( repeatePlaying)
{
ledLight = !ledLight;
}
else
{
if (ledLight)
{
ledLight = false;
}
if (record)
{
ledLight = true;
}
};
digitalWrite(pinLedRecord, ledLight);
delay(50);
}
void AddToBuff()
{
for (int i = 0; i < buffPos; i++)
{
buff[recPos + i] = buffAdd[i];
}
recPos += buffPos;
if (debug)
{
if (record) Serial.print(" Record ");
if (play) Serial.print(" Play ");
if (repeatePlaying) Serial.print(" Auto ");
Serial.print("Servo=");
Serial.print(servoNumber, HEX);
Serial.print("\tAngle=");
Serial.print(angle);
Serial.print("\tEnd=");
Serial.print(endOfData);
Serial.print("\tData=");
Serial.print(data, BIN);
Serial.println();
}
}
void StartPosition()
{
int angleBase = servoBase.read();
int angleShoulder = servoShoulder.read();
int angleElbow = servoElbow.read();
int angleGripper = servoGripper.read();
Serial.print(angleBase);
Serial.print("\t");
Serial.print(angleShoulder);
Serial.print("\t");
Serial.print(angleElbow);
Serial.print("\t");
Serial.print(angleGripper);
Serial.println("\t");
posBase = startBase;
posShoulder = startShoulder;
posElbow = startElbow;
posGripper = startGripper;
servoBase.write(posBase);
servoShoulder.write(posShoulder);
servoElbow.write(posElbow);
servoGripper.write(posGripper);
}
× 1
DHT11 Temperature & Humidity Sensor (4
pins)
× 1
× 1
× 1
20x4 lcd
boolean state_led1 = 0;
const int duration2 = 16000;
#define MG_PIN (0) //define which analog input channel you are
going to use
#define BOOL_PIN (2)
#define DC_GAIN (8.5) //define the DC gain of amplifier
#define READ_SAMPLE_INTERVAL (50) //define how many samples you are
going to take in normal operation
#define READ_SAMPLE_TIMES (5) //define the time interval(in
milisecond) between each samples in
//normal operation
#define ZERO_POINT_VOLTAGE (0.37) //define the output of the sensor in
volts when the concentration of CO2 is 400PPM
#define REACTION_VOLTGAE (0.020) //define the voltage drop of the
sensor when move the sensor from air into 1000ppm CO2
float CO2Curve[3] = {2.602,ZERO_POINT_VOLTAGE,
(REACTION_VOLTGAE/(2.602-3))};
void setup() {
pre_time = millis();
pinMode(3,INPUT);
pinMode(4,INPUT);
pinMode(BOOL_PIN, INPUT); //set pin to input
digitalWrite(BOOL_PIN, HIGH); //turn on pullup resistors
lcd.begin(20, 4);
dht.begin();
//Notification LED Output Settings
pinMode(ledPin, OUTPUT);
//Serial communication speed 9600 baud rate setting
Serial.begin(9600);
//Start the software serial
ser.begin(9600);
//ESP8266 Reset
ser.println("AT+RST");
}
void loop() {
delay(1800);
cur_time = millis();//Assign millis to cur_time (for parallel operations)
int percentage;
float volts;
Serial.println( pre_time );
Serial.println( cur_time);
percentage = MGGetPercentage(volts,CO2Curve);
Serial.print("CO2:");
if (percentage == -1) {
Serial.print( "<400" );
} else {
Serial.print(percentage);
}
Serial.print( "ppm" );
Serial.print("\n");
if (digitalRead(BOOL_PIN) ){
Serial.print( "=====BOOL is HIGH======" );
} else {
Serial.print( "=====BOOL is LOW======" );
}
Serial.print("\n");
//---------------------------------------------------------------------------
if ((millis()-starttime) >= sampletime_ms) { //If the sample time is 5 seconds (the sample
time specified above)
ratio = lowpulseoccupancy/(sampletime_ms*10.0); // Integer percent
concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; // Fine dust sensor
specification Sheet curve use
pcsPerCF = concentration * 100; // When the particle concentration is multiplied by 100,
the CF value per particle
ugm3 = pcsPerCF / 13000; //When CF per particle is divided by 13000, the fine dust
measurement of micrograms per cubic meter
Serial.print(ugm3);
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 2);
lcd.print("Dust:");
lcd.setCursor(6, 2);
lcd.print(ugm3);
lcd.print("ug/m3");
lowpulseoccupancy = 0;
starttime = millis();
}
// String Conversion
char buf[16];
String strTemp = dtostrf(temp, 4, 1, buf);
String strHumi = dtostrf(humi, 4, 1, buf);
Serial.println(strTemp);
Serial.println(strHumi);
Serial.print("Dust density(ug/m3) = ");
Serial.println(ugm3);
//Measured value lcd display section------------------------------------------
lcd.setCursor(0, 3);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print("Co2:");
if (percentage == -1) {
lcd.print( "<400" );
} else {
lcd.print(percentage);
lcd.print("ppm");
}
lcd.setCursor(0, 0);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 0);
lcd.print("Temperature:");
lcd.setCursor(13, 0);
lcd.print(strTemp);
lcd.setCursor(0, 1);
lcd.print("Humidity:");
lcd.setCursor(10, 1);
lcd.print(strHumi);
//-----------------------------------------------------------------------------
pre_time = cur_time;
// TCP connection
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "184.106.153.149"; // api.thingspeak.com Access IP
cmd += "\",80"; // api.thingspeak.com access port, 80
ser.println(cmd);
if(ser.find("Error")){
Serial.println("AT+CIPSTART error");
lcd.setCursor(13, 3);
lcd.print("Wifioff");
return;
}
// Send Data
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
ser.println(cmd);
if(ser.find(">")){
ser.print(getStr);
lcd.setCursor(14, 3);
lcd.print("Wifion");
}
else{
ser.println("AT+CIPCLOSE");
// alert user
Serial.println("AT+CIPCLOSE");
lcd.setCursor(13, 3);
lcd.print("Wifioff");
}
}
}
//co2 measurement sensor--------------------------------------------------------
float MGRead(int mg_pin)
{
int i;
float v=0;
for (i=0;i<READ_SAMPLE_TIMES;i++) {
v += analogRead(mg_pin);
delay(READ_SAMPLE_INTERVAL);
}
v = (v/READ_SAMPLE_TIMES) *5/1024 ;
return v;
}
//--------------------------------------------
× 1
FastLED.addLeds<LED_TYPE, 3, COLOR_ORDER>(leds[1],
NUM_LEDS_PER_STRIP).setCorrection(TypicalLEDStrip);
FastLED.addLeds<LED_TYPE, 4, COLOR_ORDER>(leds[2],
NUM_LEDS_PER_STRIP).setCorrection(TypicalLEDStrip);
FastLED.addLeds<LED_TYPE, 5, COLOR_ORDER>(leds[3],
NUM_LEDS_PER_STRIP).setCorrection(TypicalLEDStrip);
Test the piezo elements
The Arduino official example for using a piezo element is very well
explained.
The four piezo elements must be connected to analog pins A0, A1, A2,
A3.
To sum up:
SCHEMATICS
CODE
#include <FastLED.h>
int score;
int currentDelay;
CRGB currentColor;
unsigned long lastTime;
int numTiles[NUM_STRIPS];
bool canCheck[NUM_STRIPS];
bool canCreate[NUM_STRIPS];
int currentIndex[NUM_STRIPS];
int tiles[NUM_STRIPS][MAX_TILES_PER_STRIP];
CRGB leds[NUM_STRIPS][NUM_LEDS_PER_STRIP];
void setup()
{
delay(3000); // power-up safety delay
FastLED.addLeds<LED_TYPE, 2, COLOR_ORDER>(leds[0],
NUM_LEDS_PER_STRIP).setCorrection(TypicalLEDStrip);
FastLED.addLeds<LED_TYPE, 3, COLOR_ORDER>(leds[1],
NUM_LEDS_PER_STRIP).setCorrection(TypicalLEDStrip);
FastLED.addLeds<LED_TYPE, 4, COLOR_ORDER>(leds[2],
NUM_LEDS_PER_STRIP).setCorrection(TypicalLEDStrip);
FastLED.addLeds<LED_TYPE, 5, COLOR_ORDER>(leds[3],
NUM_LEDS_PER_STRIP).setCorrection(TypicalLEDStrip);
InitGame();
randomSeed(37);
Serial.begin(9600);
FastLED.setBrightness(BRIGHTNESS);
}
void loop()
{
for(int i = 0; i < NUM_STRIPS; i++) {
int piezoValue = analogRead(i);
// level up
if(score % LEVEL_DURATION == 0 && score > 0) {
currentDelay -= LEVEL_SPEED_INCREASE;
if(currentDelay < MIN_TILE_DELAY) currentDelay = MIN_TILE_DELAY; // maximum
speed
currentColor = nextColor();
}
// refresh display
for(int i = 0; i < NUM_STRIPS; i++) {
SwitchOffLEDs(leds[i]);
FastLED.show();
FastLED.setBrightness(BRIGHTNESS);
}
}
void InitGame()
{
score = 0;
lastTime = millis();
currentColor = CRGB::Yellow;
currentDelay = INIT_REFRESH_RATE;
void GameOver()
{
for(int i = 0; i < NUM_STRIPS; i++) {
// Fill last tile in red
FillTile(TILE_LENGTH - 1, leds[i], CRGB::Red);
}
FastLED.show();
delay(GAME_OVER_DELAY);
InitGame();
}
CRGB nextColor() {
switch (score) {
case LEVEL_DURATION:
return CRGB::Blue;
case 2*LEVEL_DURATION:
return CRGB::Green;
case 3*LEVEL_DURATION:
return CRGB::Purple;
case 4*LEVEL_DURATION:
return CRGB::Orange;
case 5*LEVEL_DURATION:
return CRGB::Pink;
case 6*LEVEL_DURATION:
return CRGB::Salmon;
case 7*LEVEL_DURATION:
return CRGB::DeepSkyBlue;
case 8*LEVEL_DURATION:
return CRGB::ForestGreen;
default:
return CRGB::Yellow;
}
}
140) Clock with Arduino Projet
COMPONENTS AND SUPPLIES
× 1
× 1
Resistor 221 ohm
× 1
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
void setup()
pinMode(2,OUTPUT);
UtlTime=0; {
minute=0;
hour=0;
day=0;
mounth=0;
year=0;
Serial.begin(9600);
display.begin();
display.setContrast(50); // Adjust the display contrast
display.clearDisplay(); //Apaga o buffer e o display
display.setTextSize(1); //Seta o tamanho do texto
display.setTextColor(BLACK); //Seta a cor do texto
//Configura o minute
display.clearDisplay();
display.setCursor(0,0);
display.print("minute: ");
display.display();
Serial.print("\nin between minute:");
while(minute==0) {
if (Serial.available() > 0)
{
minute= Serial.parseInt();
}
}
display.print(minute);
display.display();
delay(1000);
//Configura a hour
display.clearDisplay();
display.setCursor(0,0);
display.print("hour: ");
display.display();
Serial.print("\nin between hour:");
while(hour==0)
{
if (Serial.available() > 0)
{
hour= Serial.parseInt();
}
}
display.print(hour);
display.display();
delay(1000);
//Configura o day
display.clearDisplay();
display.setCursor(0,0);
display.print("day: ");
display.display();
Serial.print("\nin between day:");
while(day==0)
{
if (Serial.available() > 0)
{
day= Serial.parseInt();
}
}
display.print(day);
display.display();
delay(1000);
//Configura o mês
display.clearDisplay();
display.setCursor(0,0);
display.print("mounth: ");
display.display();
Serial.print("\nin between mounth:");
while(mounth==0)
{
if (Serial.available() > 0)
{
mounth= Serial.parseInt();
}
}
display.print(mounth);
display.display();
delay(1000);
//Configura o year
display.clearDisplay();
display.setCursor(0,0);
display.print("year: ");
display.display();
Serial.print("\nin between year:");
while(year==0)
{
if (Serial.available() > 0)
{
year= Serial.parseInt();
}
}
display.print(year);
display.display();
delay(1000);
display.clearDisplay();
void loop()
{
if(millis()-UtlTime<0)
{
UtlTime=millis();
}
else
{
second=int((millis()-UtlTime)/1000);
}
if(second>59)
{
second=0;
minute++;
UtlTime=millis();
if(minute>59)
{
hour++;
minute=0;
if(hour>23)
{
day++;
hour=0;
if(mounth==1||mounth==3||mounth==5||mounth==7||mounth==8||mounth==10||mounth
{
if(day>31)
{
day=1;
mounth++;
if(mounth>12)
{
year++;
mounth=1;
}
}
}
else if(mounth==2)
{
if(year%400==0)
{
if(day>29)
{
day=1;
mounth++;
}
}
else if((year%4==0)&&(year%100!=0))
{
if(day>29)
{
day=1;
mounth++;
}
}
else
{
if(day>28)
{
day=1;
mounth++;
}
}
}
else
{
if(day>30)
{
day=1;
mounth++;
}
}
}
}
}
display.clearDisplay();
delay(1000);
Serial.print(day);
Serial.print("/");
Serial.print(mounth);
Serial.print("/");
Serial.print(year);
Serial.println();
display.setCursor(0,0);
display.print("date ");
display.print(day);
display.print("/");
display.print(mounth);
display.print("/");
display.print(year);
display.display();
Serial.print(hour);
Serial.print(":");
Serial.print(minute);
Serial.print(":");
Serial.print(second);
Serial.print("\n");
Serial.println();
display.setCursor(0,10);
display.print("hour ");
display.print(hour);
display.print(":");
display.print(minute);
display.print(":");
display.print(second);
display.display();
char tecla;
tecla = Serial.read();
if(tecla=='1'){
digitalWrite(2,LOW);
}
if(tecla=='2'){
digitalWrite(2, HIGH);
}
}
× 1
LED (generic)
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
void loop() {
digitalWrite(trigPin, HIGH); // initiate the ultrasonic sensor for sending and
receiving
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
× 1
Generic IR Receiver
× 1
Buzzer
× 1
× 1
× 23
× 1
APPS AND ONLINE SERVICES
Arduino IDE
void Jingle()
{
beep(speakerPin, e, 300);
beep(speakerPin, e, 300);
beep(speakerPin, e, 500);
delay(250);
beep(speakerPin, e, 300);
beep(speakerPin, e, 300);
beep(speakerPin, e, 500);
delay(350);
beep(speakerPin, e, 350);
beep(speakerPin, g, 350);
beep(speakerPin, c, 350);
beep(speakerPin, d, 350);
beep(speakerPin, e, 1000);
delay(250);
beep(speakerPin, f, 350);
beep(speakerPin, f, 350);
beep(speakerPin, f, 350);
beep(speakerPin, f, 300);
beep(speakerPin, f, 300);
beep(speakerPin, e, 320);
beep(speakerPin, e, 320);
beep(speakerPin, e, 150);
beep(speakerPin, e, 150);
beep(speakerPin, e, 150);
beep(speakerPin, d, 340);
beep(speakerPin, d, 340);
beep(speakerPin, e, 440);
beep(speakerPin, d, 540);
beep(speakerPin, g, 440);
delay(2000);
}
Printing the loading message
void setup()
{
lcd.begin(16,2);
irrecv.enableIRIn();
pinMode(speakerPin,OUTPUT);
lcd.print("Mike Player");
lcd.setCursor(0,1);
lcd.print("Loading.");
delay(1000);
lcd.print(".");
delay(1000);
lcd.print(".");
delay(1000);
lcd.print(".");
delay(1000);
lcd.print(".");
delay(1000);
lcd.clear();
lcd.print("Press Play");
}
And the short menu I've made (needs improvement)
void loop()
{
if (irrecv.decode(&results))
{
lcd.clear();
lcd.print("Select Song");
lcd.setCursor(0,1);
lcd.print("+:Song List");
if (results.value==0xA3C8EDDB) //+
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Smoke On The Water: 1 Jingle Bells: 2");
for (int positionCounter = 0; positionCounter < 64; positionCounter++)
{
lcd.scrollDisplayLeft();
delay(300);
}
}
if (results.value == 0x9716BE3F) //1
{
Smoke();
}
if (results.value == 0x3D9AE3F7) //2
{
Jingle();
}
irrecv.resume();
}
}
SCHEMATICS
CODE
#include <IRremote.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int speakerPin = 9;
int RECV_PIN = 13;
#define cL 129
#define cLS 139
#define dL 146
#define dLS 156
#define eL 163
#define fL 173
#define fLS 185
#define gL 194
#define gLS 207
#define aL 219
#define aLS 228
#define bL 232
#define c 261
#define cS 277
#define d 294
#define dS 311
#define e 329
#define f 349
#define fS 370
#define g 391
#define gS 415
#define a 440
#define aS 455
#define b 466
#define cH 523
#define cHS 554
#define dH 587
#define dHS 622
#define eH 659
#define fH 698
#define fHS 740
#define gH 784
#define gHS 830
#define aH 880
#define aHS 910
#define bH 933
IRrecv irrecv(RECV_PIN);
decode_results results;
delay(20);
}
void Smoke()
{
beep(speakerPin, cH, 500);
beep(speakerPin, dHS, 500);
beep(speakerPin, fH, 500);
delay(250);
delay(350);
delay(250);
delay(250);
}
void Jingle()
{
beep(speakerPin, e, 300);
beep(speakerPin, e, 300);
beep(speakerPin, e, 500);
delay(250);
beep(speakerPin, e, 300);
beep(speakerPin, e, 300);
beep(speakerPin, e, 500);
delay(350);
beep(speakerPin, e, 350);
beep(speakerPin, g, 350);
beep(speakerPin, c, 350);
beep(speakerPin, d, 350);
beep(speakerPin, e, 1000);
delay(250);
beep(speakerPin, f, 350);
beep(speakerPin, f, 350);
beep(speakerPin, f, 350);
beep(speakerPin, f, 300);
beep(speakerPin, f, 300);
beep(speakerPin, e, 320);
beep(speakerPin, e, 320);
beep(speakerPin, e, 150);
beep(speakerPin, e, 150);
beep(speakerPin, e, 150);
beep(speakerPin, d, 340);
beep(speakerPin, d, 340);
beep(speakerPin, e, 440);
beep(speakerPin, d, 540);
beep(speakerPin, g, 440);
delay(2000);
}
void setup()
{
lcd.begin(16,2);
irrecv.enableIRIn();
pinMode(speakerPin,OUTPUT);
lcd.print("Mike Player");
lcd.setCursor(0,1);
lcd.print("Loading.");
delay(1000);
lcd.print(".");
delay(1000);
lcd.print(".");
delay(1000);
lcd.print(".");
delay(1000);
lcd.print(".");
delay(1000);
lcd.clear();
lcd.print("Press Play");
}
void loop()
{
if (irrecv.decode(&results))
{
lcd.clear();
lcd.print("Select Song");
lcd.setCursor(0,1);
lcd.print("+:Song List");
if (results.value==0xA3C8EDDB) //+
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Smoke On The Water: 1 Jingle Bells: 2");
for (int positionCounter = 0; positionCounter < 64; positionCounter++)
{
lcd.scrollDisplayLeft();
delay(300);
}
irrecv.resume();
}
}
143) Proximity Lamp using Arduino Projet
COMPONENTS AND SUPPLIES
× 1
LED (generic)
× 1
SCHEMATICS
CODE
#include <CapacitiveSensor.h>
int in = 2;
int out = 4;
void setup()
{
Serial.begin(9600); // // initialize serial communication at 9600 bits per second:
pinMode(4, INPUT);
pinMode(9, OUTPUT);
}
void loop()
{
long start = millis();
long total1 = cs_2_4.capacitiveSensor(30); //sensor resoultion. Default 30.
// increase for higher resolution, but slower performance.
Serial.print(millis() - start); // check on performance in milliseconds
Serial.print("\t"); //tab character for debug window spacing
Serial.println(total1); // print sensor output 1
delay(10); // arbitrary delay to limit data to serial port
}
else
{
digitalWrite(9,LOW);
}
}
144) Arduino 3D Bar Charts Projet
COMPONENTS AND SUPPLIES
Arduino Mega 2560 & Genuino
Mega 2560
× 1
× 1
Male/Male Jumper Wires
× 1
Functionality Overview
Below is a diagram with the project's code overview.
Code Overview
Read Sensors will read the sensors the user attached to the device, the
values can be set constant.
ProcessData will map the sensor data to the graph
GraphData will draw the graph and graph the data on the LCD.
Drawing the Graph
As the graph is 3 dimensional there are more steps involved in drawing it,
the images below guide you through all the steps taken to draw the graph.
Who the device boots up, it will draw the outline of the graph, label it and
map the values on the y axis
It will then read the sensor data and then draw 2 dimensional bars for the
values
The device will then draw the outline of the 3D graph with lines
A Lecture
All you have to know to be able to proceed with this project is a broad
understanding onto how things are positioned on the TFT LCD, this is
explained below.
I refer to the whole LCD as the canvas, this is where everything is drawn,
all TFT LCD libraries work quite similarly, so the functions in this code
should also work with other libraries. Below is a sketch of a quadrilateral
(a rectangle) being drawn on a TFT LCD.
Sketch of Shape
In this sketch, a rectangle is drawn, each point is labelled, the line of code
that is used to draw a rectangle is this,
tft.fillRect(originX, originY, sizeX, sizeY, Colour);
originX is represented by 'z' on the diagram above, this is the distance
from the right of the screen to the shape.
originY is represented by 'x' on the sketch, this is the distance form the top
of the screen to the shape.
sizeX is the size of the shape on the x axis, this is the length of the shape.
sizeY is the size of the shape on the y axis, this is the height of the shape.
Benefits
Theuseroperatingthisprojectwillbenefitin:
Graphing their data on a professional graph in minutes
Ability to personalise the graph
Ease of set up
Constructing the Project
Step1: Required Apparatus
This example uses potentiometers as the sensors from which we will
gather the data but any sensors, digital or analogue can be used. The list of
materials is below.
1, Arduino Mega
1, Elegoo 2.8' TFT LCD
1, Breadboard
2, Potentiometers
Jumper Wires
The Schematics
Step 3: Acknowledging the Code
There are three main parts to the code:
Set Up Graph
Read Sensor Values
Draw Graph
These sections are explained below.
Set Up Graph
// draw title
tft.setCursor(10, 10); // set the cursor
tft.setTextColor(BLUE); // set the colour of the text
tft.setTextSize(3); // set the size of the text
tft.println(graphName);
// draw outline
tft.drawLine(originX, originY, ((originX + sizeX) - 20), originY,
graphColor);
tft.drawLine(originX, originY, originX, (originY - sizeY), graphColor);
tft.drawLine(originX, originY, (originX + 20), (originY - 20),
graphColor);
tft.drawLine(((originX + sizeX) - 20), originY, ((originX + sizeX)),
(originY - 20), graphColor);
tft.drawLine((originX + 20), (originY - 20), (originX + 20), ((originY -
sizeY) - 20), graphColor);
tft.drawLine((originX + 20), ((originY - sizeY) - 20), originX, (originY -
sizeY), graphColor);
tft.drawLine((originX + 20), (originY - 20), ((originX + sizeX)), (originY
- 20), graphColor);
// draw lables
for(int i = 0; i < numberOfMarks; i++)
{
tft.drawLine(mark[i], originY, mark[i], minorSizeY, graphColor);
}
// draw lable names
for(int i = 0; i < numberOfMarks; i += 2)
{
tft.setCursor((mark[i] + 6), (originY + 10));
tft.setTextColor(graphColor);
tft.setTextSize(2);
tft.println(graphBlock[i / 2]);
}
// draw numbers
for(int i = 0; i < 6; i++)
{
tft.drawLine(originX, (originY - number[i]), minorSizeX, (originY -
number[i]), graphColor);
}
// draw number values
for(int i = 0; i < 6; i++)
{
tft.setCursor((minorSizeX - 30), (number[i] + numberSize));
tft.setTextColor(graphColor);
tft.setTextSize(1);
tft.println(val[i]);
}
This section of code draws the outline of the graph and gives it a 3D
effect. This is done using the parameters set by the user.
Read Sensor Data
// get the values of the sensors
valueBlock[0] = analogRead(A15);
valueBlock[1] = analogRead(A14);
This section of code will append 2 analog values to the variables
representing the data that will be used to draw the graph.
DrawGraph
// Erase the previous blocks
for(int i = 0; i < 2; i++)
{
if(posBlock[i] > (prevPosBlock[i] + 2) || posBlock[i] < (prevPosBlock[i] -
2) || firstRun)
{
tft.fillRect((mark[i * 2] - 1), ((originY - sizeY) - 20), (boxSize + 22),
(sizeY + 20), WHITE);
}
}
// Complicated graph redrawing
if(valueBlock[0] < 5)
{
tft.drawLine((originX + 20), (originY - 20), ((originX + sizeX) / 2),
(originY - 20), graphColor);
}
if(valueBlock[1] < 5)
{
tft.drawLine((((originX + 20) * 2) + 25), (originY - 20), ((originX +
sizeX)), (originY - 20), graphColor);
}
// The main graph drawing loop
for(int i = 0; i < 2; i++)
{
if(posBlock[i] > (prevPosBlock[i] + 2) || posBlock[i] < (prevPosBlock[i] -
2) || firstRun)
{
// start drawing
tft.drawLine((mark[(i * 2) + 1]), originY, (mark[(i * 2) + 1] + 20),
(originY - 20), BLACK);
tft.drawLine((mark[(i * 2)] + 20), (posBlock[i] - 20), mark[(i * 2)],
posBlock[i], BLACK);
if(valueBlock[i] > 20)
{
// draw the bars
tft.fillRect((mark[i * 2] + 1), (posBlock[i] + 1), (boxSize - 1), (originY -
posBlock[i] - 1), blockColor);
// Draw 3D Outline
tft.drawLine((mark[(i * 2) + 1] + 20), (originY - 20), (mark[(i * 2) + 1] +
20), (posBlock[i] - 20), BLACK);
tft.drawLine((mark[(i * 2) + 1] + 20), (posBlock[i] - 20), mark[(i * 2) + 1],
posBlock[i], BLACK);
tft.drawLine((mark[(i * 2)] + 20), (posBlock[i] - 20), (mark[(i * 2) + 1] +
20), (posBlock[i] - 20), BLACK);
tft.drawLine(mark[(i * 2)], posBlock[i], (mark[(i * 2) + 1]), posBlock[i],
BLACK);
tft.drawLine(mark[(i * 2)], originY, mark[(i * 2)], posBlock[i], BLACK);
tft.drawLine(mark[(i * 2) + 1], originY, mark[(i * 2) + 1], posBlock[i],
BLACK);
// Draw the triangles
tft.fillTriangle((mark[(i * 2) + 1] + 1), (originY - 2), ((mark[(i * 2) + 1] +
20) - 1), ((originY - 20) - 1), ((mark[(i * 2) + 1] + 20) - 1), ((posBlock[i] -
20) + 2), blockColor);
tft.fillTriangle((mark[(i * 2) + 1] + 1), posBlock[i], (mark[(i * 2) + 1] + 1),
(originY - 2), ((mark[(i * 2) + 1] + 20) - 1), ((posBlock[i] - 20) + 2),
blockColor);
tft.fillTriangle((mark[(i * 2) + 1]), (posBlock[i] - 1), ((mark[(i * 2) + 1] +
20) - 2), ((posBlock[i] - 20) + 1), (mark[(i * 2)] + 2), (posBlock[i] - 1),
blockColor);
tft.fillTriangle((mark[(i * 2)] + 1), (posBlock[i] - 1), ((mark[(i * 2) + 1] +
20) - 2), ((posBlock[i] - 20) + 1), ((mark[(i * 2)] + 20)), ((posBlock[i] -
20) + 1), blockColor);
}
}
}
// print value on bars if set
for(int i = 0; i < 2; i++)
{
if(posBlock[i] > (prevPosBlock[i] + 2) || posBlock[i] < (prevPosBlock[i] -
2) || firstRun)
{
prevPosBlock[i] = posBlock[i];
if(displayValues)
{
tft.setCursor((mark[i * 2] + 5), (originY - 20));
tft.setTextColor(BLACK);
tft.setTextSize(2);
tft.println(valueBlock[(i *2) / 2]);
}
}
}
firstRun = false;
This part of code will draw the bars of the graph representing the sensor
data collected, fro further information on the exact procedure, refer to
Functionality > Drawing the Graph.
Personalising the Graph
So that is great, we have the graph, but it is always nicer to be able to
make it our own, here we will talk about personalising the graph. The lines
of code below expose the variables that have to be edited.
bool proDebug = false; // TODO - Debugging? ~
true/false - Note - Requires Serial Monitor to be open
bool displayValues = true; // TODO - Display the Values
of the Sensors on the Graph?
uint16_t graphColor = BLUE; // TODO - Colour of Graph
Outline
uint16_t blockColor = GREEN; // TODO - Colour of Bars
String graphName = "3D Bar Chart"; // TODO - Title of Graph
String graphBlock[] = {"Pot 1", "Pot 2"}; // TODO - Title of Blocks
int graphRange = 1024; // Max Value that the data can
get to - Used to map the data - Refer to Tutorial for help setting
proDebug enables printing to the serial monitor, its default position is 0
(off), when turned on (1/true), the device requires the serial monitor to be
open, it then prints values to the serial monitor, ideal for troubleshooting.
displayValues regulates if values should be displayed for each bar or not,
when turned on, the value of each sensor is displayed at the bottom of
each block, defaults to true.
graphColor sets the colour of the graph, the lines and numbers on the x
and y axis will be displayed in the selected colour.
blockColour sets the colour that the blocks/bars of the chart are displayed
in.
graphName sets the name of the chart, this is displayed at the top of the
graph in blue.
graphRange is the highest number that the sensor can output, this number
is essential for the graphing and must be set correctly, if you want to
display a Raw Analog pin's value, like the potentiometer, set it to 1024,
the max value of an Analog pin. If you are using a sensor that outputs a
gestured value, like a temperature sensor, you could set the value to a high
number like 50. (Note that the chart has not been tested with negative
numbers)
All of the other values are calculated automatically which means less time
to worry about the code and more time to enjoy the graph.
Editing Values
As mentioned so many times before, the project can graph any data you
give it. At the moment the code is designed to read Analogue pins 14 and
15 and graph those values, but the user can read any analogue pins
connected to any sensors and even integrate libraries in the code that
provide the data. Adding your own value to the graph is stepped below.
Change the values to any analogue pin you have your sensors connected to
SCHEMATICS
CODE
// Global Variables
int valueBlock[2]; // stores values
int posBlock[2];
int prevPosBlock[2];
bool firstRun = true;
// Editable Variables
bool proDebug = false; // TODO - Debugging? ~ true/false - Note -
Requires Serial Monitor to be open
bool displayValues = true; // TODO - Display the Values of the Sensors on
the Graph?
int graphRange = 1024; // Max Value that the data can get to - Used to
map the data - Refer to Tutorial for help setting
// calculate values
const int numberOfMarks = 4;
const int originX = 45;
const int originY = 200;
const int sizeX = 270;
const int sizeY = 150;
void drawHome()
{
tft.fillScreen(BLACK);
delay(500);
tft.fillScreen(WHITE);
delay(500);
}
void drawGraph()
{
// draw title
tft.setCursor(10, 10); // set the cursor
tft.setTextColor(BLUE); // set the colour of the text
tft.setTextSize(3); // set the size of the text
tft.println(graphName);
// draw outline
tft.drawLine(originX, originY, ((originX + sizeX) - 20), originY, graphColor);
tft.drawLine(originX, originY, originX, (originY - sizeY), graphColor);
tft.drawLine(originX, originY, (originX + 20), (originY - 20), graphColor);
tft.drawLine(((originX + sizeX) - 20), originY, ((originX + sizeX)), (originY - 20),
graphColor);
// draw lables
for(int i = 0; i < numberOfMarks; i++)
{
tft.drawLine(mark[i], originY, mark[i], minorSizeY, graphColor);
}
// draw lable names
for(int i = 0; i < numberOfMarks; i += 2)
{
tft.setCursor((mark[i] + 6), (originY + 10));
tft.setTextColor(graphColor);
tft.setTextSize(2);
tft.println(graphBlock[i / 2]);
}
// draw numbers
for(int i = 0; i < 6; i++)
{
tft.drawLine(originX, (originY - number[i]), minorSizeX, (originY - number[i]),
graphColor);
}
void graph()
{
// get the values of the sensors
valueBlock[0] = analogRead(A15);
valueBlock[1] = analogRead(A14);
if(proDebug)
{
Serial.println(valueBlock[0]);
Serial.println(valueBlock[1]);
Serial.println("");
}
if(proDebug)
{
Serial.println(posBlock[0]);
Serial.println(posBlock[1]);
Serial.println("");
}
if(valueBlock[1] < 5)
{
tft.drawLine((((originX + 20) * 2) + 25), (originY - 20), ((originX + sizeX)), (originY - 20),
graphColor);
}
// Draw 3D Outline
tft.drawLine((mark[(i * 2) + 1] + 20), (originY - 20), (mark[(i * 2) + 1] + 20), (posBlock[i]
- 20), BLACK);
tft.drawLine((mark[(i * 2) + 1] + 20), (posBlock[i] - 20), mark[(i * 2) + 1], posBlock[i],
BLACK);
tft.drawLine((mark[(i * 2)] + 20), (posBlock[i] - 20), (mark[(i * 2) + 1] + 20), (posBlock[i]
- 20), BLACK);
firstRun = false;
}
void setup()
{
if(proDebug)
{
Serial.begin(9600);
while(!Serial) {};
}
tft.reset();
delay(500);
uint16_t identifier = tft.readID();
identifier=0x9341;
tft.begin(identifier);
tft.setRotation(1);
drawHome();
drawGraph();
}
void loop()
{
graph();
delay(200);
}
145) Arduino Keyboard Melodies Projet
× 1
Arduino UNO & Genuino UNO
× 1
Breadboard (generic)
× 1
Buzzer
× 1
× 2
Resistor 1M ohm
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CORE VARIABLES
int speakerOut = 9; //Set up speaker on pin 9
long tempo = 10000; //Set overall tempo
int pause = 1000; //Length of pause between individual notes
int rest_count = 100;
int tone_ = 0;
int beat = 0;
long duration = 0;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MARY HAD A LITTLE LAMB
//Quarter note = 40
int melody1[] = { b4, a4, g4, a4, b4, b4, b4, R, a4, a4, a4, R, b4, d4, d4, R, b4, a4, g4, a4,
b4, b4, b4, b4, a4, a4, b4, a4, g4 }; //Tones/notes
int beats1[] = { 40, 40, 40, 40, 40, 40, 40, 2, 40, 40, 40, 2, 40, 40, 40, 2, 40, 40, 40, 40, 40,
40, 40, 40, 40, 40, 40, 40, 80 }; //Tone/note lengths
int MAX_COUNT1 = sizeof(melody1)/2; //Melody length for looping
// ALL STAR
//Quarter note = 100
int melody2[] = { b4b, g4b, g4b, e4, g4b, g4b, g4b, e4, g4b, g4b, g4b, b4b, R, b4b, d5b, b4,
d5b, e5b, g5b, g5b, a5b, g5b, g4b, g4b, a4b, g4b, b4b, a4b, a4b, g4b, a4b, a4b, b4b, e4b,
e4b }; //Tones/notes
int beats2[] = { 50, 100, 25, 25, 50, 100, 25, 25, 50, 100, 100, 100, 25, 100, 100, 50, 50, 50,
50, 50, 50, 100, 50, 50, 50, 50, 50, 100, 100, 100, 50, 50, 50, 200, 50 }; //Tone/note lengths
int MAX_COUNT2 = sizeof(melody2)/2; //Melody length for looping
// JEOPARDY
//Quarter note = 64
int melody3[] = { c5, f5, c5, f4, c5, f5, c5, c5, f5, c5, a5, g5, f5, e5, d5, d5b, c5, f5, c5, f4,
c5, f5, c5, f5, d5, c5, b4b, a4, g4, f4 }; //Tones/notes
int beats3[] = { 64, 64, 64, 64, 64, 64, 128, 64, 64, 64, 96, 32, 32, 32, 32, 32, 64, 64, 64, 64,
64, 64, 128, 96, 32, 64, 64, 64, 64, 64 }; //Tone/note lengths
int MAX_COUNT3 = sizeof(melody3)/2; //Melody length for looping
// LONELY
//Quarter note = 84
int melody4[] = { d4, a4, g4b, a4, d4b, a4, g4b, g4, a4, d4b, g4, g4b, g4, a4, b4, a4, a5, a5
}; //Tones/notes
int beats4[] = { 84, 168, 63, 21, 84, 168, 32, 32, 32, 84, 63, 32, 32, 32, 32, 168, 84, 84 };
//Tone/note lengths
int MAX_COUNT4 = sizeof(melody4)/2; //Melody length for looping
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PLAY TONE
void playTone() { //Pulse the speaker to play a tone for a particular duration (so that there is
a small break between each note and they don't immediatly follow each other)
long elapsed_time = 0;
if (tone_ > 0) { //if this isn't a rest beat, while the tone has played less long than 'duration',
pulse speaker HIGH and LOW
while (elapsed_time < duration) {
digitalWrite(speakerOut,HIGH);
delayMicroseconds(tone_ / 2);
digitalWrite(speakerOut, LOW);
delayMicroseconds(tone_ / 2);
elapsed_time += (tone_); //Keep track of how long we pulsed
}
}
else {
for (int j = 0; j < rest_count; j++) {
delayMicroseconds(duration);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SETUP
void setup() {
pinMode(speakerOut, OUTPUT);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LOOP
void loop() {
int keyVal = analogRead(A0);
Serial.println(keyVal);
// PIN ONE (MARY HAD A LITTLE LAMB)
if(keyVal >= 1011){ //Only when the 1st button is pressed
for (int i=0; i<MAX_COUNT1; i++) { //Set up a counter to pull from melody1[] and
beats1[]
tone_ = melody1[i]; //Defining which notes to play
beat = beats1[i]; //Defining the note lengths to use
duration = beat * tempo; //Set up timing
playTone(); //Inserting/applying the code for a pause between notes
delayMicroseconds(pause);
}
}
// PIN TWO (ALL STAR)
else if(keyVal >= 990 && keyVal <= 1010){ //Only when the 2nd button is pressed
for (int i=0; i<MAX_COUNT2; i++) { //Set up a counter to pull from melody2[] and
beats2[]
tone_ = melody2[i]; //Defining which notes to play
beat = beats2[i]; //Defining the note lengths to use
duration = beat * tempo; //Set up timing
playTone(); //Inserting/applying the code for a pause between notes
delayMicroseconds(pause);
}
}
// PIN THREE (JEOPARDY)
else if(keyVal >= 480 && keyVal <= 515){ //Only when the 3rd button is pressed
for (int i=0; i<MAX_COUNT3; i++) { //Set up a counter to pull from melody3[] and
beats3[]
tone_ = melody3[i]; //Defining which notes to play
beat = beats3[i]; //Defining the note lengths to use
duration = beat * tempo; //Set up timing
playTone(); //Inserting/applying the code for a pause between notes
delayMicroseconds(pause);
}
}
// PIN FOUR (LONELY)
else if(keyVal >= 5 && keyVal <= 10){ //Only when the 4th button is pressed
for (int i=0; i<MAX_COUNT4; i++) { //Set up a counter to pull from melody4[] and
beats4[]
tone_ = melody4[i]; //Defining which notes to play
beat = beats4[i]; //Defining the note lengths to use
duration = beat * tempo; //Set up timing
playTone(); //Inserting/applying the code for a pause between notes
delayMicroseconds(pause);
}
}
// NONE
else{
noTone(8);
}
}
146) Arduino DC Motor Speed Control and Measurement Projet
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
Geared DC Motor, 12 V
× 1
Alphanumeric LCD, 20 x 4
× 1
Darlington High Power Transistor
× 1
NECESSARY TOOLS AND MACHINES
Breadboard, 270 Pin
APPS AND ONLINE SERVICES
Arduino IDE
Circuit description:
As shown in figure, the circuit is built using arduino UNO development
board, 16x4 LCD, NPN Darlington transistor TIP122 and opto interrupt
sensor MOC7811.
· The analog output pin 9 of arduino drives 12V@2000 RPM DC motor
through TIP122. This pin is given to base input of TIP122 through
current limiting resistor R2 and DC motor is connected to collector of
TIP122
· The internal IR LED of MOC7811 is given forward bias using 5V
supply form arduino board through current limiting resistor R1.
Internal photo transistor is pulled up by resistor R4. The collector
output of transistor is connected to digital pin 7 or arduino
· LCD data pins D4 to D7 are connected to digital pins 5, 4, 3 and 2 of
arduino while control pins Rs and En are connected to 12 and 11. RW
pin is connected to ground. Vcc pin and LED+ pin are connected to 5V
supply from arduino board and Vss pin and LED- pins are connected to
arduino board ground
· One pot is connected to Vee pin to vary contras of LCD
Circuit operation:
· First the motor is given 12 V supply through external power supply.
Next the arduino board, LCD and sensor is given supply through USB
from PC / laptop
· Initially the LCD shows different parameters as
PWM ip:
PWM Duty:
PWM volt:
speed:
· Then arduino starts applying PWM to motor with maximum pulse
width
· So motor will start rotating at maximum speed. Some time delay is
provided to allow motor to attain full speed
· As the motor starts rotating, the slotted wheel attached to its shaft will
also rotate
· The MOC7811 sensor is placed such a way that the slot of wheel
passes through sensor air gap. Thus when motor rotates one full
revolution, the slot passes through sensor gap. Due the slot in the wheel
the IR light falls on photo transistor. So transistor conducts and
generates negative pulse in collector output. Thus each rotation of
motor produces pulse
· The frequency of these pulses is actually RPS (-revolution per
second) of motor. To measure the frequency of this pulse first the ON
time is measured then OFF time is measured and from these frequency
is calculated as
Time period = Ton + Toff (in us)
Frequency= 1000000/time period
· This frequency is speed of motor in RPS. From this RPS, speed of
motor is calculated in RPM as
RPM= 60×RPS
· The PWM input is varied from 250 to 100 in step of 15. That is
directly displayed on LCD
· The ON time and OFF time of PWM output is also measured to
calculate the PWM duty cycle as
PWM duty = [PWM_Ton / (PWM_Ton + PWM_Toff)] × 100
· Finally voltage applied to motor is calculate as
Voltage applied to motor = motor voltage × duty
= (12/100)× duty
· First the PWM input is decreased from 250 to 100 in 10 steps of 15
and then again it is increased from 100 to 250 and this cycle is repeated
continuously
· So motor speed continuously decreases and then continuously
increases. We can observe the change in motor speed that is displayed
on LCD as speed in RPM
Thus the given project varies the speed of DC motor and also measures
it accurately. It displays % of pulse width applied to motor along with
applied voltage. So one can note down motor speed in RPM at different
voltage and pulse width in observation table for further needs.
SCHEMATICS
CODE
#include <LiquidCrystal.h>
void setup()
{
pinMode(motor_RPS_pulse_ip,INPUT);
pinMode(motor_PWM_pulse_ip,INPUT);
lcd.begin(16, 4);
lcd.clear();
lcd.print("Pulse Width:");
lcd.setCursor(0,1);
lcd.print("PWM Volt:");
lcd.setCursor(0,2);
lcd.print("Speed(RPS):");
lcd.setCursor(0,3);
lcd.print("Speed(RPM):");
}
void loop()
{
analogWrite(3,pulse_width);
PWM_Ton= pulseIn(motor_PWM_pulse_ip,HIGH);
PWM_Toff=pulseIn(motor_PWM_pulse_ip,LOW);
delay(2000);
PWM_T = PWM_Ton+PWM_Toff;
PWM_duty = (PWM_Ton/PWM_T)*100;
voltage = 0.12*PWM_duty;
lcd.setCursor(12,0);
lcd.print(PWM_duty);
lcd.print('%');
lcd.setCursor(9,1);
lcd.print(voltage);
lcd.print('V');
pulse_width-=15;
if(pulse_width==90) pulse_width = 255;
delay(3000);
}
× 2
433MHZ RF wireless receiver &
transmitter module × 1
Breadboard (generic)
× 2
SCHEMATICS
Laptop Uno connected to RF transmitter
#include <VirtualWire.h>
#include <VirtualWire_Config.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
char cad[100];
int i=0;
void setup()
{
// put your setup code here, to run once:
lcd.begin(16, 2);
lcd.setCursor(3, 0);
lcd.print("UNO-TX !");
// initialize serial:
Serial.begin(9600);
vw_setup(2000);
Serial.println("Encrtypted Communication");
Serial.println("Developed by: Mr-Joe");
Serial.println("-------------------------");
Serial.println("Important:(UNO - TX) ");
Serial.println("End with \".\" each data");
}
void loop()
{
if( Serial.available() > 0)
{
cad[i] = Serial.read();
i++;
}
if( cad[i-1] == '.')
{
lcd.setCursor(1, 1);
lcd.print( "**Classified** " );
cad[i] = '\0';
i=0;
vw_send((byte *)cad, strlen(cad));
delay(400);
}
}
Receiver.ino
#include <VirtualWire.h>
#include <VirtualWire_Config.h>
#include <LiquidCrystal.h>
// initialize serial:
Serial.begin(9600);
vw_setup(2000);
Serial.println("Encrtypted Communication");
Serial.println("Developed by: Mr-Joe ");
Serial.println("-------------------------");
Serial.println("Important:(UNO - RX) ");
void loop()
{
byte buf[VW_MAX_MESSAGE_LEN];
byte buflen = VW_MAX_MESSAGE_LEN;
int i;
if( vw_get_message(buf, &buflen) )
{
// dont uncomment that unless you need to use a flag for each received
line.
/*if(pos < 2)
lcd.setCursor(0, 1);
else
{
pos=0;
Serial.println(" ");
lcd.clear();
lcd.setCursor(3, 0);
lcd.print("UNO-RX !");
lcd.setCursor(1, 1);
}*/
}
if( buf[i-1] == '.')
{
lcd.setCursor(1, 1);
lcd.print( "**Classified** " );
Serial.println(" ");
buf[i] = '\0';
i=0;
}
}
}
148) Arduino Burglar Projet
LED (generic)
×1
LED (generic)
×1
LED (generic)
×1
Buzzer
×1
Adafruit keypad
×1
Breadboard (generic)
×1
Resistor 1k ohm
×1
Resistor 1k ohm
×1
Resistor 1k ohm
CODE
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Addr, En, Rw, Rs, d4, d5,
d6, d7, backlighpin, polarity
#include <Keypad.h> //includo libreria per tastierino numerico 4*4
#define led 10
#define led1 13
#define led2 12
#define PIR 7
#define BUZZER 6
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
}; //matrice che rappresenta la tastiera collegata ad arduino
byte pinRiga[dim] = {19, 15, 16, 17};
byte pinColonna[dim] = {1, 2, 3, 4}; //vettore che contiene i pin delle colonne
//vettore che contiene i pin delle righe
char tasto; //variabile che contiene il valore del tasto premuto
bool Pass_Completa = false ;
void setup()
{
lcd.clear();
lcd.begin(16,2);
lcd.backlight();
pinMode (led,OUTPUT);
pinMode (led1,OUTPUT);
digitalWrite(led2,OUTPUT);
pinMode(PIR,INPUT); //imposto il pin 2 come input
pinMode(BUZZER,OUTPUT); //imposto il pin 3 come output
//imposto la velocità di comunicazione seriale a 9600 bit al secondo
// attachInterrupt(0,interruzione,RISING); //imposto il pin di interruput,la funzione che
deve richiamare e in quale caso si deve attivare (RISING --> sul fronte di salita)
}//end setup
void loop()
{
switch(stato)
{
/*Stato di partenza in cui si chiede la password per abilitare l'antifurto*/
case 0:
digitalWrite(led1,HIGH);
lcd.clear();
lcd.print("Digitare PIN: ");
while(Pass_Completa == false)
{
tasto = keypad.getKey(); //lettura del tasto premuto
keypad.setDebounceTime(tempo); //tempo di debounce per premuta tasti
if(tasto)
{
password[conta] = tasto; //salvo il tasto premuto nel vettore di caratteri
lcd.print(password[conta]); //stampa del tasto premuto
delay(100);
lcd.clear();
#if DEBUG
delay(100);
lcd.print(conta);
#endif //fine if condizionale del preprocessore
lcd.clear();
delay(100);
lcd.println("");
conta++;
}//end if
if(conta == Lunghezza_Password-1)
{
password[5] = '\0'; //chiudo la stringa
Pass_Completa = true; //imposto la password a vero per uscire dal ciclo while
conta = 0; //imposto la variabile contatore nuovamente a 0 per un possibile nuovo input di
password
} //end if
}//end while
lcd.clear();
digitalWrite(led1,LOW);
break; //end case 0
lcd.println("Antifurto ON");
delay(3000);
lcd.clear();
lcd.println("Tasto D per OFF");
//delay(3000);
while(AllarmeAttivo == true)
{
tasto = keypad.getKey(); //lettura tasto premuto
keypad.setDebounceTime(tempo); //debounce per tasto premuto
valPIR = digitalRead(PIR);
lcd.clear();
#if DEBUG
lcd.clear();
lcd.println(tasto);
delay(1000);
lcd.clear();
delay(10);
#endif
if(valPIR == 1)
{ digitalWrite(led2, LOW);
stato = 2;
AllarmeAttivo = false; //imposto il valore a falso
}
if(tasto == 'D')
{ digitalWrite(led2, LOW);
lcd.clear();
lcd.println("disattivazione");
stato = 0; //imposto lo stato a 0 per tornare così allo stato di partenza
} //end if
} //end while
case 2:
{
analogWrite(BUZZER,HIGH);
digitalWrite(led, HIGH);
delay(500);
analogWrite(BUZZER,LOW);
digitalWrite(led, LOW);
delay(500);
}
stato = 1;
break;
× 1
1Sheeld
× 1
Breadboard (generic)
× 1
Android device
× 1
Arduino cable
× 1
electric strike
× 1
relay module
× 1
jumpers
× 1
lamp
× 1
ABOUT THIS PROJECT
This project enables you to:
1. Control your home (or at least your room's) lights and power outlets
(on/off) using a keypad in your android smartphone.
2. Get a buzzer beep through your phone speaker in case of detecting
smoke in your home that exceed a threshold predefined value.
3. Access your home, simply opening your home door lock, through
entering a pattern. In case of entering the correct pattern, the door becomes
unlocked and you get an email informing you that the home was accessed.
In case of entering a wrong pattern, a photo of the one entering the pattern
is captured and sent to you attached in a mail informing you of an attempt
to access the home.
First Step:
1. Connect the 1sheeld to the arduino.
2. Connect the signal pin of the relay module to pin 13 in the Arduino.
3. Connect the vcc pin of the relay module to the 5V pin of the Arduino.
4. Connect the GND pin of the really module to pin GND of the Arduino.
5. Connect the vcc pin of the smoke sensor to pin 5V of the Arduino.
6. Connect the GND pin of the smoke sensor to the GND pin of the
arduino.
7. Connect the analog signal pin of the smoke sensor to pin A0 of the
Arduino.
8. Connect the signal pin of the electric strike to pin 13 of the Arduino.
9. Connect the power pins of the electric strike to prop-er power sources.
10, Connect Arduino to your computer through the USB cable.
Connection of arduino, 1sheeld and the modules
Second Step: Write the code
1. Download 1sheeld Arduino Library and save it in the suitable folder.
2. Start writing the code by adding initialization values and library
defining
#define CUSTOM_SETTINGS
#define INCLUDE_BUZZER_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD
#define INCLUDE_KEYPAD_SHIELD
#define INCLUDE_EMAIL_SHIELD
#define INCLUDE_PATTERN_SHIELD
#define INCLUDE_CAMERA_SHIELD
#include
int taken =0;
long previousMillis = 0;
int State = LOW;
int lamp = 12;
int sensor = A0;
int reading = 0;
int Lock = 13;
PatternNode patternStored[] = { {0, 0}, {1, 0}, {2, 0}, {2, 1}, {2, 2} };
int counter = 0;
int length = 0;
3. Writing the setup part of the arduino program
void setup()
{
OneSheeld.begin();
pinMode(lamp, OUTPUT);
pinMode(sensor, INPUT);
pinMode(Lock, OUTPUT);
}
4. Write the function of the pattern and door lock
void pattern() { if (Pattern.isNewPatternReceived())
{
/* This pointer act as array to store the last pattern entered by user. */
PatternNode * patternEntered = Pattern.getLastPattern();
/* Get the length of the pattern to loop over it. */
length = Pattern.getLastPatternLength();
/* Check if the pattern length is equal to 5. */
if (length == 5)
{
for (int i = 0; i < length ; i++)
{
if (patternEntered[i].row == patternStored[i].row && patternEntered[i].col
== patternStored[i].col)
{
counter++;
}
}
if (counter == 5)
{
digitalWrite(Lock, HIGH); // lock is high when opened
Email.send("[email protected]", "Your Home Security", "Your
home was accessed right now!");
taken =0;
}
else
{
digitalWrite(Lock, LOW);
if (taken ==0){
Camera.setFlash(ON);
Camera.rearCapture();
taken = 1;
}
Email.attachLastPicture ("[email protected]", "Your Home
Security", "Someone tried to access your home and we took a picture of
him", 0);
counter = 0;
}
}
/* If pattern length is different turn off the LED. */
else
{
digitalWrite(Lock, LOW);
if (taken ==0){
Camera.setFlash(ON);
Camera.rearCapture();
taken = 1;
}
Email.attachLastPicture ("[email protected]", "Your Home
Security", "Someone tried to access your home and we took a picture of
him", 0);
}
}
}
5. Write the loop part of the code in which the function of the keypad and
the smoke sensor and the calling of the pattern function are included
void loop()
{
if (Keypad.isRowPressed(0) && Keypad.isColumnPressed(0))
{
if (digitalRead(lamp) == LOW)
{
digitalWrite(lamp, HIGH);
}
else
{
digitalWrite(lamp, LOW);
}
}
reading = analogRead(sensor);
if (reading >= 90) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > 1500) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (State == LOW)
{ State = HIGH;
Buzzer.buzzOn();
}
else
{ State = LOW;
Buzzer.buzzOff();
}
}
}
else
{
Buzzer.buzzOff();
}
pattern();
}
Third step: Upload the code
1. Switch the 1sheeld to the upload mode with the switch being directed
away from 1sheeld logo.
2. Verify the code on Arduino IDE.
3. Upload the code to the Arduino.
4. Switch the 1sheeld to the bluetooth mode using the switch directed
towards the 1sheeld logo.
Fourth and Final Step: HAVE FUN!
1. Download 1sheeld app from play store for android.
2. Open your bluetooth and connect to your shield from the app.
3. Add the following shields:
- Buzzer
- Keypad
- E-mail
- Camera
- Pattern
4. Start testing:
- Click the '1' button of the keypad and enjoy the lamp turning on and
turning off when you click it again.
- Expose the smoke sensor of your home to smoke and listen to your
phone speaker beeping.
- Try to enter the correct pattern (which is L in this case as written in the
code and which is the default pattern) and see the electric strike opening
and receiving the email.
- Try to enter a wrong pattern and check the received mail with your photo
attachedas the one who have tried to access the home door.
SCHEMATICS
CODE
#define CUSTOM_SETTINGS
#define INCLUDE_BUZZER_SHIELD
#define INCLUDE_KEYPAD_SHIELD
#define INCLUDE_EMAIL_SHIELD
#define INCLUDE_PATTERN_SHIELD
#define INCLUDE_CAMERA_SHIELD
#include <OneSheeld.h>
int taken =0;
long previousMillis = 0;
int State = LOW;
void setup()
{
OneSheeld.begin();
pinMode(lamp, OUTPUT);
pinMode(sensor, INPUT);
pinMode(Lock, OUTPUT);
void loop()
{
if (Keypad.isRowPressed(0) && Keypad.isColumnPressed(0))
{
if (digitalRead(lamp) == LOW)
{
digitalWrite(lamp, HIGH);
}
else
{
digitalWrite(lamp, LOW);
}
}
reading = analogRead(sensor);
if (reading >= 90) {
unsigned long currentMillis = millis();
if (State == LOW)
{ State = HIGH;
Buzzer.buzzOn();
}
else
{ State = LOW;
Buzzer.buzzOff();
}
}
}
else
{
Buzzer.buzzOff();
}
pattern();
void pattern() {
if (Pattern.isNewPatternReceived())
{
PatternNode * patternEntered = Pattern.getLastPattern();
length = Pattern.getLastPatternLength();
if (length == 5)
{
if (counter == 5)
{
digitalWrite(Lock, HIGH); // lock is high when opened
Email.send("[email protected]", "Your Home Security", "Your home was accessed
right now!");
taken =0;
}
else
{
digitalWrite(Lock, LOW);
if (taken ==0){
Camera.setFlash(ON);
Camera.rearCapture();
taken = 1;
}
Email.attachLastPicture ("[email protected]", "Your Home Security", "Someone tried
to access your home and we took a picture of him", 0);
counter = 0;
}
}
else
{
digitalWrite(Lock, LOW);
if (taken ==0){
Camera.setFlash(ON);
Camera.rearCapture();
taken = 1;
}
Email.attachLastPicture ("[email protected]", "Your Home Security", "Someone tried
to access your home and we took a picture of him", 0);
}
}
}
150) Garage Door Opener with Modem and Arduino Projet
× 1
SCHEMATICS
CODE
#include <SoftwareSerial.h> //Including Sotware
Serial lib for second serial port to connect Siemens TC35i
void loop() {
else {
Serial.println("Unknow number door sill locked"); //Print to debug port
serial2.println("AT H"); //Hang up the call/ring
temp = serial2.readString(); //Eliminate "OK" feedback to AT H command
void dooropen()
{
Serial.println("Opening the door"); //Print to debug port
digitalWrite(door, LOW); //Set relay output LOW, activate the relay
delay(1000); //Wait 1 sec
digitalWrite(door, HIGH); //Set relay output HIGH, relay normal state
}
151) Arduino Copy Of Fidget Spinner RPM Counter Projet
× 3
LED (generic)
× 3
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
void setup()
{
pinMode(hallSensorPin,INPUT);
Serial.begin(9600);
lcd.begin(16, 2);
lcd.print("Initializing");
delay(1000);
lcd.clear();
lcd.print("Welcome to Fidget Spinner RPM Counter");
for (int positionCounter = 0; positionCounter < 21; positionCounter++) {
lcd.scrollDisplayLeft();
delay(350);
}
delay(1000);
lcd.clear();
}
void loop()
{
delay(100);
int rpm = getRPM();
if (rpm > rpmMaximum) rpmMaximum = rpm;
lcd.clear();
displayRPM(rpm);
displayBar(rpm);
int getRPM()
{
int count = 0;
boolean countFlag = LOW;
unsigned long currentTime = 0;
unsigned long startTime = millis();
while (currentTime <= sampleTime)
{
if (digitalRead(hallSensorPin) == HIGH)
{
countFlag = HIGH;
}
if (digitalRead(hallSensorPin) == LOW && countFlag == HIGH)
{
count++;
countFlag=LOW;
}
currentTime = millis() - startTime;
}
int countRpm = int(60000/float(sampleTime))*count;
return countRpm;
}
× 1
ControlEverything.com 4-
CHANNEL RELAY
CONTROLLER FOR I2C × 1
HC-05 Bluetooth Module
× 1
× 1
Breadboard (generic)
× 1
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Andoid Application
Edit a new panel
Add new panel
Add 2 switches and edit their Turn On Status according to the code
Add 2 switches
Now click on the "Connect" button and select "Bluetooth Classic" option
then click "Next" button
Connect with Bluetooth
After that pair with this application with "HC-05 Bluetooth Module" and
click "Done" button. Finally Click "Run" button to start working with this
app.
Pairing
Warning
Do not touch any wires while connecting the system with AC Supply
Do not disconnect any connections during powering up the system.
Complete all the connections properly.
SCHEMATICS
CODE
int input1=8;
int input2=9;
void setup() {
pinMode(input1, OUTPUT);
pinMode(input2,OUTPUT);
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0)
{
char data= Serial.read();
switch(data)
{
case 'a': digitalWrite(input1, HIGH);
break;
default : break;
}
Serial.println(data);
}
delay(50);
}
153) Arduino Working with Shift Register Projet
Breadboard (generic)
× 1
LED (generic)
× 8
Resistor 1k ohm
× 8
× 1
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
void loop()
{
digitalWrite (LatchPin, LOW);
shiftOut (DataPin, ClockPin, LSBFIRST, 255);
digitalWrite (LatchPin, HIGH);
delay (1000);
digitalWrite (LatchPin, LOW);
shiftOut (DataPin, ClockPin, LSBFIRST, 0);
digitalWrite (LatchPin, HIGH);
delay (1000);
}
byte Data = 0;
void setup()
{
pinMode (DataPin, OUTPUT);
pinMode (ClockPin, OUTPUT);
pinMode (LatchPin, OUTPUT);
}
void loop()
{
shiftWrite (0,1);
delay(1000);
shiftWrite (1,1);
delay(1000);
shiftWrite (2,1);
delay(1000);
shiftWrite (3,1);
delay(1000);
shiftWrite (4,1);
delay(1000);
shiftWrite (5,1);
delay(1000);
shiftWrite (6,1);
delay(1000);
shiftWrite (7,1);
delay(1000);
shiftWrite (0,0);
delay(1000);
shiftWrite (1,0);
delay(1000);
shiftWrite (2,0);
delay(1000);
shiftWrite (3,0);
delay(1000);
shiftWrite (4,0);
delay(1000);
shiftWrite (5,0);
delay(1000);
shiftWrite (6,0);
delay(1000);
shiftWrite (7,0);
delay(1000);
}
Arduino Nano R3
× 1
× 1
× 2
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
// display features
static boolean top2bottom = false; // display direction (top to bottom, or right to left
static boolean hour24 = false; // 24 hour display?
static boolean charHI = true; // highlight whole character
//*************************************************************************************
// Initial Setup
//*************************************************************************************
void setup () {
Wire.begin();
Serial.begin(57600);
if(doSerial) Serial.print("MATRIX Clock - Adrian Jones, Mar. 2014");
// LED pins
pinMode(mode_Pin, OUTPUT); // mode pin
digitalWrite(mode_Pin, 1);
pinMode(min_Pin, OUTPUT); // minute pin
digitalWrite(min_Pin, 1);
// encoder control
pinMode(enc_PinA, INPUT_PULLUP); digitalWrite(enc_PinA, HIGH); // rotary
encoder pin A
pinMode(enc_PinB, INPUT_PULLUP); digitalWrite(enc_PinB, HIGH); // rotary
encoder pin B
pinMode(enc_Switch, INPUT_PULLUP);digitalWrite(enc_Switch, HIGH); // encoder
switch
attachInterrupt(0, rotEncoder, CHANGE); // time setting
attachInterrupt(1, swEncoder, CHANGE); // mins / hours
// RTC
RTC.begin();
if (! RTC.isrunning()) {
RTC.adjust(DateTime(__DATE__, __TIME__));
if(doSerial) Serial.println(" (RTC reset)");
} else {
if(doSerial) Serial.println(" (RTC running)");
}
//*************************************************************************************
// Main Loop
//*************************************************************************************
void loop () {
if(updateFlag) {
show_time_and_date(now);
updateFlag = false;
}
while(rotating) {
delay(1); // debounce
adjTime(now, clockwise);
show_time_and_date( RTC.now() );
display_message = createMessage(now);
arraylen = initDisplayString(display_message);
delay(1);
rotating = false; // Reset the interrupt flag back to false
}
delay(5);
//
**********************************************************************************
//
// INTERRUPT ROUTINES
//
**********************************************************************************
//
//
**********************************************************************************
//
// OPERATION ROUTINES
//
**********************************************************************************
//
// function newDelay
void newDelay (int dly) {
for (int z=1; z< dly; z++) {
delay(1);
if(rotating || updateFlag) break;
}
}
// function rotChar(char): for character char, transposes bits 90 deg. (top - bottom ==> left -
right)
// and stores results in rc[0] - rc[7].
byte rotChar(char inLetter) {
int ind = int(inLetter) - 0x20;
for (int col = 0; col < 8; col++) {
byte mask = 0x01 << (7-col);
for (int row = 0; row < 8 ; row++) { bitWrite(rc[col], 7-row,(alphanum[ind][row] & mask));
}
}
}
Serial.print(te);
if(hours<10) Serial.print(0); Serial.print(hours,DEC);
Serial.print(":");
if(minutes<10) Serial.print(0); Serial.print(minutes,DEC);
Serial.print(":");
if(seconds < 10) Serial.print(0); Serial.print(seconds,DEC);
Serial.println("");
}
}
Arduino Gemma
× 1
SparkFun LED
× 1
Breadboard (generic)
× 1
circuito.io
SCHEMATICS
CODE
// Include Libraries
#include "Arduino.h"
// Pin Definitions
#define LEDRed_PIN_VIN 0
#define MQ9_PIN_AOUT 2
// Setup the essentials for your circuit to work. It runs first every time your
circuit is powered with electricity.
void setup()
{
// Setup Serial which is useful for debugging
// Use the Serial Monitor to view printed messages
Serial.begin(9600);
while (!Serial) ; // wait for serial port to connect. Needed for native USB
Serial.println("start");
Arduino Nano R3
× 1
NECESSARY TOOLS AND MACHINES
3D Printer (generic)
SCHEMATICS
CODE
#include <Wire.h>
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
//#define Wire.write(x) Wire.send(x)
//#define Wire.read() Wire.receive()
#endif
static uint8_t nunchuck_buf[6]; // array to store nunchuck data,
// Uses port C (analog in) pins as power & ground for Nunchuck
static void nunchuck_setpowerpins() {
#define pwrpin PORTC3
#define gndpin PORTC2
DDRC |= _BV(pwrpin) | _BV(gndpin);
PORTC &= ~ _BV(gndpin);
PORTC |= _BV(pwrpin);
delay(100); // wait for things to stabilize
}
// initialize the I2C system, join the I2C bus,
// and tell the nunchuck we're talking to it
static void nunchuck_init() {
Wire.begin(); // join i2c bus as master
Wire.beginTransmission(0x52);// transmit to device 0x52
#if (ARDUINO >= 100)
Wire.write((uint8_t)0x40);// sends memory address
Wire.write((uint8_t)0x00);// sends sent a zero.
#else
Wire.send((uint8_t)0x40);// sends memory address
Wire.send((uint8_t)0x00);// sends sent a zero.
#endif
Wire.endTransmission();// stop transmitting
}
// Send a request for data to the nunchuck
// was "send_zero()"
static void nunchuck_send_request() {
Wire.beginTransmission(0x52);// transmit to device 0x52
#if (ARDUINO >= 100)
Wire.write((uint8_t)0x00);// sends one byte
#else
Wire.send((uint8_t)0x00);// sends one byte
#endif
Wire.endTransmission();// stop transmitting
}
// Encode data to format that most wiimote drivers except
// only needed if you use one of the regular wiimote drivers
static char nunchuk_decode_byte (char x) {
x = (x ^ 0x17) + 0x17;
return x;
}
// Receive data back from the nunchuck,
// returns 1 on successful read. returns 0 on failure
static int nunchuck_get_data() {
int cnt = 0;
Wire.requestFrom (0x52, 6);// request data from nunchuck
while (Wire.available ()) {
// receive byte as an integer
#if (ARDUINO >= 100)
nunchuck_buf[cnt] = nunchuk_decode_byte( Wire.read() );
#else
nunchuck_buf[cnt] = nunchuk_decode_byte( Wire.receive() );
#endif
cnt++;
}
nunchuck_send_request(); // send request for next data payload
// If we recieved the 6 bytes, then go print them
if (cnt >= 5) {
return 1; // success
}
return 0; //failure
}
// Print the input data we have recieved
// accel data is 10 bits long
// so we read 8 bits, then we have to add
// on the last 2 bits. That is why I
// multiply them by 2 * 2
static void nunchuck_print_data() {
static int i = 0;
int joy_x_axis = nunchuck_buf[0];
int joy_y_axis = nunchuck_buf[1];
int accel_x_axis = nunchuck_buf[2]; // * 2 * 2;
int accel_y_axis = nunchuck_buf[3]; // * 2 * 2;
int accel_z_axis = nunchuck_buf[4]; // * 2 * 2;
int z_button = 0;
int c_button = 0;
// byte nunchuck_buf[5] contains bits for z and c buttons
// it also contains the least significant bits for the accelerometer data
// so we have to check each bit of byte outbuf[5]
if ((nunchuck_buf[5] >> 0) & 1)
z_button = 1;
if ((nunchuck_buf[5] >> 1) & 1)
c_button = 1;
if ((nunchuck_buf[5] >> 2) & 1)
accel_x_axis += 1;
if ((nunchuck_buf[5] >> 3) & 1)
accel_x_axis += 2;
if ((nunchuck_buf[5] >> 4) & 1)
accel_y_axis += 1;
if ((nunchuck_buf[5] >> 5) & 1)
accel_y_axis += 2;
if ((nunchuck_buf[5] >> 6) & 1)
accel_z_axis += 1;
if ((nunchuck_buf[5] >> 7) & 1)
accel_z_axis += 2;
Serial.print(i, DEC);
Serial.print("\t");
Serial.print("joy:");
Serial.print(joy_x_axis, DEC);
Serial.print(",");
Serial.print(joy_y_axis, DEC);
Serial.print(" \t");
Serial.print("acc:");
Serial.print(accel_x_axis, DEC);
Serial.print(",");
Serial.print(accel_y_axis, DEC);
Serial.print(",");
Serial.print(accel_z_axis, DEC);
Serial.print("\t");
Serial.print("but:");
Serial.print(z_button, DEC);
Serial.print(",");
Serial.print(c_button, DEC);
Serial.print("\r\n"); // newline
i++;
}
// returns zbutton state: 1=pressed, 0=notpressed
static int nunchuck_zbutton() {
return ((nunchuck_buf[5] >> 0) & 1) ? 0 : 1; // voodoo
}
// returns zbutton state: 1=pressed, 0=notpressed
static int nunchuck_cbutton() {
return ((nunchuck_buf[5] >> 1) & 1) ? 0 : 1; // voodoo
}
// returns value of x-axis joystick
static int nunchuck_joyx() {
return nunchuck_buf[0];
}
// returns value of y-axis joystick
static int nunchuck_joyy() {
return nunchuck_buf[1];
}
// returns value of x-axis accelerometer
static int nunchuck_accelx() {
return nunchuck_buf[2]; // FIXME: this leaves out 2-bits of the data
}
// returns value of y-axis accelerometer
static int nunchuck_accely() {
return nunchuck_buf[3]; // FIXME: this leaves out 2-bits of the data
}
// returns value of z-axis accelerometer
static int nunchuck_accelz() {
return nunchuck_buf[4]; // FIXME: this leaves out 2-bits of the data
}
int loop_cnt = 0;
byte joyx, joyy, zbut, cbut, accx, accy, accz;
void _print() {
Serial.print("\tX Joy: ");
Serial.print(map(joyx, 15, 221, 0, 255));
Serial.print("\tY Joy: ");
Serial.println(map(joyy, 29, 229, 0, 255));
}
int joyx1 = 129; // 15 - 221
int joyy1 = 124; // 29 - 229
void setup() {
Serial.begin(9600);
nunchuck_setpowerpins();
nunchuck_init(); // send the initilization handshake
Serial.println("Wii Nunchuck Ready");
pinMode(3, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
//type();
}
void loop() {
if ( loop_cnt > 10 ) { // every 100 msecs get new data
loop_cnt = 0;
nunchuck_get_data();
zbut = nunchuck_zbutton();
joyx = nunchuck_joyx(); // 15 - 221
joyy = nunchuck_joyy(); // 29 - 229
_print();
}
loop_cnt++;
if (zbut == 1) {
type();
zbut = 0;
}
else {
if (joyx > (joyx1 + 20)) {
int speed1 = map(joyx - joyx1, 0, 80, 40, 255);
speed1 = constrain(speed1, 0, 255);
analogWrite(6, 0);
analogWrite(9, speed1);
}
else if (joyx < (joyx1 - 20)) {
int speed2 = map(joyx1 - joyx, 0, 90, 40, 255);
speed2 = constrain(speed2, 0, 255);
analogWrite(6, speed2);
analogWrite(9, 0);
}
else {
analogWrite(6, 0);
analogWrite(9, 0);
}
void type() {
int rltime = 200;
//digitalWrite(6, 1);//origin
//digitalWrite(9, 0);
//digitalWrite(3, 1);
//digitalWrite(5, 0);
//delay(1000);
//H==============
//digitalWrite(3, 0);//wait
//digitalWrite(5, 0);
//digitalWrite(6, 0);
//digitalWrite(9, 0);
//delay(250);
//digitalWrite(3, 0);//up
digitalWrite(5, 1);
delay(500);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(3, 1);//down
//digitalWrite(5, 0);
delay(250);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
//digitalWrite(6, 0);//right
digitalWrite(9, 1);
delay(rltime);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
//digitalWrite(3, 0);//up
digitalWrite(5, 1);
delay(250);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(3, 1);//down
//digitalWrite(5, 0);
delay(500);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
//digitalWrite(6, 0);//right
digitalWrite(9, 1);
delay(rltime);
//I========================
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(3, 0);//up
digitalWrite(5, 1);
delay(500);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(6, 0);//right
digitalWrite(9, 1);
delay(100);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(6, 1);//left
digitalWrite(9, 0);
delay(rltime);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(6, 0);//right
digitalWrite(9, 1);
delay(100);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(3, 1);//down
digitalWrite(5, 0);
delay(500);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(6, 0);//right
digitalWrite(9, 1);
delay(100);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
digitalWrite(6, 1);//left
digitalWrite(9, 0);
delay(rltime);
digitalWrite(3, 0);//wait
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(9, 0);
delay(250);
}
157) Arduino Save Your Life with The Building Collapse Monitor
Projet
COMPONENTS AND SUPPLIES
× 1
Buzzer
× 1
× 2
APPS AND ONLINE SERVICES
Blynk
Arduino IDE
Introduction
With the development of civil engineering field, we can identify a lot of
constructions everywhere. Metal structures, Concrete beams, Multi-
platform buildings are some of them. Further, most of us are used to stay
in a building or home during most times of the day. But how can we
assure that building is safe enough to stay? What if there’s a small crack or
over-inclined beam in your building? It would risk a hundreds of lives.
Earthquakes, Soil hardness, Tornadoes and many more things, could be
factors for internal cracks and the deviation of the structures or beams
from the neutral position. Most of the times we are not aware of the
situation of the surrounding structures. Maybe the place everyday we walk
in has cracked concrete beams and can collapse at anytime. But without
knowing it we are freely going inside.
As a solution for this, we need a good method to monitor concrete, wood,
metal beams of constructions where we cannot reach.
Solution
“Structure Analyzer” is a portable device which can be mounted on a
concrete beam, metal structure, slabs etc. This device measures the angle
and analyze bends where it’s mounted and send the data to mobile app
through Bluetooth.
This device uses an accelerometer/ Gyroscope to measure the angle in
x,y,z planes and flex sensor to monitor the bends. All raw data are
processed and information is sent to the mobile app.
3D Model
Circuit
Collect the following components.
Arduino 101 Board
2 X Flex sensors
2 X 10k Resistors
To reduce the number of components Arduino 101 board is used here as it
contains an accelerometer and a BLE module. Flex sensors are used to
measure the amount of bending as it changes it's resistance when bending.
The circuit is a very small one as only 2 resistors and 2 flex sensors
needed to be connected. Following diagram shows how to connect a flex
sensor to the Arduino board.
One pin of the resistor is connected to the A0 pin of the Arduino board.
Follow the same procedure to connect the second flex sensor. Use A1 pin
to connect the resistor.
But with this device, a hundreds of lives can be saved by informing the
small yet dangerous problems in constructions.
SCHEMATICS
CODE
#include <Wire.h>
/*This code file is related to the "Structure Analyzer" which
* is a device to maintain the standards and levels of many
* types of structures.
*/
#include "CurieIMU.h"
#include <BlynkSimpleCurieBLE.h>
#include <CurieBLE.h>
#include <Wire.h>
#include <EEPROM.h>
#include <SPI.h>
WidgetTerminal terminal(V2);
BLEPeripheral blePeripheral;
void values(){
for(int i=0;i<100;i++){
flx1 = analogRead(flex1); //Get raw readings from sensors
flx2 = analogRead(flex2);
x = CurieIMU.readAccelerometer(X_AXIS)/100;
y = CurieIMU.readAccelerometer(Y_AXIS)/100;
z = CurieIMU.readAccelerometer(Z_AXIS)/100;
delay(2);
}
flx1=flx1/100;
flx2=flx2/100;
x = x/100; //Get the average values of the readings
y = y/100;
z = z/100;
}
void setup(){
//pinMode(3,OUTPUT);
pinMode(flex1,INPUT);
pinMode(flex2,INPUT); //Setting the sensor pin modes
Serial.begin(9600);
blePeripheral.setLocalName("Arduino101Blynk");
blePeripheral.setDeviceName("Arduino101Blynk");
blePeripheral.setAppearance(384);
Blynk.begin(auth, blePeripheral);
blePeripheral.begin();
m_flx1 = EEPROM.read(0);
m_flx2 = EEPROM.read(1);
m_x = EEPROM.read(2); //Read pre saved sensor values from EEPROM
m_y = EEPROM.read(3);
m_z = EEPROM.read(4);
void loop(){
Blynk.run();
blePeripheral.poll();
values();
if(abs(flex1-m_flx1)>10 or abs(flex2-m_flx2)>10){
terminal.println("Over Bend");
tone(buzzer, 1000);
}
tone(buzzer, 0);
}
/*VO indicates the calibration mode. In this mode the values of sensors
* are saved in the EEPROM
*/
BLYNK_WRITE(V0){
int pinValue = param.asInt();
if (pinValue == 1){
values();
EEPROM.write(0,flx1);
EEPROM.write(1,flx2);
EEPROM.write(2,x);
EEPROM.write(3,y);
EEPROM.write(4,z);
terminal.print("Calibration Succesful");
}
}
BLYNK_WRITE(V1){
int pinValue = param.asInt();
if (pinValue == 1){
values();
terminal.print("X angle deviation- ");
terminal.print(abs(x-m_x));
terminal.println();
terminal.print("Y angle deviation- ");
terminal.print(abs(y-m_y));
terminal.println();
terminal.print("Z angle deviation- ");
terminal.print(abs(z-m_z));
terminal.println();
terminal.print("Flex 1 deviation- ");
terminal.print(abs(flx1-m_flx1));
terminal.println();
terminal.print("Flex 2 deviation- ");
terminal.print(abs(flx2-m_flx2));
terminal.println();
}
}
BLYNK_WRITE(V2){
× 1
× 4
Capacitor 100 nF
× 2
Alphanumeric LCD, 16 x 2
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
Arduino IDE
First of all, this project is aiming to entertain those who like the digital
VU (Volume Unit) meters and want to build their own version. The
project is easy to build, no deep skills required. However, for better
sound vs level visual representation you would need some soldering
skills. The input level shifter circuit and DC decouplers are required
some attention. Please bear in mind that this device is intended to use
this way with low-level audio signals. ( < 2Vrms!)
The only thing you need to create is to create the left and right level
shifter circuit and attach it to your Arduino board. Then load the
sourcecode and you are almost ready.
Please note that you might need to use separated power supply
(separated from your PC) to avoid any kind of ground loop situation
with your hifi / pa system! Since Arduino is a sensitive device and
lacks of any surge protection, you need to be cautious with ground
looping issue.
In the below video you can see it's very simple design: Of course, you
can build it with I2C LCD driver as well to reduce the required amount
of wires.
Advantages:
Easy to build
Fairly accurate representation of sound level
Very good entertaining and for learning purposes
Can be driven with low level of audio
It is easy to add / attach to existing PA or HiFi system
Disadvantages:
Linear representation of the volume level (From around -14dB to
0dB)
Not accurate enough for true representation for studio or usage
where accuracy is essential
High update rate can cause screen flickering
Low update rate can cause delay in representation
SCHEMATICS
CODE
#include <LiquidCrystal.h>
byte Bar[8] = {
B11111,
B00000,
B11111,
B11111,
B11111,
B11111,
B00000,
B11111
};
byte L[8] = {
B00111,
B01000,
B10100,
B10100,
B10100,
B10111,
B01000,
B00111
};
byte R[8] = {
B00111,
B01000,
B10110,
B10101,
B10110,
B10101,
B01000,
B00111
};
byte EndMark[8] = {
B10000,
B01000,
B00100,
B00100,
B00100,
B00100,
B01000,
B10000
};
byte EmptyBar[8] = {
B11111,
B00000,
B00000,
B00000,
B00000,
B00000,
B00000,
B11111
};
byte peakHoldChar[8] = {
B11111,
B00000,
B01110,
B01110,
B01110,
B01110,
B00000,
B11111
};
void setup()
{
lcd.begin(40, 2); //Setting up LCD. 16 chars and 2 rows
lcd.createChar(1, Bar);
lcd.createChar(2, L);
lcd.createChar(3, R);
lcd.createChar(4, EmptyBar);
lcd.createChar(5, EndMark);
lcd.createChar(6, peakHoldChar);
delay(500);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Loading...");
delay(50);
}
delay(500);
lcd.clear();
decayTime = millis();
}
void loop()
{
actualMillis = millis();
indexL++;
indexR++;
volR = right / 3;
if(volR > 14)
{
volR = 14;
}
volR = rightAvg;
}
else if (volR > (rightAvg + 2))
{
volR = (rightAvg + 2);
rightAvg = volR;
}
else
{
rightAvg = volR;
}
volL = left / 3;
volL = leftAvg;
}
else if (volL > (leftAvg + 2))
{
volL = (leftAvg + 2);
leftAvg = volL;
}
else
{
leftAvg = volL;
}
× 1
Photo resistor
× 3
Arduino UNO & Genuino UNO
× 1
NECESSARY TOOLS AND MACHINES
3D Printer (generic)
APPS AND ONLINE SERVICES
Arduino IDE
openScad
CODE
#define redLED 3
#define greenLED 6
#define blueLED 5
/* Note the colours of the sensors below correspond to the wire colours used in my build*/
#define yellowSensor 0
#define purpleSensor 1
#define pinkSensor 2
struct SensorReading{
int pink;
int yellow;
int purple;
};
void setup() {
// put your setup code here, to run once:
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(blueLED, OUTPUT);
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, HIGH);
digitalWrite(blueLED, HIGH);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
SensorReading s;
char buffer[200];
redOn();
delay(delayTime);
readSensors(s);
greenOn();
delay(delayTime);
readSensors(s);
sprintf(buffer, "Green %d %d %d",s.pink, s.purple, s.yellow);
Serial.println(buffer);
blueOn();
delay(delayTime);
readSensors(s);
whiteOn();
delay(delayTime);
readSensors(s);
delay(5000);
}
void redOn(){
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
digitalWrite(blueLED, HIGH);}
void greenOn(){
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, HIGH);}
void blueOn(){
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, HIGH);
digitalWrite(blueLED, LOW);}
void whiteOn(){
digitalWrite(redLED, LOW);
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, LOW);}
void readSensors(SensorReading& s ){
s.pink = analogRead(pinkSensor);
s.purple = analogRead(purpleSensor);
s.yellow= analogRead(yellowSensor);
}
160) Arduino Serial Pong Projet
× 1
Single Turn Potentiometer- 10k
ohms
× 2
× 1
Breadboard (generic)
× 1
Capacitor 100 µF
SCHEMATICS
CODE
Python code
# Imports
import serial
import curses
# Constants
HEIGHT = 24
WIDTH = 80
BALL_CHAR = '*'
PADDLE_CHAR = '|'
PADDLE_HEIGHT = 4
GAME_SPEED = 100
# Classes
class Timer:
# Functions
def map(val, in_min, in_max, out_min, out_max):
return int((val - in_min) * (out_max - out_min) / (in_max - in_min) +
out_min)
def read_serial(device):
#Read serial data
raw_line = device.readline()
line = str(raw_line)
line = line[2:] #Remove the unicode characters
line = line[:-5] #Remove the cariage return and newline from the end of
the string
data = line.split(" ")
#Convert parsed strings into integers
try:
time = int(data[0])
p1_pot = int(data[1])
p2_pot = int(data[2])
return time, p1_pot, p2_pot, True
except:
return -1, -1, -1, False
# Check to see if the paddle does not pass through the top
if left_paddle_y <= 0:
left_paddle_y = 0
# Check to see if the paddles do not pass through the bottom
if left_paddle_y >= (HEIGHT - PADDLE_HEIGHT):
left_paddle_y = (HEIGHT - PADDLE_HEIGHT)
if right_paddle_y >= (HEIGHT - PADDLE_HEIGHT):
right_paddle_y = (HEIGHT - PADDLE_HEIGHT)
curses.endwin()
print(loss_message)
Arduino code
int player1_val;
int player2_val;
const int player1_pot = A0;
const int player2_pot = A1;
void setup() {
pinMode(player1_pot, INPUT);
pinMode(player2_pot, INPUT);
Serial.begin(9600);
}
void loop() {
player1_val = analogRead(player1_pot);
player2_val = analogRead(player2_pot);
Serial.print(millis());
Serial.print(" ");
Serial.print(player1_val);
Serial.print(" ");
Serial.println(player2_val);
× 1
× 4
SCHEMATICS
CODE
Servo Servo_3;
Servo Gripper;
int array_index=0;
char incoming = 0;
int action_pos;
int action_servo;
void setup() {
Serial.begin(9600); //Serial Monitor for Debugging
Servo_3.attach(9);
Gripper.attach(10);
Servo_3.write(90);
Gripper.write(90);
P_S3_pos = S3_pos;
P_G_pos = G_pos;
C_S0_pos = S0_pos; //Saved the previous value to check if the POT has been turned
}
if (C_S1_pos != S1_pos)
{
saved_data[array_index] = S1_pos + 1000; //1000 is added for 1st servo motor as
differentiator
array_index++;
}
C_S1_pos = S1_pos;
}
if (P_S3_pos == S3_pos)
{
Servo_3.write(S3_pos);
if (C_S3_pos != S3_pos)
{
saved_data[array_index] = S3_pos + 3000; //3000 is added for 3rd servo motor as
differentiater
array_index++;
}
C_S3_pos = S3_pos;
}
if (P_G_pos == G_pos)
{
Gripper.write(G_pos);
if (C_G_pos != G_pos)
{
saved_data[array_index] = G_pos + 4000; //4000 is added for 4th servo motor as
differentiator
array_index++;
}
C_G_pos = G_pos;
}
void Play() //Functon to play the recorded movements on the Robotic ARM
{
for (int Play_action=0; Play_action<array_index; Play_action++) //Navigate through every
saved element in the array
{
action_servo = saved_data[Play_action] / 1000; //The fist character of the array element is
split for knowing the servo number
action_pos = saved_data[Play_action] % 1000; //The last three characters of the array
element is split to know the servo postion
delay(50);
}
}
void loop() {
× 1
Adafruit MLX90614
× 1
Breadboard (generic)
8x2 cm
× 2
16 MHz Crystal
× 1
Slide Switch
× 1
Buzzer
× 1
USB A Connector
× 1
Idea
This is a story about making an pocket carry-able USB stick like IR
Thermometer made using Arduino programming and some other stuff.
The device will also have stopwatch function, kitchen timer and inactivity
tracker function.
IR Thermometer is an IR radiation-based temperature sensing device
which allows for the measurement of the average temperature of a surface
it's facing - most probably with Wien's displacement law or Stefan–
Boltzmann law from highs school physics.
A stopwatch is a basic time measurement device used in sports, scientific
experiment, etc. to measure lapsed time. Today, hardware stopwatches
(the analog type) are kind of extinct and replaced by a so-called
smartphone app. A kitchen timer is a device that alerts cook by buzzing an
alarm set such that something being cooked needs checking.
An inactivity tracker is a periodic timer that alerts a person to move after
every X amount of time. This helps one to get a minute break from idle
state and practice healthy life.
Hardware Description
The finished device looks like this:
Device Top
Bottom
Here is a nice description picture of the thing:
Description
Making The Thing!
Step 1: Gather all the ingredients, imagine and make a mental map of what
goes where!
Take measurements, make necessary holes, place components and solder.
Tops
bottoms
Step 2: Use heat shrink tube and 0 Ohm resistors to interconnect things, 1k
resistors on display segment pins, and solder according to the schematic.
Internal Layer
Step 3: Interconnect both layers.
Room Temperature
Note!
The IR Sensor has 90 degree field of view, which means it is not
measuring the temperature of the point where the laser pointer is
shining, rather it is averaging the temperature of objects on its view
plane.
The system runs with 4.2 volt fully charged Li-Po battery and should
operate with at least 3.7 volts without worries.
Laser is directly driven from MCU pin and buzzer is driven through
transistor.
One of the digital pin powers the 3.3V regulator and the IR sensor.
11 pins are required to direct drive the 7 segment display.
The device is rechargeable from the USB port of PC/Laptop. From
the USB, 5 volts are reduced to 4.2 with a diode and a resistor in
series - simple charging circuit where the blue LED glows while
charging.
The program can be updated through the 3 blue male header pins
(Reset,RX,TX) connected through the external USB-FTDI (serial)
device, which is detected as Adruino in Arduino IDE.
SCHEMATICS
CODE
// Thanks to Lady Ada and Read for MLX90614 and Sevseg library !
#include "SevSeg.h"
#include <Wire.h>
#include <Adafruit_MLX90614.h>
#define PIN_PWR_SENESOR 13
#define PIN_PWR_LASER A0
#define PIN_PRESS_SWITCH1 2
#define PIN_PRESS_SWITCH2 3
#define PIN_BUZZER_ALERM 4
void setup() {
pinMode(PIN_PRESS_SWITCH1, INPUT_PULLUP);
attachInterrupt(0, SW1, FALLING);// Interrupt for Swithc 1
pinMode(PIN_PRESS_SWITCH2, INPUT_PULLUP);
attachInterrupt(1, SW2, FALLING);// Interrupt for Swithc 2
pinMode(PIN_PWR_SENESOR, OUTPUT);
pinMode(PIN_PWR_LASER, OUTPUT);
pinMode(PIN_BUZZER_ALERM, OUTPUT);
digitalWrite(PIN_PWR_SENESOR,HIGH); // powers the regulator + IR
sensor
digitalWrite(PIN_PWR_LASER,LOW);
digitalWrite(PIN_BUZZER_ALERM,LOW);
byte numDigits = 3;
byte digitPins[] = {A1, A2, A3};
byte segmentPins[] = {11, 9, 7, 6, 5, 10, 8, 12};
bool resistorsOnSegments = false; // Use 'true' if on digit pins
byte hardwareConfig = COMMON_ANODE; // See README.md for
options
}
sevseg.setNumber(T_obj, 1);
}
if(test==0)
{
// T_amb = mlx.readAmbientTempC();
T_obj = mlx.readObjectTempC();
sevseg.setNumber(T_obj, 0);
sevseg.refreshDisplay();
sevseg.refreshDisplay();
sevseg.refreshDisplay();
sevseg.refreshDisplay(); // Must run repeatedly
}
if (test==1)
{
T_amb = mlx.readAmbientTempC();
// T_amb=T_amb*10;
sevseg.setNumber(T_amb, 1);
sevseg.refreshDisplay();
sevseg.refreshDisplay();
sevseg.refreshDisplay();
sevseg.refreshDisplay(); // Must run repeatedly
}
}
void SW1()
{
test=1;
digitalWrite(PIN_PWR_Laser,HIGH);
}
void SW2()
{
test=0;
digitalWrite(PIN_PWR_Laser,HIGH);}
× 1
× 1
× 1
Diode 1N4148
× 1
Capacitor 10 µF
× 1
× 2
// serial connection
// RX = Icom radio to Arduino : to pin 2 via resistor 4k7
// TX = Arduino to Icom radio : to pin 7 via diode 1N4148, with pull up 10k to Vcc (5V)
on tip of 3.5 mm connector
int readCounter; // counts the number of bytes received from the radio
int sMeterVal1; // stores the most significant BCD byte containing signal info.
int sMeterVal2; // stores the least significant BCD byte containing signal info.
int sMeterOut = 11; // External analog S-meter connected to pin 11.
//---------------------------------------------------------------------------------------------
void setup()
{
pinMode(13, OUTPUT); digitalWrite(13, LOW); // force LED (pin 13) to turn off.
mySerial.begin(BAUD_RATE);
mySerial.listen(); // only one port can be made to listen with software serial
// see reference https://www.arduino.cc/en/Reference/SoftwareSerialListen
while (mySerial.available()) mySerial.read(); // clean buffer
}
//---------------------------------------------------------------------------------------------
void loop()
{
// read and display S-meter value
mySerial.flush();
if (nbChar > 0) {
for (int readCounter = 0; readCounter < nbChar ; readCounter++) {
byte byteRead = mySerial.read();
if (readCounter == 6){
sMeterVal1 = ( (byteRead/16*10) + (byteRead%16) ); // First byte: convert from BCD to
decimal.
}
if (readCounter == 7){
sMeterVal2 = ( (byteRead/16*10) + (byteRead%16) ); // Second byte: convert from BCD to
decimal.
× 1
MicroSD Module
× 1
2S LiFe Battery
× 1
2S LiPo Battery
× 1
Pliers
Wire Stripper
APPS AND ONLINE SERVICES
Arduino IDE
Audacity
Original bike had forward/reverse control and 2 push buttons for pre-
recorded audio playback (honk the horn and bike start sound effect).
I got rid of all original electronics including speaker, lead-acid battery
and buttons (including the 3 position rocker switch). I kept the 6V DC
motor and the original powertrain wire harness (had to do some rewire
though).
With some planning and creativity I ended up with the following
features:
new ON/OFF switch for electronics automatically triggers startup
sound (no more button for that)
rear proximity sensor automatically enabled when reverse is engaged
police siren with 3 modes (lights only, quick siren, loop mode)
horn (or ability to play other sound effects/music)
bottom led strip for "fast and furious" mode
Having all features in mind it was time to design the PCB and order
required parts. A mono audio amplifier was needed to drive the new
speaker. For audio file storage we are using a MicroSD card module.
The police LED lightning system comes from RC car toys. It's
supposed to work with servo protocol but after some tinkering I could
manage to make it work with standard Arduino functions.
For the PCB I found 10cm x 5cm a perfect fit for our bike electronics
bay. All connections to external modules and wires are made thru pin
headers (males or females, straight or right angle). Blue wires are
external jumpers in the top of the board while copper wires are
soldered track on the bottom.
Powertrain rewired
Many different connectors were used to make custom cables for all
necessary wiring. The police lighting system, cooling fan and the LED
strip have JST plugs. The power switch has a JST (input) and a servo
connector (output). My batteries have XT60 and JST plugs. We also
need a female USB to drive power to the Arduino board. Please see the
parts list for all parts I have used.
under the seat bay
Bear in mind that our DC motor is 6V only but we are powering it with
a 6,6V (nominal voltage) battery that can reach more than 7V when
fully charged. The extra power can make things very hot at our engine
so I installed a heatsink with a 5V fan. The fact it's 5V is the reason
why the fan is connected to the electronics power line and not the
powertrain. You can see the fan in the middle left of the picture above.
Initially I considered to power the electronics with a 9V battery but
adding the fan to this power line depleted the battery in a matter of a
few minutes. That's why I replaced it later for a 2S Lipo (properly
protected with a lipo bag and a low voltage alarm).
Electronics bay
Electronics bay is located under the bike, it's a little tight in there but
with patience you can fit everything in place. Speaker is installed in the
bay cover (same place as the original speaker). Bay cover is shown
resting in the left of the picture above.
Top view
From top to bottom: police lightning system, proximity sensor,
ON/OFF switch for electronics power line
SCHEMATICS
CODE
/**
* Arduino open source project for battery operated electric bike
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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.
*/
#define DISABLE_SPEAKER2
//#define DEBUG
#include <SD.h>
#include <TMRpcm.h>
#include <SPI.h>
#define PIN_SDCARD A5
#define PIN_SW_GIROFLEX 3 // a
#define PIN_SW_REVERSE 4 // b
#define PIN_SW_SIREN 5 // c
#define PIN_SW_HONK 6 // d
#define PIN_SPEAKER 9 // DON'T TOUCH
#define PIN_SENSOR_ECHO 10
#define PIN_SENSOR_TRIGGER 11
#define PIN_GIROFLEX 12
#ifdef DEBUG
#define DPRINT(x) Serial.print(x)
#define DPRINTLN(x) Serial.println(x)
#else
#define DPRINT(x)
#define DPRINTLN(x)
#endif
void setup() {
pinMode(PIN_SW_GIROFLEX, INPUT_PULLUP);
pinMode(PIN_SW_REVERSE, INPUT_PULLUP);
pinMode(PIN_SW_SIREN, INPUT_PULLUP);
pinMode(PIN_SW_HONK, INPUT_PULLUP);
pinMode(PIN_SENSOR_ECHO, INPUT);
pinMode(PIN_SENSOR_TRIGGER, OUTPUT);
digitalWrite(PIN_SENSOR_TRIGGER, LOW);
pinMode(PIN_GIROFLEX, OUTPUT);
digitalWrite(PIN_GIROFLEX, LOW);
pinMode(PIN_SPEAKER, OUTPUT);
pinMode(PIN_SDCARD, OUTPUT);
#ifdef DEBUG
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Arduino Micro
}
#endif
audio.speakerPin = PIN_SPEAKER;
audio.setVolume(4);
if (!SD.begin(PIN_SDCARD)) {
DPRINTLN("SD fail");
tone(PIN_SPEAKER, 392);
delay(250);
tone(PIN_SPEAKER, 262);
delay(500);
noTone(PIN_SPEAKER);
} else {
audio.play("start.wav");
while (audio.isPlaying());
audio.disable();
}
DPRINTLN("done setup");
}
void loop() {
int state = 0;
state += debounce(PIN_SW_GIROFLEX) << 3;
state += debounce(PIN_SW_REVERSE) << 2;
state += debounce(PIN_SW_SIREN) << 1;
state += debounce(PIN_SW_HONK);
if (last_state != state) {
DPRINT("state: ");
DPRINTLN(state);
}
last_state = state;
switch (state) {
case B0000:
giroflex(0);
reset_siren();
audio.disable();
noTone(PIN_SPEAKER);
break;
case B0011:
case B0010:
case B1010:
if (count_siren < 10) {
count_siren++;
DPRINT("siren button hold :");
DPRINTLN(count_siren);
} else {
giroflex(2);
if (!audio.isPlaying())
audio.play("s2.wav");
}
break;
case B0101:
case B0100:
case B0110:
case B0111:
giroflex(0);
case B1100:
case B1101:
case B1110:
case B1111:
count_siren = 0;
audio.disable();
parking();
break;
case B1000:
reset_siren();
audio.disable();
noTone(PIN_SPEAKER);
giroflex(5);
break;
case B0001:
giroflex(0);
reset_siren();
if (!audio.isPlaying()) {
audio.play("honk.wav");
while (audio.isPlaying());
}
break;
case B1001:
reset_siren();
case B1011:
giroflex(5);
if (!audio.isPlaying()) {
audio.play("honk.wav");
while (audio.isPlaying());
}
break;
}
}
void reset_siren() {
if (count_siren > 0 and count_siren < 10) {
giroflex(3);
audio.disable();
audio.play("s1.wav");
while (audio.isPlaying());
giroflex(0);
}
count_siren = 0;
}
void parking() {
DPRINTLN("parking");
pinMode(PIN_SPEAKER, OUTPUT);
noTone(PIN_SPEAKER);
tone(PIN_SPEAKER, 440, 100);
delay(500);
noTone(PIN_SPEAKER);
DPRINTLN("no parking");
}
if (giroflex_mode == target_mode)
return;
/*
* audio can mess with timers so we wait for it to finish
*/
while (audio.isPlaying());
int i;
for (i = giroflex_mode; i != target_mode; i = (i + 1) % 7) {
digitalWrite(PIN_GIROFLEX, HIGH);
delayMicroseconds(900);
digitalWrite(PIN_GIROFLEX, LOW);
delay(2);
digitalWrite(PIN_GIROFLEX, HIGH);
delayMicroseconds(2000);
digitalWrite(PIN_GIROFLEX, LOW);
delay(2);
digitalWrite(PIN_GIROFLEX, HIGH);
delayMicroseconds(900);
digitalWrite(PIN_GIROFLEX, LOW);
delay(2);
digitalWrite(PIN_GIROFLEX, HIGH);
delayMicroseconds(2000);
digitalWrite(PIN_GIROFLEX, LOW);
delay(2);
}
giroflex_mode = i;
}
165) Arduino Pluto Bluetooth RC Car Projet
COMPONENTS AND SUPPLIES
× 1
DC Motor, 12 V
× 2
Breadboard (generic)
× 1
× 1
× 1
× 2
9V battery (generic)
to power the Arduino board
× 1
AA Batteries
To power the DC motor
× 8
Battery Holder, AA x 8
× 1
NECESSARY TOOLS AND MACHINES
3D Printer (generic)
Ultimaker Cura
SolidWorks 2019/20
CODE
char t;
#include <Wire.h> //include the required libraries
#include <MPU6050.h> //include MPU6050 libraries
#include <Servo.h>
MPU6050 sensor ; //create an instance of the MPU6050 named sensor
Servo sg90y;
Servo sg90x;
int servo_pinX = 2;
int servo_pinY = 3;
int motor1A = 4;
int motor1B = 5;
int motor2A = 6;
int motor2B = 7;
void setup() {
pinMode(servo_pinX, OUTPUT);
pinMode(servo_pinY, OUTPUT);
pinMode(motor1A, OUTPUT);
pinMode(motor1B, OUTPUT);
pinMode(motor2A, OUTPUT);
pinMode(motor2B, OUTPUT);
pinMode(A5, INPUT);
pinMode(A4, INPUT);
sg90x.attach ( servo_pinX );
sg90y.attach ( servo_pinY );
Wire.begin ( ); //begins the trasmission with MPU6050
sensor.initialize ( ); //initialise the sensor
Serial.begin(9600);
delay(400);
}
void forward() {
digitalWrite(motor1A, LOW);
digitalWrite(motor1B, HIGH);
digitalWrite(motor2A, LOW);
digitalWrite(motor2B, HIGH);
}
void reverse() {
digitalWrite(motor1A, HIGH);
digitalWrite(motor1B, LOW);
digitalWrite(motor2B, LOW);
digitalWrite(motor2A, HIGH);
}
void right() {
digitalWrite(motor1B, HIGH);
digitalWrite(motor1A, LOW);
digitalWrite(motor2B, LOW);
digitalWrite(motor2A, HIGH);
}
void left() {
digitalWrite(motor1B, LOW);
digitalWrite(motor1A, HIGH);
digitalWrite(motor2B, HIGH);
digitalWrite(motor2A, LOW);
}
void nomove() {
digitalWrite(motor1B, LOW);
digitalWrite(motor1A, LOW);
digitalWrite(motor2B, LOW);
digitalWrite(motor2A, LOW);
}
void loop() {
sensor.getMotion6 (&ax, &ay, &az, &gx, &gy, &gz); //read 6 values into 6 variables
ay = map (ay, -17000, 17000, 0, 180) ; // change the range of the ay value from
-17000/17000 to 0/180
sg90y.write (ay);
ax = map (ax, -17000, 17000, 0, 180) ; // change the range of the ax value from
-17000/17000 to 0/180
sg90x.write (ax);
if (Serial.available()) {
t = Serial.read();
Serial.println(t); //Read the incoming data and store it into variable t
if (t == 'F') {
forward();
}
else if (t == 'B') {
reverse();
}
else if (t == 'L') {
left();
}
else if (t == 'R') {
right();
}
else if (t == 'S') {
nomove();
}
}
}
166) Arduino Solar Tracker Projet
× 1
LDR, 5 Mohm
× 4
× 4
× 1
× 2
Parallax PLX-DAQ
Fig. 3. Electronic circuit of the solar tracker with manual and automatic
modes
The LDR sensor circuitry is designed as a voltage divider circuit. The
variation in the light intensity is proportional to the variation of the divider
output voltage. The top of the potential divider is 5 V, the ground is at 0
V, and the output of the voltage divider is connected to an analog input
(A0 for instance) of the microcontroller. Subsequently, the Analog to
Digital Converter(ADC) of the microcontroller converts the analog value
read by A0 into a digital value between 0 and 1023 because the ADC is
coded in 10 bits, and according to this value, it is possible to know the
level of light. The value of resistors used in voltage dividers is 330 Ω.
Two 180 degrees servomotors are used. A servomotor (MG996R) to
control the solar tracker according to the vertical axis, which is the left-
right servomotor. And a micro servo motor (SG90) to control the solar
tracker according to the horizontal axis, which is the up-down servomotor.
The advantage of the servomotor is that we can control its stop, run, the
direction of rotation and speed using a single low current wire connected
directly to an output of the microcontroller without needing any drivers.
The used servo motors are controlled by the Arduino UNO board via 3-
wire electrical cable as shown in Fig. 3, two wires for supply and one wire
for PWM to control its positions.
The embedded software design
The embedded software is the piece that will be embedded in the hardware
(Arduino Uno) to control and monitor the solar tracker test bench. The
embedded software is designed to cover the following requirements:
1. The test bench has two modes: manual and automatic. A pushbutton is
connected to pin 12 to switch between the two modes.
2. If the manual mode is active, the potentiometer can control servomotors
either from east to west for left-right motor or from south to north for the
up-down motor. A push-button is connected to pin 11 to switch the
potentiometer between the two motors, either it controls the left-right
servomotor or up-down servo motor.
3. If the automatic mode is active, the algorithm presented in Fig. 4 will be
executed. The latter uses the analog values returned by LDR sensors. For
instance, considering azimuth or vertical axis, the average values from two
right LDRs and two left LDRs are compared and if the left set of LDRs
receives more light, the solar tracker will move in that direction through
the left-right servomotor. The latter will continue to rotate until the
difference result is in the range [−10, 10]. This range is used to stabilize
the controller and once the solar tracker is perpendicular to the sun, no
further control is made. On the other hand, if the right set of LDRs receive
more light, the solar tracker moves in that direction through the left-right
servomotor and will continue to rotate until the difference result is in the
range [−10, 10]. The same way is used for the elevation axis. Moreover,
we also determined the average radiation between the four LDR sensors
and if this value is less than a little value (8: a value which has been
adjusted and tested practically and is returned when the irradiation is null).
That is to say, the night has come. In this case, the solar tracker must
return to the sun’s rising position. For example, if the sun’s rising position
can be reached by setting 0 degrees in the left-right servomotor, and 30
degrees in the up-down servomotor. This can easily be done through the C
function “servox. write(angle)” provided by Arduino IDE.
4. The PV voltage acquired through the analog pin A5 must be treated and
used to compute the PV current and power. Then all these data and the
actual mode must be sent through a USB cable to the computer and then
present them in MS Excel.
Fig. 4. The algorithm for automatic mode of the solar tracker
The PLX-DAQ Excel Macro is used for data acquisition from the Arduino
microcontroller to an Excel Spreadsheet. We only need to download it.
After installation, a folder named "PLX-DAQ" will automatically be
created on the PC in which a shortcut named "PLX-DAQ Spreadsheet" is
inside. Then, to establish the communication between the board and Excel,
we just need to open the Spreadsheet and defining the connections settings
(Baud rate and port) in the PLX-DAQ window (Fig. 5). Thereafter, after
clicking on "connect" the output data will be collected and displayed in
real-time on the Excel Spreadsheet
SCHEMATICS
CODE
void setup()
{
Serial.begin(9600); //serial connection setup //opens serial port, sets
data rate to 9600 bps
Serial.println("CLEARDATA"); //clear all data that’s been place in already
Serial.println("LABEL,t,voltage,current,power,Mode"); //define the column headings
(PLX-DAQ command)
void loop()
{
// pv_power();
char Mode;
float volt = analogRead(A5)*5.0/1023;
float voltage = 2*volt; // Volt=(R1/R1+R2)*Voltage / R1=R2=10Ohms =>
voltage=2*volt)
float current = voltage/20; // I=voltage/(R1+R2)
float power = voltage*current;
Serial.print("DATA,TIME,"); // PLX-DAQ command
Serial.print(voltage); //send the voltage to serial port
Serial.print(",");
Serial.print(current); //send the current to serial port
Serial.print(",");
Serial.print(power); //send the power to serial port
Serial.print(",");
// Serial.println(Mode);
buttonState1 = digitalRead(12);
if (buttonState1 != prevButtonState1) {
if (buttonState1 == HIGH) {
//Change mode and ligh up the correct indicator
if (mode == 1) {
mode = 0;
} else {
mode = 1;
}
}
}
prevButtonState1 = buttonState1;
delay(50); // Wait for 50 millisecond(s)
if (mode == 0) {
Mode='M';
Serial.println(Mode); //send Mode "Manual" to serial port
manualsolartracker();
} else { // mode automatic
Mode = 'A';
Serial.println(Mode);
automaticsolartracker(); //send Mode "Automatic" to serial port
}
}
void automaticsolartracker(){
// calculating average
int avgtop = (topr + topl) / 2; //average of top LDRs
int avgbot = (botr + botl) / 2; //average of bottom LDRs
int avgleft = (topl + botl) / 2; //average of left LDRs
int avgright = (topr + botr) / 2; //average of right LDRs
void manualsolartracker(){
buttonState2 = digitalRead(13);
if (buttonState2 != prevButtonState2) {
if (buttonState2 == HIGH) {
//Change mode and ligh up the correct indicator
if (axe == 1) {
axe = 0;
} else {
axe = 1;
}
}
}
prevButtonState2 = buttonState2;
delay(50); // Wait for 50 millisecond(s)
if (axe == 0) { //control right-left movement
servo_rightleft.write(map(analogRead(A4), 0, 1023, 0, 180));
} else { // //control up-down movement
servo_updown.write(map(analogRead(A4), 0, 1023, 0, 180));
}
}
Arduino Nano R3
× 1
× 1
CODE
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
#define Today
RTC_DS1307 rtc;
void setup () {
while (!Serial); // for Leonardo/Micro/Zero
Serial.begin(9600);
if (! rtc.begin()) {
while (1);
}
if (! rtc.isrunning()) {
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
// This line sets the RTC with an explicit date & time, for example to set
// January 21, 2014 at 3am you would call:
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
}
Wire.begin();
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C
(for the 128x32)
// init done
//Clear the buffer.
display.clearDisplay();
text();
}
void text(void) {
display.setTextSize(1);
display.setTextColor(WHITE);
}
void Display () {
display.clearDisplay();
DateTime now = rtc.now();
display.print(daysOfTheWeek[now.dayOfTheWeek()]);
//set date
display.setCursor(0,12);
int mo=now.month();
if ((mo>0)&&(mo<2)){
display.print("January ");
}
if ((mo>1)&&(mo<3)){
display.print("February ");
}
if ((mo>2)&&(mo<4)){
display.print("March ");
}
if ((mo>3)&&(mo<5)){
display.print("April ");
}
if ((mo>4)&&(mo<6)){
display.print("May ");
}
if ((mo>5)&&(mo<7)){
display.print("June ");
}
if ((mo>6)&&(mo<8)){
display.print("July ");
}
if ((mo>7)&&(mo<9)){
display.print("August ");
}
if ((mo>8)&&(mo<10)){
display.print("September ");
}
if ((mo>9)&&(mo<11)){
display.print("October ");
}
if ((mo>10)&&(mo<12)){
display.print("November ");
}
if ((mo>11)&&(mo<13)){
display.print("December ");
}
display.print(", ");
}
if ((hr>11)&&(hr<13)){
display.print("Twelve ");
}
// set minute
int m=now.minute();
if ((m>0)&&(m<2)){
display.print("O-One");
}
if ((m>1)&&(m<3)){
display.print("O-Two");
}
if ((m>2)&&(m<4)){
display.print("O-Three");
}
if ((m>3)&&(m<5)){
display.print("O-Four");
}
if ((m>4)&&(m<6)){
display.print("O-Five");
}
if ((m>5)&&(m<7)){
display.print("O-Six");
}
if ((m>6)&&(m<8)){
display.print("O-Seven");
}
if ((m>7)&&(m<9)){
display.print("O-Eight");
}
if ((m>8)&&(m<10)){
display.print("O-Nine");
}
//teens
if ((m>9)&&(m<11)){
display.print("Ten");
}
if ((m>10)&&(m<12)){
display.print("Eleven");
}
if ((m>11)&&(m<13)){
display.print("Twelve");
}
if ((m>12)&&(m<14)){
display.print("Thirteen");
}
if ((m>13)&&(m<15)){
display.print("Fourteen");
}
if ((m>14)&&(m<16)){
Serial.print("Fifteen");
}
if ((m>15)&&(m<17)){
display.print("Sixteen");
}
if ((m>16)&&(m<18)){
display.print("Seventeen");
}
if ((m>17)&&(m<19)){
display.print("Eighteen");
}
if ((m>18)&&(m<20)){
display.print("Ninteen");
}
//twenty
if ((m>19)&&(m<21)){
display.print("Twenty");
}
if ((m>20)&&(m<22)){
Serial.print("Twenty-One");
}
if ((m>21)&&(m<23)){
display.print("Twenty-Two");
}
if ((m>22)&&(m<24)){
display.print("Twenty-Three");
}
if ((m>23)&&(m<25)){
Serial.print("Twenty-Four");
}
if ((m>24)&&(m<26)){
display.print("Twenty-Five");
}
if ((m>25)&&(m<27)){
display.print("Twenty-Six");
}
if ((m>26)&&(m<28)){
display.print("Twenty-Seven");
}
if ((m>27)&&(m<29)){
Serial.print("Twenty-Eight");
}
if ((m>28)&&(m<30)){
display.print("Twenty-Nine");
}
// thirty
if ((m>29)&&(m<31)){
display.print("Thirty");
}
if ((m>30)&&(m<32)){
display.print("Thirty-One");
}
if ((m>31)&&(m<33)){
display.print("Thirty-Two");
}
if ((m>32)&&(m<34)){
display.print("Thirty-Three");
if ((m>33)&&(m<35)){
display.print("Thirty-Four");
if ((m>34)&&(m<36)){
display.print("Thirty-Five");
}
if ((m>35)&&(m<37)){
display.print("Thirty-Six");
}
if ((m>36)&&(m<38)){
display.print("Thirty-Seven");
if ((m>37)&&(m<39)){
display.print("Thirty-Eight");
}
if ((m>38)&&(m<40)){
display.print("Thirty-Nine");
}
//forty
if ((m>39)&&(m<41)){
display.print("Forty");
}
if ((m>40)&&(m<42)){
display.print("Forty-One");
}
if ((m>41)&&(m<43)){
display.print("Forty-Two");
}
if ((m>42)&&(m<44)){
display.print("Forty-Three");
}
if ((m>43)&&(m<45)){
display.print("Forty-Four");
}
if ((m>44)&&(m<46)){
display.print("Forty-Five");
}
if ((m>45)&&(m<47)){
display.print("Forty-Six");
}
if ((m>46)&&(m<48)){
display.print("Forty-Seven");
}
if ((m>47)&&(m<49)){
display.print("Forty-Eight");
}
if ((m>48)&&(m<50)){
display.print("Forty-Nine");
}
//fifty
if ((m>49)&&(m<51)){
display.print("Fifty");
}
if ((m>50)&&(m<52)){
display.print("Fifty-One");
}
if ((m>51)&&(m<53)){
display.print("Fifty-Two");
}
if ((m>52)&&(m<54)){
display.print("Fifty-Three");
}
if ((m>53)&&(m<55)){
display.print("Fifty-Four");
}
if ((m>54)&&(m<56)){
Serial.print("Fifty-Five");
}
if ((m>55)&&(m<57)){
display.print("Fifty-Six");
}
if ((m>56)&&(m<58)){
display.print("Fifty-Seven");
}
if ((m>57)&&(m<59)){
display.print("Fifty-Eight");
}
if ((m>58)){
display.print("Fifty-Nine");
}
if (m<1){
display.print("O'Clock");
}
display.print(" ");
int tm=now.hour();
if (tm<13){
display.print("AM");
}
if (tm>12){
display.print("PM");
}
display.display();
}
void loop()
{
Display();
delay(0);
}
× 1
× 4
LED (generic)
× 4
Breadboard (generic)
× 1
× 1
Resistor 1k ohm
× 4
SCHEMATICS
CODE
#include <EEPROM.h>
void Init()
{
IsProgrammingMode = false;
isTheEnd = false;
progress = 0;
currentCode = 0;
void SaveSettings()
{
EEPROM.write(1,TASK_DIFFICULTY);
}
boolean ReadSensor(byte sensorId)
{
int val = analogRead(sensors[sensorId]);
//Serial.print(" SENSOR [");
//Serial.print(sensorId);
//Serial.print("]=");
//Serial.println(val);
return val>MIN_SENSOR_VALUE;
}
// reading
byte GetCurrentCode()
{
byte res=0;
for(int i=1; i<5; i++)
{
if(ReadSensor(i-1))
res+=i;
}
if(res>4)
res=0;
return res;
}
void CheckProgrammingMode()
{
if(digitalRead(programmingPort)==HIGH)
{
if(IsProgrammingMode)
{
// Stop the programming
IsProgrammingMode=false;
SetSensorLEDs(LOW);
SaveSettings();
Init();
ShowProgress(0);
CloseDoor();
}else
{
IsProgrammingMode=true;
SetSensorLEDs(HIGH);
// TODO: Зажечь все светодиоды и подсветить текущий уровень сложности
}
delay(1000);
}
}
}
void CorrectMelody()
{
for (int thisNote = 0; thisNote < 1; thisNote++) {
int noteDuration = 1000/noteDurations1[thisNote];
tone(tonePort, melody1[thisNote],noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(tonePort);
}
}
void WrongMelody()
{
for (int thisNote = 0; thisNote < 2; thisNote++) {
int noteDuration = 1000/noteDurations2[thisNote];
tone(tonePort, melody2[thisNote],noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(tonePort);
}
}
void OpenDoor()
{
digitalWrite(relayPort, HIGH);
}
void CloseDoor()
{
digitalWrite(relayPort, LOW);
}
void setup() {
//Serial.begin(9600);
Init();
OpenDoor();
SetSensorLEDs(HIGH);
ShowProgress(16);
delay(500);
SetSensorLEDs(LOW);
ShowProgress(0);
CloseDoor();
//Serial.println("--- INIT COMPLETE ---");
}
void loop() {
CheckProgrammingMode();
//Serial.print("IsProgramming = ");
//Serial.println(IsProgrammingMode);
if(IsProgrammingMode)
{
//Serial.print("TASK_DIFFICULTY = ");
//Serial.println(TASK_DIFFICULTY);
if(code==1||code==2)
{
if(TASK_DIFFICULTY<MAX_TASK_DIFFICULTY)
{
TASK_DIFFICULTY+=1;
//ShowProgress(TASK_DIFFICULTY);
SimpleMelody(0);
delay(200);
}
}
if(code==3||code==4)
{
if(TASK_DIFFICULTY>MIN_TASK_DIFFICULTY)
{
TASK_DIFFICULTY-=1;
//ShowProgress(TASK_DIFFICULTY);
SimpleMelody(2);
delay(200);
}
}
ShowProgress(TASK_DIFFICULTY);
return;
}
// Serial.print("PrevCode = ");
// Serial.print(currentCode);
// Serial.print(" CurrCode = ");
// Serial.print(code);
// Serial.print(" RquredCode = ");
// Serial.print(task[progress]);
// Serial.print(" Progress = ");
// Serial.println(progress);
if(isTheEnd)
{
progress+=1;
if(progress>MAX_TASK_DIFFICULTY)
{
progress= -MAX_TASK_DIFFICULTY+1;
}
SetSensorLEDs(LOW);
byte led = abs(progress%4);
if(led==2)
led=3;
else
if(led==3)
led=2;
TurnOnSensorLED(led);
byte res = abs(progress);
ShowProgress(res);
delay(100);
return;
}
if(code==task[progress])
{
currentCode=code;
progress+=1;
ShowProgress(progress);
CorrectMelody();
if(progress>=TASK_DIFFICULTY)
{
CorrectMelody();
CorrectMelody();
CorrectMelody();
isTheEnd=true;
OpenDoor();
}
}
else
{
isTheEnd=false;
progress=0;
ShowProgress(progress);
currentCode=0;
SetSensorLEDs(LOW);
WrongMelody();
}
}
Relay (generic)
2 Channel really board was used × 1
to control the motor
Slide Switch
Power on/off switches
× 2
9V battery (generic)
9v Battery holder × 1
This is the schematic for all of the electronics. Its kind of complicated
in the center of the diagram, however the bluetooth dongle receives
what the PS3 controller is telling it and it sends it through the Arduino
USB host shield that is plug in to the Arduino UNO which tells
everything else that to do.
CODE
USB Usb;
BTD Btd(&Usb);
PS3BT PS3(&Btd);
int position=90;
void setup()
{
Serial.begin(115200);
if (Usb.Init() == -1)
{
Serial.print(F("\r\nOSC did not start"));
while(1); //halt
}
Serial.print(F("\r\nPS3 Bluetooth Library Started"));
× 1
testing
testing sensitivity to fumes using a permanent marker pen
running off batteries
new home
glue plus alterations
almost done
SCHEMATICS
CODE
//***************************************************************************
// This is a library for the CCS811 air
// These sensors use I2C to communicate. The device's I2C address is 0x5A
#include <SD.h> // sd card
#include <Wire.h>
#include "RTClib.h" // real time clock
#include <DHT.h> // load lib dht11
#include "Adafruit_CCS811.h"
#include "Arduino.h"
#include "LiquidCrystal_PCF8574.h"
int n = 1;
int val; // A simple data logger for the Arduino analog pins
#define LOG_INTERVAL 1000 // mills between entries (reduce to take more/faster data)
// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
#define SYNC_INTERVAL 10000 // mills between calls to flush() - to write data to the card
600000 = 10 minutes
uint32_t syncTime = 0; // time of last sync()
const int chipSelect = 10; // for the data logging shield, we use digital pin
10 for the SD cs line
LiquidCrystal_PCF8574 lcdI2C;
Adafruit_CCS811 ccs;
File logfile;
void error(char *str)
{
Serial.print(F("error: "));
Serial.println(str);
}
void setup() {
Serial.begin(9600);
if (! logfile) {
error("couldnt create file");
}
// connect to RTC
Wire.begin();
if (!RTC.begin()) {
logfile.println("RTC failed");
#if ECHO_TO_SERIAL
Serial.println(F("RTC failed"));
#endif //ECHO_TO_SERIAL
}
void loop() {
float h = dht.readHumidity();
float f = dht.readTemperature();
if(ccs.available()){
float temp = ccs.calculateTemperature();
if(!ccs.readData()){
DateTime now;
delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL)); // delay for the amount of
time we want between readings
int H = now.hour(); // Get the hours right now and store them in an integer called h
int M = now.minute(); // Get the minutes right now and store them in an integer called m
int S = now.second(); // Get the seconds right now and store them in an integer called s
logfile.print(now.year(), DEC);
logfile.print("/");
logfile.print(now.month(), DEC);
logfile.print("/");
logfile.print(now.day(), DEC);
logfile.print(" ");
if (H<10){ // Add a zero, if necessary, as above
logfile.print(0);
}
logfile.print(now.hour(), DEC);
logfile.print(":");
if (M<10){ // Add a zero, if necessary, as above
logfile.print(0);
}
logfile.print(now.minute(), DEC);
logfile.print(":");
if (S<10){ // Add a zero, if necessary, as above
logfile.print(0);
}
logfile.print(now.second(), DEC);
logfile.print('"');
Serial.print('"');
Serial.print(now.year(), DEC);
Serial.print("/");
Serial.print(now.month(), DEC);
Serial.print("/");
Serial.print(now.day(), DEC);
Serial.print(" ");
if (H<10){ // Add a zero, if necessary, as above
Serial.print(0);
}
Serial.print(now.hour(), DEC);
Serial.print(":");
if (M<10){ // Add a zero, if necessary, as above
Serial.print(0);
}
Serial.print(now.minute(), DEC);
Serial.print(F(":"));
if (S<10){ // Add a zero, if necessary, as above
Serial.print(0);
}
Serial.print(now.second(), DEC);
Serial.print(F(" "));
Serial.print(F("CO2: "));
Serial.print(ccs.geteCO2());
Serial.print(F("ppm, TVOC: "));
Serial.print(ccs.getTVOC());
Serial.print(F("ppb Temp:"));
Serial.println(f); // temp from dht11
lcdI2C.setCursor (0,0);
lcdI2C.print ("CO2 ");
lcdI2C.setCursor (5,0);
lcdI2C.print (" ");
lcdI2C.setCursor (5,0);
lcdI2C.print(ccs.geteCO2()); // Print print String to LCD on first line
lcdI2C.setCursor (0,1); // Set cursor at the begining of line 2
lcdI2C.print ("tVOC ");
lcdI2C.print(ccs.getTVOC()); // Print print String to LCD on second line
lcdI2C.print (" ");
lcdI2C.setCursor (12,1);
if (H<10){ // Add a zero, if necessary, as above
lcdI2C.print(0);
}
lcdI2C.print(now.hour(), DEC);
lcdI2C.print (":");
if (M<10){ // Add a zero, if necessary, as above
lcdI2C.print(0);
}
lcdI2C.print(now.minute(), DEC);
lcdI2C.print (":");
if (S<10){ // Add a zero, if necessary, as above
lcdI2C.print(0);
}
lcdI2C.print(now.second(), DEC);
lcdI2C.setCursor (0,2);
lcdI2C.print ("Humidity ="); // print on the lcd Humidity =
lcdI2C.print(h); // to print the humidity
lcdI2C.print("% "); //print "percentage" symbol
lcdI2C.setCursor (0,3);
lcdI2C.print("Temperature ="); // print on the lcd temp =
lcdI2C.print (f); // print on the lcd temperture
lcdI2C.print((char)223); // print "degrees" symbol
lcdI2C.print("C"); // print "C" with spaces after to fill 20 character line
logfile.print(", ");
logfile.print(ccs.geteCO2());
logfile.print(",");
logfile.print(ccs.getTVOC());
logfile.print(",");
logfile.print(h);
logfile.print(",");
logfile.print(f);
logfile.println();
// Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
// which uses a bunch of power and takes time
if ((millis() - syncTime) < SYNC_INTERVAL) return;
syncTime = millis();
// blink LED to show we are syncing data to the card & updating FAT!
logfile.flush();
}
else{
Serial.println(F("ERROR!"));
while(1);
}
}
}
171) Smart Lock Door with Voice Acrivation using Arduino Projet
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
Alphanumeric LCD, 16 x 2
× 1
5 mm LED: Red
× 1
× 1
Custom PCB
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
Scissor, Electrician
SCHEMATICS
CODE
× 1
1Sheeld
× 1
1Sheeld
× 1
Apple iPhone
× 1
RobotGeek Relay
× 2
Christmas tree
× 1
× 8
9V battery (generic)
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
SCHEMATICS
CODE
#define CUSTOM_SETTINGS
#define INCLUDE_VOICE_RECOGNIZER_SHIELD
#include <OneSheeld.h>
int counter=0;
int x=0;
int y=0;
int z=0;
int l=0;
int m=0;
int n=0;
int p=0;
int q=0;
int val=0;
void setup()
{
/* Start Communication. */
OneSheeld.begin();
pinMode(lamp,OUTPUT);
pinMode(power,OUTPUT);
}
void loop ()
{
/* Check if new command received. */
if(VoiceRecognition.isNewCommandReceived())
{
/* Compare the Poer on command. */
if(!strcmp(poweronCommand,VoiceRecognition.getLastCommand()))
{
digitalWrite(power,LOW);
counter=0;
}
/* Compare the Poer off command. */ else if
(!strcmp(poweroffCommand,VoiceRecognition.getLastCommand()))
{
digitalWrite(power,HIGH);
}
/* Compare the combination command. */
else if (!strcmp(combinationCommand,VoiceRecognition.getLastCommand()))
{
x=0-counter;
if(x<0){
x+=8;
}
for(val=0 ; val<x ; val++){
mode();
}
counter=0;
}
/* Compare the waves command. */
else if (!strcmp(wavesCommand,VoiceRecognition.getLastCommand()))
{
y=1-counter;
if(y<0){
y+=8;
}
for(val=0 ; val<y ; val++){
mode();
}
counter=1;
}
/* Compare the sequential command. */
else if (!strcmp(sequentialCommand,VoiceRecognition.getLastCommand()))
{
z=2-counter;
if(z<0){
z+=8;
}
for(val=0 ; val<z ; val++){
mode();
}
counter=2;
}
/* Compare the slow command. */
else if (!strcmp(slowCommand,VoiceRecognition.getLastCommand()))
{
l=3-counter;
if(l<0){
l+=8;
}
for(val=0 ; val<l ; val++){
mode();
}
counter=3;
}
/* Compare the chasing command. */
else if (!strcmp(chasingCommand,VoiceRecognition.getLastCommand()))
{
m=4-counter;
if(m<0){
m+=8;
}
for(val=0 ; val<m ; val++){
mode();
}
counter=4;
}
/* Compare the fade command. */
else if (!strcmp(fadeCommand,VoiceRecognition.getLastCommand()))
{
n=5-counter;
if(n<0){
n+=8;
}
for(val=0 ; val<n ; val++){
mode();
}
counter=5;
}
/* Compare the Twinkle command. */
else if (!strcmp(twinkleCommand,VoiceRecognition.getLastCommand()))
{
p=6-counter;
if(p<0){
p+=8;
}
for(val=0 ; val<p ; val++){
mode();
}
counter=6;
}
/* Compare the steady command. */
else if (!strcmp(steadyCommand,VoiceRecognition.getLastCommand()))
{
q=7-counter;
if(q<0){
q+=8;
}
for(val=0 ; val<q ; val++){
mode();
}
counter=7;
}
}
}
void mode(){
digitalWrite(lamp,LOW);
delay(150);
digitalWrite(lamp,HIGH);
delay(150);
}
173) Arduino Interactive LED Name Projet
× 1
Slide Switch
× 1
LED (generic)
× 36
SparkFun Potentiometer
× 2
SparkFun Button
× 1
× 2
× 36
NECESSARY TOOLS AND MACHINES
Laser cutter (generic)
When complete squish all the components together and use wood glue
to close the box and connect a 9V battery to the Arduino as a power
supply.
Finished project
SCHEMATICS
CODE
#include <SoftReset.h>
#include <SparkFunLIS3DH.h>
#include <Wire.h>
#include <SPI.h>
int j = 0;
int mode = 0;
int blinkBtn = 4;
int waveBtn = 2;
int loopBtn = 3;
int masterSwitch = 5;
int blinkBtnState, waveBtnState, loopBtnState, masterState;
int speedPot = A0;
int speedValue = 0;
int master = 0;
int buzzer = 9;
LIS3DH myIMU;
int reset = 6;
//holders for infromation you're going to pass to shifting function
byte waveOne, waveTwo, waveThree, waveFour, waveFive, loopOne, loopTwo, loopThree,
loopFour, loopFive;
byte waveDataOne[16], waveDataTwo[16], waveDataThree[16], waveDataFour[16],
waveDataFive[16];
byte loopDataOne[10], loopDataTwo[10], loopDataThree[10], loopDataFour[10],
loopDataFive[10];
void setup() {
digitalWrite(reset, HIGH);
delay(200);
pinMode(reset, OUTPUT);
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
pinMode(blinkBtn, INPUT_PULLUP);
pinMode(waveBtn, INPUT_PULLUP);
pinMode(loopBtn, INPUT_PULLUP);
pinMode(buzzer, OUTPUT);
pinMode(masterSwitch, INPUT_PULLUP);
myIMU.begin();
Serial.begin(9600);
MCUSR = 0;
loopDataOne[0] = 1;
loopDataOne[1] = 3;
loopDataOne[2] = 6;
loopDataOne[3] = 12;
loopDataOne[4] = 24;
loopDataOne[5] = 48;
loopDataOne[6] = 96;
loopDataOne[7] = 192;
loopDataOne[8] = 128;
loopDataOne[9] = 0;
loopDataTwo[0] = 2;
loopDataTwo[1] = 6;
loopDataTwo[2] = 12;
loopDataTwo[3] = 24;
loopDataTwo[4] = 48;
loopDataTwo[5] = 96;
loopDataTwo[6] = 192;
loopDataTwo[7] = 128;
loopDataTwo[8] = 1;
loopDataTwo[9] = 1;
loopDataThree[0] = 8;
loopDataThree[1] = 24;
loopDataThree[2] = 48;
loopDataThree[3] = 96;
loopDataThree[4] = 192;
loopDataThree[5] = 128;
loopDataThree[6] = 0;
loopDataThree[7] = 1;
loopDataThree[8] = 3;
loopDataThree[9] = 6;
loopDataFour[0] = 4;
loopDataFour[1] = 12;
loopDataFour[2] = 24;
loopDataFour[3] = 48;
loopDataFour[4] = 224;
loopDataFour[5] = 193;
loopDataFour[6] = 3;
loopDataFour[7] = 2;
loopDataFour[8] = 2;
loopDataFour[9] = 2;
loopDataFive[0] = 0;
loopDataFive[1] = 0;
loopDataFive[2] = 0;
loopDataFive[3] = 0;
loopDataFive[4] = 0;
loopDataFive[5] = 1;
loopDataFive[6] = 3;
loopDataFive[7] = 6;
loopDataFive[8] = 12;
loopDataFive[9] = 8;
waveDataOne[0] = 56;
waveDataOne[1] = 124;
waveDataOne[2] = 198;
waveDataOne[3] = 131;
waveDataOne[4] = 1;
waveDataOne[5] = 0;
waveDataOne[6] = 0;
waveDataOne[7] = 0;
waveDataOne[8] = 0;
waveDataOne[9] = 0;
waveDataOne[10] = 0;
waveDataOne[11] = 0;
waveDataOne[12] = 0;
waveDataOne[13] = 0;
waveDataOne[14] = 0;
waveDataOne[15] = 0;
waveDataTwo[0] = 0;
waveDataTwo[1] = 0;
waveDataTwo[2] = 0;
waveDataTwo[3] = 1;
waveDataTwo[4] = 25;
waveDataTwo[5] = 60;
waveDataTwo[6] = 102;
waveDataTwo[7] = 194;
waveDataTwo[8] = 128;
waveDataTwo[9] = 0;
waveDataTwo[10] = 0;
waveDataTwo[11] = 0;
waveDataTwo[12] = 0;
waveDataTwo[13] = 0;
waveDataTwo[14] = 0;
waveDataTwo[15] = 0;
waveDataThree[0] = 0;
waveDataThree[1] = 0;
waveDataThree[2] = 0;
waveDataThree[3] = 0;
waveDataThree[4] = 0;
waveDataThree[5] = 0;
waveDataThree[6] = 0;
waveDataThree[7] = 4;
waveDataThree[8] = 7;
waveDataThree[9] = 251;
waveDataThree[10] = 248;
waveDataThree[11] = 0;
waveDataThree[12] = 0;
waveDataThree[13] = 0;
waveDataThree[14] = 0;
waveDataThree[15] = 0;
waveDataFour[0] = 0;
waveDataFour[1] = 0;
waveDataFour[2] = 0;
waveDataFour[3] = 0;
waveDataFour[4] = 0;
waveDataFour[5] = 0;
waveDataFour[6] = 0;
waveDataFour[7] = 0;
waveDataFour[8] = 0;
waveDataFour[9] = 0;
waveDataFour[10] = 1;
waveDataFour[11] = 3;
waveDataFour[12] = 114;
waveDataFour[13] = 248;
waveDataFour[14] = 140;
waveDataFour[15] = 4;
waveDataFive[0] = 0;
waveDataFive[1] = 0;
waveDataFive[2] = 0;
waveDataFive[3] = 0;
waveDataFive[4] = 0;
waveDataFive[5] = 0;
waveDataFive[6] = 0;
waveDataFive[7] = 0;
waveDataFive[8] = 0;
waveDataFive[9] = 0;
waveDataFive[10] = 0;
waveDataFive[11] = 0;
waveDataFive[12] = 3;
waveDataFive[13] = 4;
waveDataFive[14] = 12;
waveDataFive[15] = 8;
}
void loop() {
//Read button states and analog value
blinkBtnState = digitalRead(blinkBtn);
waveBtnState = digitalRead(waveBtn);
loopBtnState = digitalRead(loopBtn);
masterState = digitalRead(masterSwitch);
speedValue = analogRead(speedPot);
speedValue = speedValue / 3;
Serial.println(speedValue);
//Prevents lights from flashing too fast to avoid epilepsy
if(speedValue < 30)
speedValue = 30;
void turnOff()
{
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
}
//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 blinkLeds(int d)
{
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 255);
shiftOut(dataPin, clockPin, 255);
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);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
delay(d);
}
Arduino MKR1000
× 1
× 1
Resistor 1k ohm
× 1
× 2
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
pushingbox
Google Sheets
Cut the wires between the wall-wart and DC-jack (which plugs into
router). Mark one of pair with tape.
6) Use a multi-meter to check the polarity of the wires coming from the
wall-wart, and label them
7) Assemble the circuit as indicated on the schematic on the hardware
page. PCB header terminals like these, are a good way of connecting
the larger wires from the wall-wart and to the DC-jack onto the
breadboard.
8) Customize the Arduino script (see below and the software page for
details) to have the details of your Wi-Fi connection, etc. and then
upload it to the MKR1000 board.
9) Turn on the wall-wart and enjoy never having to manually power-
cycle your router ever again! And also have the satisfaction of a record
being kept of the number of times this power-cycling has been
necessary!
Customizing the Arduino Code
The hardware and software sections provide details of the hardware
required, and the software which needs to be programmed onto the
MKR1000 board. There are two additional steps that are required to get
the full functionality.
The first is setting up a Google Form, and PushingBox account to allow
the Arduino to report information about connection drop-outs and
recoveries. For this project I have followed the excellent
instructions here. There are quite a few steps, but if you follow them
carefully you should get a PushingBox 'DeviceID' which you can paste
into the Arduino sketch, and 'hey-presto' your Ardunio can upload stuff
into a google docs spreadsheet.
The second is log-in details which may be required for your ISP (we
have such a requirement in our apartment). To find these details, go to
the landing page where you normally enter your login information. A
screenshot of our log-in page is given below:
Web Login Page for our Internet
You then need to navigate to the source code of this page (most
browsers will have an option to do so under the 'View' or 'Tools' menu).
You are looking for the action which is taken when you submit the
form (click the login button). The image below shows the source code
for our landing page:
SCHEMATICS
CODE
/*
WiFi Power Toggler
Circuit:
Detailed schematics can be found at the URL above.
Pin 0 connects (via 1k resistor) to the gate of power mosfet
Pin 1 connects (via 100k, 220k potential divider) to the 5V output of 7805 linear regulator
5V pin connects to output of 7805 linear regulator
GND pin connects to ground of 7805 linear regulator
3.7V Li-Po battery connects via the 2-pin JST connector
*/
#include <SPI.h>
#include <WiFi101.h>
//////////////////////////////////
///// VALUES TO BE EDITED ////////
//////////////////////////////////
// WIFI SETTINGS:
char ssid[] = "YOUR_NETWORK_NAME"; // <== Insert your network SSID (name)
HERE
char pass[] = "YOUR_WIFI_PASSWORD"; // <== Your Wi-Fi password goes here
int keyIndex = 0; // <== Your network key Index number goes here
(needed only for WEP)
//////////////////////////////////
////////// EDITING DONE //////////
//////////////////////////////////
void setup() {
// Set up digital outputs (to driver mosfet, and led for debugging):
pinMode(mosfetPin, OUTPUT);
pinMode(ledPin, OUTPUT);
// Also need to turn on the mosfet (otherwise Wi-Fi set-up below won't work)
digitalWrite(mosfetPin, HIGH);
digitalWrite(ledPin, HIGH);
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
/*
while (client.available()) {
char c = client.read();
Serial.write(c);
}*/
lastConnectionCheck = millis();
connStatus = testConnection();
if (~connStatus) {
// Connection not working; log status of mains power, and record time of outage
powerOnAtDisconn = digitalRead(powerSense);
timeConnectionFailed = millis();
// Repeatedly try to turn off power, restore power and re-test connection
// limit to maximum number of iterations to prevent excessive power toggling
// if for example www.google.com is not available for some reason
int nToggles = 0;
while(~connStatus && nToggles <= nTogglesMax) {
digitalWrite(mosfetPin, LOW);
digitalWrite(ledPin, LOW);
delay(timeOff);
digitalWrite(mosfetPin, HIGH);
digitalWrite(ledPin, HIGH);
delay(timeOn);
connStatus = testConnection();
nToggles = nToggles + 1;
}
if (client.connect(serverUpload, 80)) {
delay(1000);
client.stop();
} else {
Serial.println("Failed to connect to pusshing box");
client.stop();
return;
}
}
client.println("");
sprintf(tempString, "Content-Length: %d", sizeof(webLoginUsername) +
sizeof(webLoginPass) + 19);
client.println(tempString);
client.println("");
client.println("Connection: close");
}
else {
Serial.println("Connection to web log-in page failed");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
× 1
× 1
× 1
9V battery (generic)
× 1
× 1
× 1
× 1
NECESSARY TOOLS AND MACHINES
Tape, Double Sided
Arduino IDE
SCHEMATICS
CODE
char t;
const int r1=13,r2=12,l1=11,l2=10;
void setup() {
Serial.begin(9600);
pinMode(r1,OUTPUT); //right motors forward
pinMode(r2,OUTPUT); //right motors reverse
pinMode(l1,OUTPUT); //left motors forward
pinMode(l2,OUTPUT); //left motors reverse
}
void loop() {
if(Serial.available()){
t = Serial.read();
}
else if(t == 'B'){ //move reverse (all motors rotate in reverse direction)
digitalWrite(r1,LOW);
digitalWrite(r2,HIGH);
digitalWrite(l1,LOW);
digitalWrite(l2,HIGH);
}
else if(t == 'L'){ //turn right (left side motors rotate in forward direction, right side
motors rotate in reverse direction for 100ms & stop)
digitalWrite(r1,HIGH);
digitalWrite(r2,LOW);
digitalWrite(l1,LOW);
digitalWrite(l2,HIGH);
delay(100);
t = 'S';
}
else if(t == 'R'){ //turn left (right side motors rotate in forward direction, left side motors
rotate in reverse direction for 100ms & stop)
digitalWrite(r1,LOW);
digitalWrite(r2,HIGH);
digitalWrite(l1,HIGH);
digitalWrite(l2,LOW);
delay(100);
t = 'S';
}
Arduino Nano R3
× 1
SCHEMATICS
CODE
#include "IRremote.h"
int x;
int Power__ON = 0;
IRrecv irrecv(receiver);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn();
pinMode(M1P1, OUTPUT);
pinMode(M1N1, OUTPUT);
pinMode(M2P2, OUTPUT);
pinMode(M2N2, OUTPUT);
pinMode(M1__Speed, OUTPUT);
pinMode(M2__Speed, OUTPUT);
}
void loop()
{
if (irrecv.decode(&results))
{
x = results.value & 0x0000ff;
Serial.println(results.value, HEX);
processIR();
irrecv.resume();
}
}
void processIR()
{
if (x == 0x1f) //previous
{
Serial.println("Motor 1 rotates forward");
digitalWrite(M1P1, HIGH);
digitalWrite(M1N1, LOW);
analogWrite(M1__Speed, velocity1);
}
else if (x == 0x57) //next
{
Serial.println("Motor 2 rotates forward");
digitalWrite(M2P2, LOW);
digitalWrite(M2N2, HIGH);
analogWrite(M2__Speed, velocity2);
}
else if (x == 0x5d) //turn on
{
Power__ON = Power__ON + 1;
int x = Power__ON % 2;
Serial.println(x);
if (x == 0)
{
Serial.println("Both Motor goes OFF");
digitalWrite(M1P1, LOW);
digitalWrite(M1N1, LOW);
digitalWrite(M1P1, LOW);
digitalWrite(M1N1, LOW);
analogWrite(M1__Speed, 0);
analogWrite(M2__Speed, 0);
}
else
{
Serial.println("Both Motor ready to run");
digitalWrite(M1P1, HIGH);
digitalWrite(M1N1, LOW);
digitalWrite(M1P1, HIGH);
digitalWrite(M1N1, LOW);
}
}
else if (x == 0x67) // vol+
{
velocity1 = velocity1 + 10;
analogWrite(M1__Speed, velocity1);
Serial.println(velocity1);
}
else if (x == 0x97) // vol-
{
velocity1 = velocity1 - 10;
analogWrite(M1__Speed, velocity1);
Serial.println(velocity1);
}
else if (x == 0xdd) //mode
{
velocity2 = velocity2 + 10;
analogWrite(M2__Speed, velocity2);
Serial.println(velocity2);
}
else if (x == 0x3d) //equ
{
velocity2 = velocity2 - 10;
analogWrite(M2__Speed, velocity2);
Serial.println(velocity2);
}
else
{
}
delay(500);
}
177) Arduino Blind Runner Alarm Speed Measuring Device Projet
× 4
× 1
Arduino UNO & Genuino UNO
× 1
Buzzer
CODE
#include <Servo.h>
#define BUZZ 2
#define T1 3
#define T2 4
#define E1 5
#define E2 6
#define servoPin 9
#define LED 13
Servo servo;
float wall1, wall2;
int school = 0;
void setup()
{
Serial.begin(9600);
pinMode(BUZZ, OUTPUT);
pinMode(T1, OUTPUT);
pinMode(T2, OUTPUT);
pinMode(E1, INPUT);
pinMode(E2, INPUT);
pinMode(LED, OUTPUT);
servo.attach(servoPin);
get_dis(T1, E1);get_dis(T2, E2);get_dis(T1, E1);get_dis(T2, E2);
get_dis(T1, E1);get_dis(T2, E2);get_dis(T1, E1);get_dis(T2, E2);
Serial.println(wall1 = get_dis(T1, E1));
Serial.println(wall2 = get_dis(T2, E2));
}
void loop()
{
bool B = false;
long Time = 0;
while (1)
{
if (check_super(T1, E1, wall1) == 1)
{ B = true; Time = millis(); break; }
else if (check_super(T2, E2, wall2) == 1)
{ B = false; Time = millis(); break; }
if (check_super(T1, E1, wall1) == 2)
{ return; }
else if (check_super(T2, E2, wall2) == 2)
{ return; }
}
delay(50);
if (B)
while (1)
{
if (check_super(T2, E2, wall2) == 1)
{
Time = millis() - Time;
break;
}
else if (millis() - Time > 1000)
break;
if (check_super(T1, E1, wall1) == 2)
{ return; }
}
else
while (1)
{
if (check_super(T1, E1, wall1) == 1)
{
Time = millis() - Time;
break;
}
else if (millis() - Time > 1000)
break;
else if (check_super(T2, E2, wall2) == 2)
{ return; }
}
if (Time < 300)
{
BUZZER(2000);
digitalWrite(LED, LOW);
}
delay(1000);
}
void BUZZER(int T)
{
long Time = T + millis();
int delayed_T = 0, LED_state = HIGH;
while(1)
{
digitalWrite(BUZZ, HIGH);
delay(1);
digitalWrite(BUZZ, LOW);
delay(1);
if (millis() > Time)
break;
delayed_T += 2;
if (delayed_T > 100)
{
digitalWrite(LED, LED_state);
LED_state = (LED_state == HIGH) ? LOW : HIGH;
delayed_T = 0;
}
}
}
× 1
Breadboard (generic)
× 1
× 3
× 3
× 2
× 1
Capacitor 100 µF
× 2
A wing installation in the wind tunnel. This tutorial is about the control
panel not shown in this picture, but the description of the apparatus
explains the motivations of the control panel functionality.
My arrangement of the Servo Control Panel.
SCHEMATICS
CODE
#include <LiquidCrystal.h>
#include <Servo.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo myServo;
void setup() {
pinMode(zeroPin, INPUT);
pinMode(signPin, INPUT);
lcd.begin(16, 2);
lcd.print("Angle of attack");
lcd.setCursor(0, 1);
lcd.print("control panel");
delay(3000);
lcd.clear();
void loop() {
lcd.home();
lcd.print(lowLimit);
lcd.print(" < AOA < ");
lcd.print(highLimit);
lcd.setCursor(0, 1);
lcd.print("Auto sweep ON");
}
}
else { // if auto sweep is turned off
manual: // label destination of interrupted loop
lcd.setCursor(0, 1);
lcd.print("Manual control");
potVal = analogRead(pot);
Serial.print("potVal: ");
Serial.print(potVal);
angle = map(potVal, 0, 1023, 0, 179);
Serial.print(", angle: ");
Serial.print(angle);
myServo.write(angle);
delay(15);
Serial.print(", zero: ");
Serial.print(zero);
Serial.print(", AOA: ");
Serial.println(alpha);
lcd.home();
lcd.print("AOA = ");
// To avoid overlapping text among readings I must use blank
// characters (space) when needed over the four predicted positions.
× 1
LED (generic)
5 LED of different colors. I used
× 5
white, blue, green, yellow and red.
× 1
× 15
APPS AND ONLINE SERVICES
Arduino IDE
CODE
//* Representing the comfort level by blinking of LED using HUMIDEX by DHT22 sensor
and arduino Uno.
//Libraries
#include <DHT.h>;
#include <math.h>
//Constants
#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
//Variables
double hum; //Stores humidity value
double temp; //Stores temperature value
double B; // Stores the value of intermediate parameter.
double dew; // Stores the value of Dew temperature
long humidex; // Stores the value of HUMIDEX
const int LED1 = 02; // White LED connected to digital pin 2
const int LED2 = 04; // Blue LED connected to digital pin 4
const int LED3 = 06; // Green LED connected to digital pin 6
const int LED4 = 10; // Yellow LED connected to digital pin 8
const int LED5 = 12; // Red LED connected to digital pin 10
void setup()
{
dht.begin();
pinMode(LED1, OUTPUT); // sets the digital pin as output
pinMode(LED2, OUTPUT); // sets the digital pin as output
pinMode(LED3, OUTPUT); // sets the digital pin as output
pinMode(LED4, OUTPUT); // sets the digital pin as output
pinMode(LED5, OUTPUT); // sets the digital pin as output
}
void loop()
{
delay(2000);
//Read data and store it to variables hum and temp
hum = dht.readHumidity();
temp= dht.readTemperature();
B=(log(hum/100)+((17.27*temp)/(237.3+temp)))/17.27; // value of "B", the intermediate
dimentionless parameter has been calculated.
dew=(237.3*B)/(1-B); // The value of dew point has been calculated
humidex=temp+0.5555*(6.11*exp(5417.753*(1/273.16-1/(273.15+dew)))-10); // the value
of HUMIDEX has been claculated.
if (humidex<0){ // the situation when sensor is not working ! i.e NaN is coming out of the
humidity and temperature value.
digitalWrite(LED1, HIGH); // turns the Green LED (numbered as 1) on
delay(1000); // wait for 1 sec
digitalWrite(LED1, LOW); // turns the Green LED (numbered as 1) off
digitalWrite(LED2, HIGH); // turns the white LED (numbered as 1) on
delay(1000); // wait for 1 sec
digitalWrite(LED2, LOW); // turns the White LED (numbered as 1) off
digitalWrite(LED3, HIGH); // turns the yellow LED (numbered as 1) on
delay(1000); // wait for 1 sec
digitalWrite(LED3, LOW); // turns the yellow LED (numbered as 1) off
}
else if (humidex>=0 && humidex <20){
digitalWrite(LED1, HIGH); // turns the green LED (numbered as 1) on
delay(5000); // wait for 5 sec
digitalWrite(LED1, LOW); // turns the green LED (numbered as 1) off
}
else if (humidex>=20 && humidex <30){
digitalWrite(LED2, HIGH); // turns the White LED (numbered as 2) on
delay(5000); // wait for 5 sec
digitalWrite(LED2, LOW); // turns the white LED (numbered as 2) off
}
else if (humidex>=30 && humidex <40){
digitalWrite(LED3, HIGH); // turns the Yellow LED (numbered as 3) on
delay(5000); // wait for 5 sec
digitalWrite(LED3, LOW); // turns the Yellow LED (numbered as 3) off
}
else if (humidex>=40 && humidex <45){
digitalWrite(LED4, HIGH); // turns the blue LED (numbered as 4) on
delay(5000); // wait for 5 sec
digitalWrite(LED4, LOW); // turns the blue LED (numbered as 4) off
}
else {
digitalWrite(LED5, HIGH); // turns the red LED (numbered as 5) on
delay(5000); // wait for 5 sec
digitalWrite(LED5, LOW); // turns the red LED (numbered as 5) off
}
}
× 1
× 1
Alphanumeric LCD, 16 x 2
× 1
Relay (generic)
× 1
LED (generic)
× 1
APPS AND ONLINE SERVICES
Jupyter Notebook
//#include <Key.h>
#include <Keypad.h>
#include <LiquidCrystal.h>
#define Bz 11
#define rLed 10
#define gLed 9
long i;
int screenOffMsg =0;
String password="1234";
String temPassword;
boolean activated = false; //checks the state of the alarm
boolean isActivated;
boolean activateAlarm = false; // check where this is being used
boolean alarmActivated = false;
boolean enteredPassword; // checks the stated of the password
boolean passChangeMode = false;
boolean passChanged =false;
//keypad
const byte Rows = 4;
const byte Cols = 4;
char keypressed;
char KeyMap [Rows][Cols] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
void setup () {
lcd.begin(16,2);
pinMode(Bz, OUTPUT);
pinMode(pirPin, INPUT);
}
void loop() {
if (activateAlarm){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Alarm will be");
lcd.setCursor(0,1);
lcd.print("activated in");
int countdown = 9;
while (countdown != 0) {
lcd.setCursor(13,1);
lcd.print(countdown);
countdown --;
tone(Bz, 700, 100);
delay(1000);
}
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Alarm Activated!");
//sensorValue = digitalRead(pirPin);
digitalWrite(rLed, HIGH);
digitalWrite(gLed, LOW);
activateAlarm = false;
alarmActivated= true;
}
//trigger
if (alarmActivated == true){
sensorValue = digitalRead(pirPin);
if(sensorValue == HIGH) {
lcd.clear();
enterPassword();
}
else {
noTone(Bz);
digitalWrite(rLed, HIGH);
}
}
if (!alarmActivated) {
if(screenOffMsg == 0){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("A - Activate");
lcd.setCursor(0,1);
lcd.print("B - Change Pass");
screenOffMsg = 1;
digitalWrite(rLed, LOW);
digitalWrite(gLed, HIGH);
}
keypressed = myKeypad.getKey();
if (keypressed == 'A'){
tone(Bz, 1000, 200);
activateAlarm = true;
}
181) Arduino Office Status Marquee
Arduino Nano R3
× 1
// my office marquee - currently connected via Contact Closure and RS232 to a Crestron
MP3E for message control.
//
// Use the MD_MAX72XX library to scroll text on the display
//
// Demonstrates the use of the callback function to control what
// is scrolled on the display text.
//
// User can enter text on the serial monitor and this will display as a
// scrolling message on the display.
// Speed for the display is controlled by a pot on SPEED_IN analog in.
#include <MD_MAX72xx.h>
#include <SPI.h>
#define PRINT_CALLBACK 0
// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 8
// Scrolling parameters
#define SCROLL_DELAY 75 // in milliseconds
void readSerial(void)
{
static uint8_t putIndex = 0;
while (Serial.available())
{
newMessage[putIndex] = (char)Serial.read();
//Serial.println(newMessage);
if ((newMessage[putIndex] == '\n') || (putIndex >= BUF_SIZE-3)) // end of message
character or full buffer
{
// put in a message separator and end the string
newMessage[putIndex++] = ' ';
newMessage[putIndex] = '\0';
// restart the index for next filling spree and flag we have a message waiting
putIndex = 0;
newMessageAvailable = true;
}
else if (newMessage[putIndex] != '\r')
// Just save the next char in next location
putIndex++;
}
}
default:
state = 0;
}
return(colData);
}
void scrollText(void)
{
static uint32_t prevTime = 0;
// done with font character, now display the space between chars
if (curLen == showLen)
{
showLen = CHAR_SPACING;
state = 2;
}
break;
default:
col = -1; // this definitely ends the do loop
}
} while (col >= (modStart * COL_SIZE));
void setup()
{
mx.begin();
mx.setShiftDataInCallback(scrollDataSource);
mx.setShiftDataOutCallback(scrollDataSink);
scrollDelay = SCROLL_DELAY;
Serial.begin(57600);
Serial.print("\n[MD_MAX72XX Message Display]\nType a message for the scrolling
display\nEnd message line with a newline");
}
void loop()
{
scrollYes = digitalRead(scrollSwitch);
readSerial();
if (scrollYes == 0){
printText(0, MAX_DEVICES-1, newMessage);
} else {
scrollText();
}
}
182) Arduino Magic Projector
COMPONENTS AND SUPPLIES
× 1
9V battery (generic)
× 1
AA Batteries
× 1
× 1
× 8
9V Battery Clip
× 1
× 1
Switch
× 1
Hand lamp
You can use any source of light
× 1
that produces a directed beam of
light. I did use a led hand lamp:
NF-A651.
Resistor 2.7K ohm
× 1
Cardboard box
× 1
Recycled carton ??
Glue
× 1
Cutting pliers
APPS AND ONLINE SERVICES
Arduino IDE
So, for the next try, I wire every pin on the matrix to each one of the
pins on the Arduino.
Full circuit diagram
Remember to use current limiting resistors on each cathode, I decided
to use 330 Ohm.
Code for the Matrix
The program can be found on my GitHub repo. It's well commented, so
I won't get deep on it. But if you do the wiring as I did, everything
should work.
To generate every image on the matrix, I found a useful resource on the
internet, just need to set the dots to on or off, copy the resulting code
and delete the first two comma separated values of the array.
Delete the red underlined values, and change the name if you want
Lamp attached to the cardboard using wires, the two of the back are the
power cables
I have two batteries on my circuit because I don't have wires of the long
needed to connect the light control circuit and the matrix control circuit,
but it should work using only one 9V battery to power all the circuit.
Step Three: Box Enclosure
The magic box has two compartments. The first is where the Arduino and
the matrix are attached. The second have the light and his control circuit in
it. In order for the projection to work, you have to be careful when get the
hardware inside the box, anything should be in front of the light. I've tried
to attach the wires very well to avoid any problem.
The box should look like this, but feel free to make your own design.
Front
Side
Control panel
For the control panel I get some translucent black fabric and cover the
matrix with it. When it's turn off, the led behind are barely visible, so it
gives a nice effect to the box.
I cover all the cardboard with matte black paper to make it looking good,
and finally print text that was made in Canva on acetate paper and put it
on one side of the box. Image below:
Projection sheet
SCHEMATICS
CODE
/******************/
// Control an 8x8 led matrix(GMM-23088CSB) with an Arduino UNO
// Pin connections:
// Remember use a resistor on each anode.
// Columns
// matrix | 13 | 3 | 4 | 10 | 6 | 11 | 15 | 16 |
// Arduino | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
//
// Raws
// matrix | 9 | 14 | 8 | 12 | 1 | 7 | 2 | 5 |
// Arduino | 10 | 11 | 12 | 13 | A0 | A1 | A2 | A3 |
/******************/
byte sp[]= { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
byte c_1[] =
{B00000000,B01111110,B01000010,B01000010,B01000010,B01000010,B01111110,B00000000
byte c_2[] =
{B00000000,B00000000,B00111100,B00100100,B00100100,B00111100,B00000000,B00000000
byte c_3[] =
{B00000000,B00000000,B00000000,B00011000,B00011000,B00000000,B00000000,B00000000
byte jenny[] =
{B00000000,B01111100,B00010000,B00010000,B00010000,B00010000,B01110000,B00000000
byte flecha_1[] =
{B00000000,B00001000,B00001100,B01111110,B00001100,B00001000,B00000000,B00000000
byte flecha_2[] =
{B00000000,B00001000,B00001100,B01111110,B01111110,B00001100,B00001000,B00000000
byte heart[] =
{B00000000,B01101100,B11111110,B11111110,B01111100,B00111000,B00010000,B00000000
byte heart_outline[] =
{B00000000,B01101100,B10010010,B10000010,B01000100,B00101000,B00010000,B00000000
byte load1[] =
{B00000000,B00000000,B00000000,B00000000,B00000000,B11111110,B10000010,B11111110
byte load2[] =
{B00000000,B00000000,B00000000,B00000000,B00000000,B11111110,B11000010,B11111110
byte load3[] =
{B00000000,B00000000,B00000000,B00000000,B00000000,B11111110,B11100010,B11111110
byte load4[] =
{B00000000,B00000000,B00000000,B00000000,B00000000,B11111110,B11110010,B11111110
byte load5[] =
{B00000000,B00000000,B00000000,B00000000,B00000000,B11111110,B11111010,B11111110
byte load6[] =
{B00000000,B00000000,B00000000,B00000000,B00000000,B11111110,B11111110,B11111110
//byte load7[] =
{B00000000,B00000000,B00000000,B00000000,B00000000,B11111111,B11111111,B11111111
void setup()
{
for (int j=2; j<19; j++){
pinMode(j, OUTPUT);
}
digitalWrite(18, LOW);
}
void SetChar(char p)
{
Clear();
for (int fil = 0; fil <8 ; fil++)
{
delayMicroseconds(350);
digitalWrite( fil + 10 , LOW) ; // Activamos la fila para el barrido
//byte F = N[fil] ;
byte F = Selecciona( p, fil);
for (int col =7; col >= 0 ; col--)
{
delayMicroseconds(350);
digitalWrite(8-col, LOW); //Bajamos la columna
bool b = GetBit(F, col) ;
if (b){
digitalWrite( 9 - col ,HIGH); //Levantamos la columna, con su pin
}
else {
digitalWrite( 9 - col ,LOW); // Si 0, apagamos
}
} // Solo si b es 1
digitalWrite( fil + 10 , HIGH) ; // Apagamos fila antes de salir
}
}
void Clear()
{
for (int j=2; j<10; j++) // Valores de los pines de columna
digitalWrite(j, LOW); // Todos apagados
for (int k= 10 ; k<18 ; k++){
digitalWrite(k, HIGH); // Todas las filas cortadas
}
}
String s;
long t;
char c;
void loop()
{
s = "loadin n n n n";
for ( int n = 0; n < 14; n++ )
{
t = millis();
c = s[n];
if(n < 6){
while ( millis()< t + 1000)
SetChar(c);
} else {
while ( millis()< t + 380)
SetChar(c);
}
}
delay(500);
//Jenny
s = "4";
t = millis();
c = s[0];
while(millis() < t + 4000){
SetChar(c);
}
//Corazn
s = "5";
t = 0;
t = millis();
c = s[0];
while(millis() < t + 4000){
SetChar(c);
}
//Corazn eterno
s = "5";
c = s[0];
while(1){
SetChar(c);
}
}
183) Arduino Control Music Volume and Ledbar using Slider of
1Sheeld
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
1Sheeld
× 1
× 1
9V battery (generic)
× 1
Android device
× 1
APPS AND ONLINE SERVICES
Arduino IDE
#define CUSTOM_SETTINGS
#define INCLUDE_SLIDER_SHIELD
#define INCLUDE_MUSIC_PLAYER_SHIELD
/* Include 1Sheeld library. */
#include <OneSheeld.h>
void setup() {
/* Set the LEDs pins as output. */
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led3,OUTPUT);
pinMode(led4,OUTPUT);
pinMode(led5,OUTPUT);
pinMode(led6,OUTPUT);
pinMode(led7,OUTPUT);
pinMode(led8,OUTPUT);
pinMode(led9,OUTPUT);
pinMode(led10,OUTPUT);
/* Start communication. */
OneSheeld.begin();
}
void loop() {
value = Slider.getValue(); /* get the slider value and keep it in the "value" variable. */
value = map(value,0,255,0,10); /* mapping the analog values of slider into values between
0 and 10 -*/
/*so the music volume will understand it. */
switch (value) /*switch between the values to determine whicch leds to turn on and which
to turn off.*/
{
case 1:
digitalWrite(led1,HIGH);
digitalWrite(led2,LOW);
digitalWrite(led3,LOW);
digitalWrite(led4,LOW);
digitalWrite(led5,LOW);
digitalWrite(led6,LOW);
digitalWrite(led7,LOW);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 2:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,LOW);
digitalWrite(led4,LOW);
digitalWrite(led5,LOW);
digitalWrite(led6,LOW);
digitalWrite(led7,LOW);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 3:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,LOW);
digitalWrite(led5,LOW);
digitalWrite(led6,LOW);
digitalWrite(led7,LOW);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 4:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led5,LOW);
digitalWrite(led6,LOW);
digitalWrite(led7,LOW);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 5:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led5,HIGH);
digitalWrite(led6,LOW);
digitalWrite(led7,LOW);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 6:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led5,HIGH);
digitalWrite(led6,HIGH);
digitalWrite(led7,LOW);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 7:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led5,HIGH);
digitalWrite(led6,HIGH);
digitalWrite(led7,HIGH);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 8:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led5,HIGH);
digitalWrite(led6,HIGH);
digitalWrite(led7,HIGH);
digitalWrite(led8,HIGH);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
break;
case 9:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led5,HIGH);
digitalWrite(led6,HIGH);
digitalWrite(led7,HIGH);
digitalWrite(led8,HIGH);
digitalWrite(led9,HIGH);
digitalWrite(led10,LOW);
break;
case 10:
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
digitalWrite(led5,HIGH);
digitalWrite(led6,HIGH);
digitalWrite(led7,HIGH);
digitalWrite(led8,HIGH);
digitalWrite(led9,HIGH);
digitalWrite(led10,HIGH);
break;
default:
digitalWrite(led1,LOW);
digitalWrite(led2,LOW);
digitalWrite(led3,LOW);
digitalWrite(led4,LOW);
digitalWrite(led5,LOW);
digitalWrite(led6,LOW);
digitalWrite(led7,LOW);
digitalWrite(led8,LOW);
digitalWrite(led9,LOW);
digitalWrite(led10,LOW);
}
184) Arduino Talking Tom
× 1
ISD1820 Module
× 1
SCHEMATICS
CODE
void setup()
{
pinMode(Rec, OUTPUT);
pinMode(Play, OUTPUT);
}
void loop()
{
digitalWrite(Rec, HIGH);
delay(10000);
digitalWrite(Rec, LOW);
delay(5000);
digitalWrite(Play, HIGH);
delay(100);
digitalWrite(Play, LOW);
delay(10000);
}
185) Arduino Sand Art Display
/*
Stepper Motor Control progam for an X-Y table named "Sand Art Display".
This program drives two unipolar 5V DC stepper motors type 28BYJ-48.
The motors are attached to digital pins 4,5,6,7 and 8,9,10 and 11 of the Arduino UNO,
via a driver board with IC ULN2003.
The motor power supply on this board is a separate 5V DC supply.
GND is connected to the GND of the Arduino.
The motors drive both axis of the sand art table with a 250 mm rack gear.
It starts the movement blue, yellow or white when the motors are resting in the full left &
up position.
See www.apinventions.wordpress.com for the Sand Art Display building instructions.
*/
#include <Stepper.h>
//this sequence is special for the 28BYJ-48 stepper motor.
Stepper myStepperX(1024, 8,10,9,11);Stepper myStepperY(1024, 4,6,5,7);
void setup() {
myStepperX.setSpeed(speed3);myStepperY.setSpeed(speed3);
pinMode(3,INPUT_PULLUP);pinMode(12,INPUT_PULLUP);pinMode(A1,INPUT_PULLUP
pinMode(A2,OUTPUT);pinMode(A3,OUTPUT);pinMode(A4,OUTPUT);pinMode(A5,OUTPUT
myStepperX.step(5*left);myStepperY.step(5*up);// always move to left/up corner start
position
}
void loop() {
myStepperX.setSpeed(speed3);myStepperY.setSpeed(speed3);
digitalWrite(whiteled,LOW);digitalWrite(yellowled,LOW);digitalWrite(blueled,LOW);
y = digitalRead(ystop);if(y==HIGH) {myStepperY.step(4*up);}
x= digitalRead(xstop);if(x==HIGH) {myStepperX.step(4*left);}
}
//PONG
void blue(){
myStepperX.setSpeed(speed2);myStepperY.setSpeed(speed2);
digitalWrite(blueled,HIGH);digitalWrite(resetled,LOW);
//PLOUGH
void yellow(){
myStepperX.setSpeed(speed2);myStepperY.setSpeed(speed2);
digitalWrite(yellowled,HIGH);digitalWrite(resetled,LOW);
x=73-d;myStepperX.step(x*right);
y=56-d;myStepperY.step(y*down);
d=d+3;
x=73-d;myStepperX.step(x*left);
y=56-d;myStepperY.step(y*up);
d=d+3;
while(y<5 || x< 5){} ;
yellow();
}
//WAFFLE
void white(){
myStepperX.setSpeed(speed2);myStepperY.setSpeed(speed2);
digitalWrite(whiteled,HIGH);digitalWrite(resetled,LOW);
if(d==0){
if(n==0){myStepperY.step(5*down);}
y = digitalRead(ystop);if(y==LOW && n==0){myStepperX.step(11*right);n=1;x=x+1;}
if(n==1){myStepperY.step(5*up);}
y = digitalRead(ystop);if(y==LOW && n==1){myStepperX.step(11*right);n=0;x=x+1;}
if(x >7){d=1;y=0;n=0;}
}
if (d==1){
if(n==0){myStepperX.step(5*left);}
x = digitalRead(xstop);if(x==LOW && n==0){myStepperY.step(11*down);n=1;y=y+1;}
if(n==1){myStepperX.step(5*right);}
x = digitalRead(xstop);if(x==LOW && n==1){myStepperY.step(11*down);n=0;y=y+1;}
while(y >5){};
}
white();
}
× 1
Alphanumeric LCD, 16 x 2
× 1
× 1
Resistor 1k ohm
× 1
× 1
× 1
Resistor 1M ohm
× 1
A 16x2 LCD just out of the kit provides the display needs in full
I started this first project as a way to learn better and make it available
a great idea to those who have just started with a basic kit.
So I started this first project as a way to learn better and make it
available a great idea (Federico's - see credits) to those who have just
started with a basic kit and the UNO board.
The theoretical principle that is applied here (and in many other
projects) is the "Voltage divider equation make difficult things simple it
is a way to calculate one resistor value that you don't know putting two
one after the other and reading how much of the total voltage the know
resistor make you read at its terminals. The nearer the two are the more
precise the result can be - so to make a balanced compromise we use
five different values of know sample resistors.
Let's get started!!!
You need to make ready the components. The scheme below will easily
take you to configure the breadboard. I used two different ones - to
keep the 16x2 LED display function as much similar as to those of the
tutorials (you should try the display as a separate part first, if you have
not done it yet!) and get more visibility on the simple resistor part
'addition'. There's plenty of space left on the main breadboard to move
it all on one - you just need to keep connected with the 5 green wires
and the yellow one as before.
Full -fritzing- breadboard view
When you have arranged the components in this way you can also try
to move it around checking with the schematics below:
Schematics
At the end it should be something like...
Now is time to open up the coding - pick up the code in the proper
section of this page and start reading it to feel it up. As everything in an
Open Source environment it is a collage of what others have built
before us. In particular all the sections that enable the visualization on
the LCD is very standard.
I added on the original project a FUNCTION - that is a separate piece
of code that gets AFTER the usual two sections of "setup" and "loop" -
that can be "called" to make a specific calculation or - in the case a
formatting - of one or more variables. I used it to transform a number
1.000.121, 34 in a string that is readable after the normal conventions
for resistors - such as 1MOhm. The rounding and formatting would
need a more extensive testing to check for all exceptions and
anomalies... help me there.
String OhmFormattingFunction(float Input) {
//FS 20200223 v0 - Ohm values formatting function **
String Result;
if (Input < 80) {
valore = (String(round(Input)));
suffisso = " ";
}
....
I confess I kept some words inside the code in the Italian (Leonardo's!)
language but it will take just a moment for you to replace them with...
whatever idiom you were born to or in the English we all share. There
are extensive debugging inserts in form of printed serial text to follow
the procedure from the monitor.
IMPROVEMENT PATH:
First of all you should make this yours by adapting it to your style
and needs - correct the unavoidable mistakes and try to improve the
calculations and/or the formatting letting us all know by commenting
(much appreciated)
I strongly suggest you buy a 0.96" OLED display and try it out - it is
quite inexpensive and easy to implement (see Federico's project)
Another way to get nearer to a finished "product" is to port it to a
Nano Every - I found that the pins are the same etc. (this requires
soldering and although it is not difficult, it implies a different level
of involvement).
SCHEMATICS
CODE
// lazyRmeter by FEDERICO VIVALDI all references to OLE display removed - pins
relocated
// lazyRmeter_v2_16x2 semplified by F.Stella 20200221 for UNO and serial print to be
ported to simple 16x2 display
// LCD 16x2 code - example added 9 Jul 2009 by Tom Igoe - modFS2020
//include the LCD library code:
#include <LiquidCrystal.h>
int R1 = 100;
int R2 = 1000;
int R3 = 10000;
long R4 = 100000;
long R5 = 1000000;
long Rn;
float Input;
String valore;
String suffisso;
float trans;
int compR1 = 6;
int compR2 = 7;
int compR3 = 8;
int compR4 = 9;
int compR5 = 10;
float raw = 0;
float Vout = 0;
float Ru = 0;
int analogOhm = A0;
void setup() {
Serial.begin(9600);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a fixed message title to the LCD.
lcd.print("Resistenza da: ");
}
void loop() {
//attivazione porte a cui sono collegate le resistenze campione
pinMode(compR1, OUTPUT); //parto attivando il pin 2 che va alla resistenza test pi alta
da 1M
pinMode(compR2, INPUT);
pinMode(compR3, INPUT);
pinMode(compR4, INPUT);
pinMode(compR5, INPUT);
Rn = R5;
Serial.println(raw); //DEBUG
Serial.println("ref 1M"); //DEBUG
Serial.println(raw);
Serial.print("ref 100k: ");
Serial.println(Rn);
Serial.println(raw);
Serial.println("ref 10k");
Serial.println(raw);
Serial.println("ref 1k");
Serial.println(raw); // DEBUG
Serial.println("ref 100");// DEBUG
}
}
}
}
Vout = 5*(raw/1024);
Ru = (Rn*Vout)/(5-Vout);
Serial.print("Ru: "); // DEBUG
Serial.println(Ru); // DEBUG
lcd.setCursor(0,1);
lcd.print(resOhm);
}
String Result;
× 1
IR receiver (generic)
× 1
SCHEMATICS
Bluetooth module
ir transmitter
ir decoder
CODE
ode 1Arduino
use in the first for decoding ir .
void setup(void) {
Serial.begin(9600);
Serial.println("Ready to decode IR!");
}
void loop(void) {
uint16_t highpulse, lowpulse; // temporary storage timing
highpulse = lowpulse = 0; // start out with no pulse length
// same as above
while (! (IRpin_PIN & _BV(IRpin))) {
// pin is still LOW
lowpulse++;
delayMicroseconds(RESOLUTION);
if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
printpulses();
currentpulse=0;
return;
}
}
pulses[currentpulse][1] = lowpulse;
void printpulses(void) {
Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
for (uint8_t i = 0; i < currentpulse; i++) {
Serial.print("delayMicroseconds(");
Serial.print(pulses[i][0] * RESOLUTION, DEC);
Serial.print("); pulseIR(");
Serial.print(pulses[i][1] * RESOLUTION, DEC);
Serial.println(");");
}
}
code 2Arduino
use secondly for transmitting ir.
int IRledPin = 3;
void setup()
{
pinMode(IRledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
int a;
if(Serial.available()>0)
{
a=Serial.read();
switch(a)
{
case 1: power(); //if it receives the number "1" from the app then the case one will be
executed
break;
case 2:tvpower();
break;
case 3:chplus();
break;
case 4:chminus();
break;
case 5:volplus();
break;
case 6:volminus();
break;
//all the data provided corresponds to my tv remote thus you have to modify to your needs
case 10: zero(); //if it receives the number "10" from the app then the case 10 will be
executed thus the respective channel is switched
delay(700);
nine();
delay(700);
one();
delay(700);
zero();
delay(700);
break; //channel number 910 will be switched
}
}
void pulseIR(long microsecs)
{
cli();
while (microsecs > 0)
{
digitalWrite(IRledPin, HIGH);
delayMicroseconds(10);
digitalWrite(IRledPin, LOW);
delayMicroseconds(10);
microsecs -= 26;
}
sei();
}
void power() /*the function stores the data for the power button taken from the step-1*/
{
//the data is for my remote so update the data with yours
delayMicroseconds(57608 );
pulseIR( 2680 );
delayMicroseconds(980 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(960 );
pulseIR( 400 );
delayMicroseconds(980 );
pulseIR( 860 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 860 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(960 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(61644 );
pulseIR( 2700 );
delayMicroseconds(980 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(980 );
pulseIR( 400 );
delayMicroseconds(960 );
pulseIR( 880 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 420 );
delayMicroseconds(480 );
pulseIR( 420 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 400 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(500 );
pulseIR( 860 );
delayMicroseconds(520 );
pulseIR( 400 );
delayMicroseconds(960 );
pulseIR( 420 );
delayMicroseconds(500 );
pulseIR( 400 );
}
void chplus()
{
//put the data of your channel plus button in this section
}
void ch minus()
{
}
void one()
{
}
void two()
{
}
void three()
{
}
//add for all the 10 numbers.
Breadboard (generic)
× 1
Alphanumeric LCD, 16 x 2
× 1
× 4
× 1
× 1
SCHEMATICS
CODE
#include <LiquidCrystal.h>
//PIN 5 R/W to Ground, for writing
//LCD Mode : 4 data pin
//Functions: Start, stop, saving up to 4 partial time in memory.
//10 millis = 1 hundredth of a second. The chronometer measures hour, minutes, seconds,
and hundredths of a second.
//LCD
int lcdclear = 0; //this to variables are needed for managing
int Display = 0; //the display, to clear and print
//chronometer
int cents = 0;
int seconds = 0;
int minutes = 0;
int hours = 0;
const int interval = 10; //Every 10 milliseconds i increase 1 cent
unsigned long previousMillis = 0;
int c1, c2, s1, s2, m1, m2, h; //Variables used to put in the form
//h:m2m1:s2s1:c2c1
void setup() {
pinMode(start, INPUT_PULLUP); //In the schematic from right to left
pinMode(pausa, INPUT_PULLUP);//there are start-pausa-partial-scroll_partial
pinMode(partial, INPUT_PULLUP);
pinMode(scroll_partial, INPUT_PULLUP);
lcd.begin(16,2);
lcd.print("Press start");
}
void loop() {
if (x == 0) { //Initially is 0
while(digitalRead(start) == HIGH) {}; //Until i press the button, the chronometer doesn't
start
x++; //When i press the button, i go out from this cycle, x++ and i cannot return here
anymore
}
if (lcdclear == 0){ //Condition to clear the display, used in the various functions
lcd.clear();
lcdclear++;
}
if (Display == 0){ //Also this is used to clear display
lcd.home();
lcd.print("Now: "); //With this condition, i can print "Now: " one single time, otherwise
the chronometer wouldn't be precise
Display++;
scrolling = 0; //When i exit from the partial menu, then if i go in the partial menu again i
always get in PAR1 and PAR2
}
chronometer(); //At the end of every increase, i control if stop is pressed. And also if the
partial function is pressed
pause();
f_partial();
}
void scrollPartial(void){
while(digitalRead(scroll_partial) == LOW) {}; //Debounce, as long as i press the button the
real function doesn't start
if (scrolling == 0) { //Visualize the last 2 partials
lcd.clear();
lcd.home();
lcd.print("PAR1:");
lcd.setCursor(6, 0);
lcd.print(h);
lcd.print(':');
lcd.print(m2);
lcd.print(m1);
lcd.print(':');
lcd.print(s2);
lcd.print(s1);
lcd.print(':');
lcd.print(c2);
lcd.print(c1);
lcd.setCursor(0, 1);
lcd.print("PAR2:");
lcd.setCursor(6, 1);
lcd.print(partial2[0]);
lcd.print(':');
lcd.print(partial2[1]);
lcd.print(partial2[2]);
lcd.print(':');
lcd.print(partial2[3]);
lcd.print(partial2[4]);
lcd.print(':');
lcd.print(partial2[5]);
lcd.print(partial2[6]);
Display = 0; //When i press start the display must be cleared
lcdclear = 0; //When i press start the display must be cleared
cents = seconds = minutes = hours = 0;
scrolling++;
}
else if (scrolling == 1){ //Visualize 3th and 4th partial
lcd.clear();
lcd.home();
lcd.print("PAR3:");
lcd.setCursor(6, 0);
lcd.print(partial3[0]);
lcd.print(':');
lcd.print(partial3[1]);
lcd.print(partial3[2]);
lcd.print(':');
lcd.print(partial3[3]);
lcd.print(partial3[4]);
lcd.print(':');
lcd.print(partial3[5]);
lcd.print(partial3[6]);
lcd.setCursor(0, 1);
lcd.print("PAR4:");
lcd.setCursor(6, 1);
lcd.print(partial4[0]);
lcd.print(':');
lcd.print(partial4[1]);
lcd.print(partial4[2]);
lcd.print(':');
lcd.print(partial4[3]);
lcd.print(partial4[4]);
lcd.print(':');
lcd.print(partial4[5]);
lcd.print(partial4[6]);
Display = 0; //When i press start the display must be cleared
lcdclear = 0; //When i press start the display must be cleared
cents = seconds = minutes = hours = 0;
scrolling = 0;
void pause(void){ //If pause is pressed, i stop in this function until start doesn't get pressed
again
if (digitalRead(pausa) == HIGH)
return;
else if (digitalRead(pausa) == LOW){ //Stuck in this cycle until i press start
while(digitalRead(start) == HIGH) {
if (digitalRead(scroll_partial) == LOW) //If i press the button for seeing the partial, i enter
in that function
scrollPartial(); //When scrollPartial() ends, i'm still in this function, so if i press start the
chronometer starts back normal
}
}
}
void f_partial(void){ //If this button is pressed, i put the current value of New in Old, and
a new crhonometer starts
if (digitalRead(partial) == HIGH)
return;
else if (digitalRead(partial) == LOW ){
lcd.clear();
lcd.setCursor(0, 1); //The values calculated in the function chronometer can be used,
h,m,s,c
lcd.print("Old: ");
lcd.setCursor(6, 1);
lcd.print(h);
lcd.print(':');
lcd.print(m2);
lcd.print(m1);
lcd.print(':');
lcd.print(s2);
lcd.print(s1);
lcd.print(':');
lcd.print(c2);
lcd.print(c1); //When i come here, i've got the old values for h,m,s,c, i save
it in the partial array
Display = 0; //The new is written again
cents = 0;
seconds = 0;
minutes = 0;
hours = 0;
while(digitalRead(partial) == LOW) {}; //Debounce, until i press the button i stay here
}
}
9V battery (generic)
× 1
9V Battery Clip
× 1
× 2
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
SCHEMATICS
CODE
/*
Connections:
Arduino UNO pin 2 to Vin
Arduino UNO pin 7 to Shield TXD
Arduino UNO pin 8 to Shield RXD
Arduino UNO pin 9 to Shield pin 9 (shield ON/OFF)
Arduino UNO GND to Shield GND
*/
#include <SoftwareSerial.h>
void setup() {
// Switch on the GSM shild
pinMode(9,OUTPUT);
digitalWrite(9, HIGH);
delay(2000);
digitalWrite(9, LOW);
delay(5000);
// Set pin 2 as input for Vin detection
pinMode(2,INPUT);
// Arduino communicates with SIM900 GSM shield at a baud rate of 19200
SIM900.begin(19200);
// Give time to GSM shield to log on to network
delay(30000);
// AT command to set SIM900 to SMS mode
SIM900.print("AT+CMGF=1\r");
delay(100);
sendSMSready();
// Set module to send SMS data to serial out upon receipt
// SIM900.print("AT+CNMI=2,2,0,0,0\r");
// delay(100);
}
void loop()
{
// Display any text that the GSM shield sends out on the serial monitor
if(SIM900.available() >0) {
//Get the character from the cellular serial port
incoming_char=SIM900.read();
//Print the incoming character to the terminal
Serial.print(incoming_char);
}
while (digitalRead(2) == HIGH) {}
if(digitalRead(2) == LOW && allarmSent == LOW) {
// whait 1" more and send message if pin 2 is already LOW
delay(1000);
if(digitalRead(2) == LOW) sendSMSallarm();
}
while (digitalRead(2) == LOW) {}
if(digitalRead(2) == HIGH && allarmSent == HIGH) sendSMSallarmOFF();
}
void sendSMSallarm()
{
// Set recipient's mobile number in international format
SIM900.println("AT + CMGS = \"+XXXXXXXXXXXX\"");
delay(100);
// Set SMS message
SIM900.println("*** MANCANZA TENSIONE RETE ***");
delay(100);
// End AT command with a ^Z, ASCII code 26
SIM900.println((char)26);
delay(100);
SIM900.println();
// Give module time to send SMS
delay(5000);
allarmSent = HIGH;
}
void sendSMSallarmOFF()
{
// Set recipient's mobile number in international format
SIM900.println("AT + CMGS = \"+XXXXXXXXXXXX\"");
delay(100);
// Set SMS message
SIM900.println("*** TENSIONE RETE OK ***");
delay(100);
// End AT command with a ^Z, ASCII code 26
SIM900.println((char)26);
delay(100);
SIM900.println();
// Give module time to send SMS
delay(5000);
allarmSent = LOW;
}
void sendSMSready()
{
// Set recipient's mobile number in international format
SIM900.println("AT + CMGS = \"+XXXXXXXXXXXX\"");
delay(100);
// Set SMS message
SIM900.println("*** SISTEMA CONNESSO ***");
delay(100);
// End AT command with a ^Z, ASCII code 26
SIM900.println((char)26);
delay(100);
SIM900.println();
// Give module time to send SMS
delay(5000);
}
190) Arduino Using Median Filter To Display DHT22 and RTC
× 1
Robojax DS3231 IIC Precision Real
time Clock Module
× 1
Any equivalent DS3231 IIC RTC
should work
Kuman 0.96 Inch Yellow Blue IIC
OLED Module I2c
× 1
Any equivalent 0.96 inch OLED
should work
Arduino Nano R3
SCHEMATICS
CODE
/*
Use an Arduino Nano to display temp/humidy on 0.96 inch Yellow/Blue IIC OLED I2c
serial 128x64 Display
These data might bounce around somewhat because the sensor can be a little noisy
at times. We use a simple median filter to smooth out the noise
*/
#include "DHT.h";
/* DHT22 pin-out:
Pin 1 VCC
Pin 2 Data out
Pin 3 Not connected
Pin 4 Ground
*/
// Define Constants
// Initialize OLED
U8GLIB_SSD1306_128X32 u8g(U8G_I2C_OPT_NONE);
#define buff_size 7 // Must be an odd number. Should be greater than 5. 7 works well.
char OLED_string_1[50]; // Need a couple of character buffers to hold the two OLED lines
char OLED_string_2[50];
void clearOLED()
{
u8g.firstPage();
do {
} while( u8g.nextPage() );
}
void Initialize()
{
float startup_delay;
int i;
clearOLED();
startup_delay = buff_size * (a_second * 5.0 / 1000.0);
temporary_string = String(startup_delay,0);
temporary_string = " (" + temporary_string + " seconds)";
void sendstringstoDisplay()
{
u8g.firstPage(); // Send them to the dispaly
do {
} while (u8g.nextPage() );
}
int int_month;
str_month = tm.Month;
int_month = str_month.toInt();
switch(int_month)
{
case 1:
str_month =("JAN");
break;
case 2:
str_month =("FEB");
break;
case 3:
str_month =("MAR");
break;
case 4:
str_month =("APR");
break;
case 5:
str_month =("MAY");
break;
case 6:
str_month =("JUN");
break;
case 7:
str_month =("JUL");
break;
case 8:
str_month =("AUG");
break;
case 9:
str_month =("SEP");
break;
case 10:
str_month =("OCT");
break;
case 11:
str_month =("NOV");
break;
case 12:
str_month =("DEC");
break;
default:
str_month =("ERR");
break;
}
// Add a leading zero when needed so all numbers are two characters
String hours,seconds,minutes;
if(tm.Hour<10)
{
hours = "0"+String(tm.Hour);
}
else
{
hours = String(tm.Hour);
}
if(tm.Minute<10)
{
minutes = "0"+String(tm.Minute);
}
else
{
minutes = String(tm.Minute);
}
// We're processing seconds "just in case", but not adding them to the small display
if(tm.Second<10)
{
seconds = "0"+String(tm.Second);
}
else
{
seconds = String(tm.Second);
}
void setup()
{
// Start Wire library for I2C
Wire.begin();
clearOLED();
dht.begin();
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
Initialize();
}
void loop()
{
int i, median_index;
// Replace the oldest value with the newest just read by moving every element in
// the arrays up one and sticking this new value in the bottom.
for (i = 0 ; i < buff_size - 1 ; i++)
{
h_array[i] = h_array[i + 1];
t_array[i] = t_array[i + 1];
}
h_array[buff_size-1] = h;
t_array[buff_size-1] = t;
// Sort them. Use quick and dirty bubble sort because it's a small number of data points
bubble_sort(h_array_sort, buff_size);
bubble_sort(t_array_sort, buff_size);
// Use the median of the last "buff_zize" readings for the display
median_index = buff_size / 2;
h = h_array_sort[median_index];
t = t_array_sort[median_index];
string_Temp = String(t,1); // Make temp a character string
string_Humid = String(h,1); // Make humid a character string
× 1
× 1
× 1
Breadboard (generic)
× 1
Resistor 1k ohm
× 1
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
#include <IRremote.h>
#include <Servo.h>
#include <LiquidCrystal.h>
Servo myservo;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
int receiver = 10;
IRrecv irrecv(receiver);
decode_results results;
int code=0;
int x;
int cont=0;
int volume=0;
int y=0;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn();
myservo.attach(11);
lcd.begin(16, 2);
lcd.clear();
}
void loop()
{
if (irrecv.decode(&results))
{
code=results.value;
Serial.println(code, HEX);
irrecv.resume();
switch(code)
{
case(0xFFFFA857):
cont=1;
x=x+3;
break;
case(0xFFFFE01F):
cont=0;
x=x-3;
break;
case(0xFFFFFFFF):
if(cont==1)x=x+4;
if(cont==0)x=x-4;
break;
default;
cont=2;
break;
}
x=constrain(x,3,180);
Serial.println(x);
myservo.write(x);
volume=map(x,3,180,0,100);
}
lcd.setCursor(8, 0);
lcd.print("VOLUME:");
lcd.setCursor(4, 1);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print(volume);
if(volume>80)
{
lcd.setCursor(7, 1);
lcd.print("too high!");
}
delay(50);
lcd.clear();
}
192) Arduino Clock
× 1
PCF8563
× 1
Crystal 32kHz
× 1
10K potentiometers
× 10
× 10
LCD 16x2
× 1
#include <Wire.h>
#include <Rtc_Pcf8563.h>
void setup()
{
//clear out the registers
rtc.initClock();
//set a time to start with.
//day, weekday, month, century(1=1900, 0=2000), year(0-99)
rtc.setDate(14, 6, 3, 1, 10);
//hr, min, sec
rtc.setTime(1, 15, 0);
}
void loop()
{
//both format functions call the internal getTime() so that the
//formatted strings are at the current time/date.
Serial.print(rtc.formatTime());
Serial.print("\r\n");
Serial.print(rtc.formatDate());
Serial.print("\r\n");
delay(1000);
}
4. The code
Now you can use your clock loading this sketch on your Arduino:
#include <Wire.h>
#include <Rtc_Pcf8563.h>
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.print(" Arduino Clock!");
while(1500 - millis() > 0);
pinMode(13, OUTPUT);
}
SCHEMATICS
CODE
void setup()
{
//clear out the registers
rtc.initClock();
//set a time to start with.
//day, weekday, month, century(1=1900, 0=2000), year(0-99)
rtc.setDate(14, 6, 3, 1, 10);
//hr, min, sec
rtc.setTime(1, 15, 0);
}
void loop()
{
//both format functions call the internal getTime() so that the
//formatted strings are at the current time/date.
Serial.print(rtc.formatTime());
Serial.print("\r\n");
Serial.print(rtc.formatDate());
Serial.print("\r\n");
delay(1000);
}
193) Arduino 7 Segment LED Display Using a Shift Register
× 1
74HC595 Shift Register
× 1
× 2
× 1
× 8
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
void setup() {
// initialize I/O pins
pinMode(dataPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop() {
decPt = !decPt; // display decimal point every other pass through loop
× 1
× 1
× 1
Maxim Integrated
MAX7219/MAX7221 LED Display
Drivers × 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
CODE
#include <LedControl.h>
LedControl lc=LedControl(DIN,CLK,CS,1);
void setup()
{
lc.shutdown(0,false);
lc.setIntensity(0,5);
lc.clearDisplay(0);
Serial.begin(9600);
}
void loop()
{
if(Serial.available() > 0)
{
data = Serial.read();// it returns ascii value if we send one in the phone
if(data < 96)
{
if(temp==0)
{
row=data-48;
temp=1;
}
else
col=data-48;
}
else if(data=='n')
{
lc.setLed(0,row,col,true);
Serial.println('n');
Serial.println(row);
Serial.println(col);
temp=0;
}
else if(data=='f')
{
lc.setLed(0,row,col,false);
Serial.println('f');
Serial.println(row);
Serial.println(col);
temp=0;
}
else if(data=='r')
lc.clearDisplay(0);
}
× 1
SCHEMATICS
CODE
/**
Peça musical executada pela função Tone do Arduino. Execução monofônica. (Musical
piece performed by Arduino Tone function. Monophonic playback.)
Título(Title): Brasileirinho.
Música (Music): Waldir Azevedo.
Arranjo (Arrangement): Glauber Santiago.
Circuito (Circuit): Autofalante de 8 ohm no pino 4 (8 ohm speaker on digital pin 8).
**/
void setup() {
pinMode(4, OUTPUT);
doPerformance();
}
void loop() {
}
void doPerformance() {
tone(4, 494);
delay(102 * msPerTick);
noTone(4);
delay(154 * msPerTick);
tone(4, 494);
delay(205 * msPerTick);
noTone(4);
delay(307 * msPerTick);
tone(4, 494);
delay(102 * msPerTick);
noTone(4);
delay(410 * msPerTick);
tone(4, 392);
delay(205 * msPerTick);
noTone(4);
delay(307 * msPerTick);
tone(4, 494);
delay(102 * msPerTick);
noTone(4);
delay(154 * msPerTick);
tone(4, 587);
delay(205 * msPerTick);
noTone(4);
delay(819 * msPerTick);
tone(4, 294);
delay(205 * msPerTick);
noTone(4);
delay(819 * msPerTick);
tone(4, 147);
delay(205 * msPerTick);
noTone(4);
delay(307 * msPerTick);
tone(4, 988);
delay(512 * msPerTick);
noTone(4);
tone(4, 988);
delay(512 * msPerTick);
noTone(4);
tone(4, 988);
delay(384 * msPerTick);
tone(4, 196);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 196);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 196);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 196);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 196);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 196);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(128 * msPerTick);
tone(4, 294);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 880);
delay(256 * msPerTick);
noTone(4);
tone(4, 831);
delay(128 * msPerTick);
tone(4, 392);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 233);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(256 * msPerTick);
noTone(4);
tone(4, 294);
delay(256 * msPerTick);
noTone(4);
tone(4, 233);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(256 * msPerTick);
noTone(4);
tone(4, 294);
delay(256 * msPerTick);
noTone(4);
tone(4, 233);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(256 * msPerTick);
noTone(4);
tone(4, 294);
delay(256 * msPerTick);
noTone(4);
tone(4, 233);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 294);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(128 * msPerTick);
tone(4, 196);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(128 * msPerTick);
tone(4, 185);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 165);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 196);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(128 * msPerTick);
tone(4, 175);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 156);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 196);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(128 * msPerTick);
tone(4, 185);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 165);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 988);
delay(128 * msPerTick);
tone(4, 147);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 988);
delay(256 * msPerTick);
noTone(4);
tone(4, 932);
delay(256 * msPerTick);
noTone(4);
tone(4, 880);
delay(256 * msPerTick);
noTone(4);
tone(4, 831);
delay(128 * msPerTick);
tone(4, 98);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(256 * msPerTick);
noTone(4);
tone(4, 247);
delay(256 * msPerTick);
noTone(4);
tone(4, 233);
delay(256 * msPerTick);
noTone(4);
tone(4, 220);
delay(256 * msPerTick);
noTone(4);
tone(4, 208);
delay(256 * msPerTick);
noTone(4);
tone(4, 196);
delay(256 * msPerTick);
noTone(4);
tone(4, 185);
delay(256 * msPerTick);
noTone(4);
tone(4, 165);
delay(256 * msPerTick);
noTone(4);
tone(4, 147);
delay(256 * msPerTick);
noTone(4);
tone(4, 98);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
noTone(4);
tone(4, 698);
delay(128 * msPerTick);
tone(4, 294);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 740);
delay(256 * msPerTick);
noTone(4);
tone(4, 698);
delay(256 * msPerTick);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 220);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
noTone(4);
tone(4, 698);
delay(256 * msPerTick);
noTone(4);
tone(4, 740);
delay(256 * msPerTick);
noTone(4);
tone(4, 698);
delay(128 * msPerTick);
tone(4, 294);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(256 * msPerTick);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
noTone(4);
tone(4, 698);
delay(128 * msPerTick);
tone(4, 220);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 740);
delay(256 * msPerTick);
noTone(4);
tone(4, 698);
delay(256 * msPerTick);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 294);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 740);
delay(256 * msPerTick);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
noTone(4);
tone(4, 587);
delay(128 * msPerTick);
tone(4, 196);
delay(128 * msPerTick);
noTone(4);
noTone(4);
tone(4, 784);
delay(256 * msPerTick);
noTone(4);
tone(4, 740);
delay(256 * msPerTick);
noTone(4);
tone(4, 659);
delay(256 * msPerTick);
...
This file has been truncated, please download it to see its full contents.
196) Arduino sCOOp-4-b1l1tY Meter
× 1
× 8
Resistor 10k ohm
× 2
× 2
Capacitor 100 µF
× 1
LED (generic)
× 8
Hydrargyrum-switch
I have used a mercury switch as it × 1
is more sensitive, but any similar
tilt switch would do
Rotary potentiometer (generic)
× 1
9V battery (generic)
× 1
9V Battery Clip
× 1
Breadboard (generic)
a larger one would be nice but the
× 1
project fits on the small one
included un the starter kit
Arduino Proto Shield
This or any other shields that fit
UNO are necessary if you want to 1
×
build the physical device (if you
just like to build the prototype a
breadboard will suffice)
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
(optional) only if you want to create the
actual device, if you build on a breadboard it
won't be necessary
Laser cutter (generic)
(optional) only if you want to create the
actual device, if you build on a breadboard it
won't be necessary
Cardboard, markers, scissors, cutter
to design your display
Wood or plastic board
(optional) To build the case with the laser
cutter
We were having a dinner night as we had done many times, when one
of us, referring to a recent acquaintance said: "I wonder whether it
would be a good idea to have sex with that person...".
The scopability challenge (later renamed sC00p-4-b1l1tY) was set. Was
there such a thing? Could a machine say whether it is a good idea to get
laid? We thought so.
SCHEMATICS
CODE
/**
* Previous versions:
* 0.9
* - testing physical implementation
* - fixed servo angles offsets
* - fixed tuxh random number problem using randomSeed()
* - made all comments in english
* 0.8
* - decided for tilt sensor instead of capacity
* 0.7
* - added tuxh factor
* - added phase LED indicators
* - decided to use capacity sensor for body input
* 0.6
* - added potentiometer feature
* - split file into tabs
* - added function documentation
* - restructured build system so that is modular
* 0.5
* - new concept with servo motor and button release millis difference
*/
#include <Servo.h>
//tilt vars
int tiltPin = 13;
//pot vars
int potPin = A0;
int currentPotValue = 0;
int previousPotValue = 0;
//LEDs vars
int green1 = 8;
int green2 = 9;
int yellow = 10;
int red = 11;
int phase1 = 4;
int phase2 = 5;
int phase3 = 6;
int phaseF = 7;
//Servo vars
int angle;
int servoPin = 12;
Servo myServo;
//switches vars
int buttonSx = 3;
int buttonDx = 2;
int buttonRelSx = 0;
int buttonRelDx = 0;
int currentSx = LOW;
int currentDx = LOW;
bool markSx = false;
bool markDx = false;
//global vars
int programPhase = 0;
int timeFactor = 0;
int potFactor = 0;
int tiltFactor = 0;
int tuxhFactor = 0;
void setup() {
Serial.begin(9600);
runTests();
}
void loop() {
currentSx = digitalRead(buttonSx);
currentDx = digitalRead(buttonDx);
programPhase = 0;
digitalWrite(phase1,HIGH);
× 1
SparkFun Button Pad 4x4 - LED
Compatible
× 1
Maxim Integrated
MAXREFDES99# MAX7219
Display Driver Shield × 1
Unlock each of 16 (4x4) locks to crack the bigger lock. Associated 4x4
buttons can be used to flip the state either horzontally or vertically.
Note either complete row or column of LEDs will flip its state not
individual.
SCHEMATICS
CODE
#include <Keypad.h> //keypad library
#include <LedControl.h>
const byte ROWS = 4; //four rows ; //declare rows
const byte COLS = 4; //four columns //declare columns
char keys[ROWS][COLS] = { //declare 2 dimensional array
to map keys
{'M', 'N', 'O', 'P'},
{'I', 'J', 'K', 'L'},
{'E', 'F', 'G', 'H'},
{'A', 'B', 'C', 'D'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row
pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column
pinouts of the keypad
int FIVER[4][4] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
int r, c, i, j;
int flag = 1;
void setup() {
Serial.begin(9600);
lc.shutdown(0, false); //The MAX72XX is in power-saving mode on startup
lc.setIntensity(0, 1); // Set the brightness to maximum value
lc.clearDisplay(0); // and clear the display
randomSeed(analogRead(0));
}
void loop() {
if (flag == 1) {
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
FIVER[i][j] = random(0, 2);
}
}
flag = 0;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (FIVER[i][j] == 1) {
lc.setLed(0, 2 * i, 2 * j , true);
lc.setLed(0, 2 * i + 1, 2 * j , true);
lc.setLed(0, 2 * i, 2 * j + 1 , true);
lc.setLed(0, 2 * i + 1, 2 * j + 1 , true);
}
if (FIVER[i][j] == 0) {
lc.setLed(0, 2 * i, 2 * j , false);
lc.setLed(0, 2 * i + 1, 2 * j , false);
lc.setLed(0, 2 * i, 2 * j + 1 , false);
lc.setLed(0, 2 * i + 1, 2 * j + 1 , false);
}
}
}
}
if (key == 'A') {
r = 0;
c = 0;
}
if (key == 'B') {
r = 0;
c = 1;
}
if (key == 'C') {
r = 0;
c = 2;
}
if (key == 'D') {
r = 0;
c = 3;
}
if (key == 'E') {
r = 1;
c = 0;
}
if (key == 'F') {
r = 1;
c = 1;
}
if (key == 'G') {
r = 1;
c = 2;
}
if (key == 'H') {
r = 1;
c = 3;
}
if (key == 'I') {
r = 2;
c = 0;
}
if (key == 'J') {
r = 2;
c = 1;
}
if (key == 'K') {
r = 2;
c = 2;
}
if (key == 'L') {
r = 2;
c = 3;
}
if (key == 'M') {
r = 3;
c = 0;
}
if (key == 'N') {
r = 3;
c = 1;
}
if (key == 'O') {
r = 3;
c = 2;
}
if (key == 'P') {
r = 3;
c = 3;
}
if (key) {
for (i = 0; i < 4; i++) {
FIVER[i][c] = 1 - FIVER[i][c];
}
for (i = 0; i < 4; i++) {
FIVER[r][i] = 1 - FIVER[r][i];
}
FIVER[r][c] = 1 - FIVER[r][c];
× 1
Temperature Sensor
× 1
Breadboard (generic)
× 2
Ethernet Cable
× 1
float temp_reading=analogRead(Sensor);
float temperature=temp_reading*(5.0/1023.0)*100;
delay(10);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Temperature in C");
lcd.setCursor(4,1);
lcd.print(temperature);
lcd.write(1);
lcd.print("C");
delay(1000);
}
199) Arduino Button
× 1
LED (generic)
× 1
SparkFun Pushbutton switch
12mm
× 1
× 1
× 1
× 1
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
This project adds user input: a way to send a message to your Arduino, in
the language of hardware.
This sketch includes a great description of the circuit right in the opening
comments. Hook it up like so:
Notice how the LED's part of the circuit looks now. Most breadboards
have power and ground rails running their entire length. That makes it
easier to hook up circuits with just a single wire for each running back to
your controller. So, both the resistor from the button and the LED are
hooked back into this ground rail – instead of taking up both of the
Arduino's GND pins.
The resistor we've just added is a pulldown resistor. Our code is going to
check to see whether or not our digital pin 2 is connected to power, via the
button-press. But while unconnected, the pin's value floats somewhere
between HIGH (powered) and LOW (grounded). So, we let a bit of power
flow to the ground pin all the time, through this 10 kΩ resistor, which
"pulls it down" LOW. But when the button is pressed, power starts
flowing between the 5V pin and pin 2, so it goes HIGH.
CODE
This time, we begin with some declarations of different variables that we'll
be using. In the Blink sketch, if you wanted to change which pin the LED
was on, you had to change pin 13 in three different places. This time, we
tell the Arduino that we'll be using "buttonPin" to represent pin 2, and
"ledPin" to represent pin 13. Now, anytime we swap things around
physically, we just need to change that pin number in one place.
Those variables are going to stay the same the whole time the program is
running, so we call them constants – hence the const int. The other
variable we have will change to reflect our button-pressing, so it's just a
plain int.
This time, we've got INPUTs (button) and OUTPUTs (LED) in the setup
section.
In our loop, the first thing we do is check pin 2 to see whether it's HIGH or
LOW, using digitalRead. Then, depending on the result, we use an if/else
statement to trigger the right action. If it's HIGH (button pressed), set the
LED HIGH as well. Else (otherwise), set the LED LOW.
FYI, you can have more than two conditions – in which case, you tell it
"if the button is on, then turn the LED on; else if the button is not pressed,
then turn the LED off; else (say the button has ceased to exist or
Schrödinger is visiting) shrug your shoulders and do nothing."
Alternate circuit
There's a slightly simpler way to hook up this circuit, using the Arduino's
built-in pullup resistors. As you might suspect, these are the opposite of
pulldown resistors: they let a small amount of power flow between the
voltage source and the pin, without you making any physical connections,
so that the pin is normally held HIGH unless you've connected it to
ground. Super convenient!
All you'll need to do is change the button's type to INPUT_PULLUP, and
then connect the button directly to pins d2 and GND – no external resistor
needed.
As you might suspect, this swaps the Arduino's behavior. Since the pin is
normally HIGH now, the LED will stay on until you press the button. So,
you can switch around your conditions:
if (buttonState == LOW) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
Adapt this
So, in this case we used a button, but that's just one kind of digital input!
What else can you use?
Switch – Add physical control to toggle different sections of code.
Reed switch – Sense whether a door is open or closed, using these two-
part magnetic switches.
Wires – You don't even need a "real" button... tape two wires or pieces of
metal to different surfaces and detect when they come into contact. I once
built a horrible instrument this way, using weighted tinfoil balls to connect
two wires as a primitive switch.
Also, see the code below for a LATCHING / TOGGLE version – a button
that stays "pressed" until you hit it again.
SCHEMATICS
arduino-button.png
arduino-button-with-pullup.png
CODE
Button": Arduino example sketch
/*
Button
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board
attached to pin 13.
*/
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);
LatchingButtonC/C++
A latching button: push once, LED turns on. Push again, LED turns
off. Includes a simple debouncer, so you don't have to worry too much
about how quickly you let go.
/*
Button
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board
attached to pin 13.
This example code is in the public domain.
*/
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);
Buzzer
× 1
flame sensor
× 1
Build your Fire Alarm System at home with Arduino UNO. In this
tutorial, you will learn all steps to DIY Arduino fire alert system by
yourself. In this project, we need IR based flame sensor to detect firelight,
and it gives a signal to Arduino where buzzer connected to provide us with
the output as fire alert.
There is two type of flame sensors available one is Analog and other
Digital. Some sensor has both feature you can use easily just need little bit
changes on the sketch, not an issue at all. We will use both sensors and
here will be both source code available in the relevant section.
Arduino Fire Alarm System:
Build fire alarm or fireplace detector the use of Flame sensor and Arduino
board. The sensor mainly detects IR (Infra purple) light wavelength
between 760 nm – 1100 nm (nanometer) that emitted from fire flame.
Most of the fire sensors got here with the YG1006 sensor which is an
excessive velocity and excessive sensitive NPN silicon photograph
transistor. It’s miles included with black epoxy, for the reason that sensor
is touchy to infrared radiation. Through using this concept assignment you
can recognize the way to screen and alert approximately hearth flame, it is
maximum appropriate for fireplace combating robotic, fire alarm and so
forth.
What you will need:
Arduino UNO ( Any)
Flame Sensor.
Buzzer.
Jumper wires.
9V supply.
The cost is around about ten bucks for this fire alarm system. You can but
all the stuff from any online site like Amazon, eBay, Aliexpress…
Flame Sensor circuit diagram:
Now you need to wiring all the components with each other correctly. See
below for both type of sensors.
If you have Digital sensor connect as per shown in the image.
In case you have A0 (Analog sensor) then wiring will be as in the picture.
void setup() {
pinMode(Buzzer, OUTPUT);
pinMode(FlamePin, INPUT);
Serial.begin(9600);
}
void loop() {
Flame = digitalRead(FlamePin);
if (Flame== HIGH)
{
Serial.println("HIGH FLAME");
digitalWrite(Buzzer, HIGH);
}
else
{
Serial.println("No flame");
digitalWrite(Buzzer, LOW);
}
}
Source Code for A0 Analog flam sensor.
// http://www.mrmodder.com visits for more Arduino Projects //
const int analogPin = A0; // Flame Sensor (A0) to Arduino analog input
pin A0
const int BuzzerPin = 13; // Buzzer output pin
const int threshold = 400; // Flame level threshold (You can vary the
value depends on your need)
void setup() {
pinMode(BuzzerPin, OUTPUT);
// initialize serial communications:
<b>Serial</b>.begin(9600);
}
void loop() {
// read the value of the Flame Sensor:
int analogValue = analogRead(analogPin);
<b>Serial</b>.println(analogValue); //serial print the FLAME sensor
value
delay(1);
}
Upload the relevant code to Arduino Board test flame sensor it can detect
fire from according to my testing maximum 3 feet. However, it depends
on sensor quality it may be different on your sensor.
SCHEMATICS
CODE
int Buzzer = 13; // Use buzzer for alert
int FlamePin = 2; // This is for input pin
int Flame = HIGH; // HIGH when FLAME Exposed
void setup() {
pinMode(Buzzer, OUTPUT);
pinMode(FlamePin, INPUT);
Serial.begin(9600);
void loop() {
Flame = digitalRead(FlamePin);
if (Flame== HIGH)
{
Serial.println("HIGH FLAME");
digitalWrite(Buzzer, HIGH);
}
else
{
Serial.println("No flame");
digitalWrite(Buzzer, LOW);
}
}
201) How to Build a DIY Arduino Smart Home Hub with 1Sheeld
1Sheeld
× 1
Ultrasonic Sensor - HC-SR04
(Generic) × 1
× 1
5 mm LED: Red
× 1
× 1
× 1
× 1
Slide Switch
× 1
18650 battery
× 2
× 1
× 19
IR transmitter diode
× 1
IR receiver module
× 1
Apple iPhone
× 1
Android device
× 1
glue gun
tape
cutter knife
Ruller
APPS AND ONLINE SERVICES
1Sheeld iOS/Android App
OPTIONAL:
To reduce the library compiled size and limit its memory usage, you
can specify which shields you want to include in your sketch by
defining CUSTOM_SETTINGS and the shields respective INCLUDE_ define.
*/
/* Include IR library */
#include <IRremote.h>
/* Initia IR object */
IRsend irsend;
// AC on/off at mp 23
unsigned int power[] = {4712, 2580, 384, 376, 380, 952, 380, 976, 356, 396, 360, 976, 356,
376, 380, 396, 356, 396, 360, 396, 356, 976, 356, 400, 356, 396, 356, 400, 356, 976, 356,
396, 360, 396, 356, 396, 360, 396, 356, 976, 356, 400, 356, 396, 356, 400, 356, 976, 356,
376, 380, 396, 356, 400, 356, 396, 356, 976, 360, 396, 356, 396, 360, 396, 356, 400, 356,
396, 356, 400, 356, 396, 356, 400, 356, 976, 356, 396, 360, 396, 356, 396, 360, 976, 356,
396, 356, 400, 356, 396, 360, 972, 360, 396, 360, 396, 356, 396, 356, 976, 360, 972, 360,
396, 356, 400, 356, 396, 356, 976, 356, 400, 356, 396, 360, 396, 356, 396, 360, 396, 356,
976, 360, 972, 360, 976, 356, 396, 360, 956, 356, 20116, 4676, 6568, 9276, 5012, 384, 396,
356, 396, 360, 396, 356, 400, 356, 396, 360, 396, 356, 396, 356, 400, 356, 396, 360, 396,
356, 396, 360, 396, 356, 976, 356, 976, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396,
356, 396, 360, 396, 356, 400, 356, 976, 356, 396, 356, 400, 356, 396, 360, 396, 356, 396,
360, 396, 356, 400, 356, 396, 356, 396, 360, 396, 356, 400, 356, 396, 356, 400, 356, 396,
360, 396, 356, 396, 356, 400, 356, 396, 360, 396, 356, 400, 356, 396, 356, 396, 360, 396,
360, 396, 356, 396, 356, 400, 356, 396, 356, 400, 356, 396, 360, 396, 356, 396, 360, 396,
356, 396, 360, 396, 356, 396, 360, 396, 356, 396, 360, 976, 356, 976, 356, 976, 356, 380,
360, 20116, 4672};
// AC mp+ from 23 to 24
unsigned int temp24[] = {4716, 2604, 360, 396, 356, 976, 356, 976, 360, 396, 356, 976,
356, 400, 356, 396, 356, 400, 356, 396, 356, 976, 360, 396, 356, 396, 360, 396, 356, 976,
360, 396, 356, 396, 360, 972, 360, 396, 356, 980, 352, 400, 356, 396, 360, 396, 356, 396,
360, 396, 356, 976, 356, 400, 356, 396, 356, 976, 360, 396, 356, 400, 356, 396, 356, 400,
356, 396, 356, 400, 356, 396, 356, 400, 356, 976, 356, 396, 360, 396, 356, 400, 356, 976,
356, 396, 360, 396, 356, 396, 360, 976, 356, 396, 356, 400, 356, 396, 360, 396, 356, 396,
356, 976, 360, 396, 356, 400, 356, 976, 356, 396, 360, 396, 356, 396, 360, 396, 356, 396,
360, 396, 356, 400, 356, 976, 356, 396, 356, 380, 360, 20104, 4684, 6596, 9276, 5012, 356,
396, 360, 396, 356, 396, 360, 396, 356, 400, 356, 396, 356, 400, 356, 400, 356, 396, 356,
396, 356, 400, 356, 396, 360, 976, 356, 976, 356, 396, 360, 396, 356, 396, 360, 396, 356,
396, 360, 396, 356, 400, 356, 396, 356, 976, 356, 400, 356, 396, 356, 400, 356, 396, 360,
396, 356, 400, 356, 396, 356, 400, 356, 396, 356, 400, 356, 396, 356, 400, 356, 396, 356,
400, 356, 396, 356, 400, 356, 396, 356, 400, 356, 400, 356, 396, 356, 400, 352, 400, 356,
400, 356, 396, 356, 400, 356, 396, 356, 400, 356, 396, 356, 400, 356, 400, 352, 400, 356,
400, 352, 400, 356, 400, 356, 396, 356, 400, 352, 400, 356, 980, 352, 980, 352, 980, 356,
380, 356, 20104, 4684};
// AC mp+ from 24 to 25
unsigned int temp25[] = {4716, 2604, 356, 400, 356, 976, 356, 976, 360, 396, 356, 976,
356, 396, 360, 396, 356, 400, 356, 396, 356, 976, 360, 396, 356, 396, 360, 396, 356, 976,
356, 400, 356, 396, 356, 400, 356, 396, 356, 976, 360, 396, 356, 396, 360, 396, 356, 976,
360, 396, 356, 396, 360, 396, 356, 396, 360, 972, 360, 396, 356, 400, 356, 396, 356, 400,
356, 396, 356, 400, 356, 396, 360, 396, 356, 976, 356, 400, 356, 396, 356, 400, 356, 976,
356, 396, 360, 396, 356, 396, 360, 976, 356, 396, 360, 396, 356, 396, 356, 976, 360, 396,
356, 976, 356, 400, 356, 396, 360, 972, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396,
356, 400, 356, 976, 356, 396, 360, 976, 356, 380, 356, 20108, 4684, 6592, 9276, 5012, 356,
396, 360, 396, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396, 356,
400, 356, 396, 356, 396, 360, 976, 356, 976, 356, 396, 360, 396, 356, 396, 360, 396, 356,
400, 356, 396, 356, 400, 356, 396, 360, 976, 356, 396, 356, 396, 360, 396, 356, 400, 356,
396, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396, 356, 396, 360,
396, 356, 400, 356, 396, 356, 400, 356, 396, 356, 400, 356, 396, 356, 400, 356, 396, 360,
396, 356, 396, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396, 356, 396, 360, 396, 360,
396, 356, 396, 356, 400, 356, 396, 356, 400, 356, 396, 360, 972, 360, 976, 356, 976, 356,
380, 356, 20080, 4712};
/* sensor variabes */
int temp;
int gas_degree;
bool gas_HighLevelWarning = false;
bool gas_emailSent = false;
bool alarm_isPressed = false;
bool interruptPin_isPressed = false;
/* required variables for the publishing function */
char tempChar[4];
char gas_degree_char[4];
/* The topics*/
const char * ultrasonic = "ultrasonic";
const char * cam_dir = "cam/direction";
const char * cam_cap = "cam/capture";
const char * light = "light";
const char * temperature = "temp";
const char * gas = "gas";
const char * speak = "speak";
const char * ac = "ac";
const char * ac_auto = "auto";
/* Start communication. */
OneSheeld.begin();
/* Disconnect from broker. */
IOT.disconnect();
/* Subscribions to topics */
IOT.subscribe(ultrasonic);
IOT.subscribe(cam_dir);
IOT.subscribe(cam_cap);
IOT.subscribe(light);
IOT.subscribe(speak);
IOT.subscribe(ac);
IOT.subscribe(ac_auto);
void loop()
{
/************************************************* Ultrasonic Sensor
*****************************************************/
/* Get the current distance from the ultrasonic */
distance = getUltrasonicDistance();
//terrminal.println("");
//Terminal.print("distance:");
//Terminal.println(distance);
if ( (distance < 30) && (distance > 0) && (isAuthorized == true) )
{
isAuthorized = false;
start_time = millis();
TextToSpeech.say("please enter your fingerprint");
OneSheeld.delay(1400);
if(published_door_status_opened == false)
{
/* Publish door status as opened */
IOT.publish(ultrasonic, "your door is opened", QOS_0);
/* Take a photo for that stranger using the phone's front camera */
Camera.frontCapture();
/* increase the AC temperature from 24 to 25C if the time passed since on is >= 4sec */
if ( ac_time_passed >= (60000 * 4) && (temp25_isSent == false))
{
/* increase temp to 25 */
irsend.sendRaw(temp25, sizeof(power) / sizeof(temp25[0]), khz); //Note the approach used
to automatically calculate the size of the array.
temp25_isSent = true;
//Compare the last command received by the Arduino Voice Recognition Shield with the
command "off"
else if (!strcmp("light off", VoiceRecognition.getLastCommand()))
{
//Then turn the light off
digitalWrite(light_pin, LOW);
}
//Compare the last command received by the Arduino Voice Recognition Shield with the
command "play music"
else if (!strcmp("play music", VoiceRecognition.getLastCommand()))
{
// play the music.
MusicPlayer.play(0);
// Terminal.println("play music now");
}
//Compare the last command received by the Arduino Voice Recognition Shield with the
command "pause music"
else if (!strcmp("pause music", VoiceRecognition.getLastCommand()))
{
// pause the music.
MusicPlayer.pause();
// Terminal.println("pause music now");
}
}
/* Read temperature */
temp = (int)DHT.temperature;
gas_HighLevelWarning = false;
alarm_isPressed = false;
gas_emailSent = false;
}
if(gas_emailSent == false)
{
/* Send an email with the last picture in OneSheeld folder. */
Email.send("[email protected]", "Dangerous Gas Alert!", "Hi, There is a
dangerous level of gas in your home! Please check your dashboard.");
/*
######################################################################################
*/
void newMessage(char * incomingTopic, char * payload, byte qos, bool retained)
{
/**************************************************************************************
/* check for the speak topic */
if (!strcmp(speak, incomingTopic))
{
/* If message is speak */
if (!strcmp("speak", payload))
{
// this is for testing
digitalWrite(test_led , HIGH);
/* turn on light */
digitalWrite(light_pin , HIGH);
/* If message is off */
else if (!strcmp("off", payload))
{
// this is for testing
digitalWrite(test_led , HIGH);
/* Take a photo for that stranger using the phone's front camera */
Camera.frontCapture();
/* If message is 1 */
else if (!strcmp("1", payload))
{
/* If message is 1 */
else if (!strcmp("2", payload))
{
/* Start servo at the 90 degree angle */
servo_for_loop(CamServo.read() , 90);
}
/* If message is 3 */
else if (!strcmp("3", payload))
{
/* Start servo at the 45 degree angle */
servo_for_loop(CamServo.read() , 45);
}
/* If message is 4 */
else if (!strcmp("4", payload))
{
/* Start servo at the 0 degree angle */
servo_for_loop(CamServo.read() , 0);
}
}
/**************************************************************************************
/* check for the ac topic */
if (!strcmp(ac, incomingTopic))
{
/* If message is on */
if (!strcmp("on", payload))
{
// this is for testing
digitalWrite(test_led , HIGH);
/* turn on ac */
irsend.sendRaw(power, sizeof(power) / sizeof(power[0]), khz); //Note the approach used to
automatically calculate the size of the array.
/* If message is off */
else if (!strcmp("off", payload))
{
// this is for testing
digitalWrite(test_led , HIGH);
/* turn on ac */
irsend.sendRaw(power, sizeof(power) / sizeof(power[0]), khz); //Note the approach used to
automatically calculate the size of the array.
/* turn on ac */
ac_start_time = millis();
/* If message is off */
else if (!strcmp("off", payload))
{
// this is for testing
digitalWrite(test_led , HIGH);
/**************************************************************************************
/* A function that makes the whole operation of the ultrasonic and returning the detected
distance */
int getUltrasonicDistance(void)
{
/* Variable to save the sound wave travel time in microseconds */
long duration;
/* Reads the echoPin, returns the sound wave travel time in microseconds */
duration = pulseIn(echoPin, HIGH);
/**************************************************************************************
void servo_for_loop(int start_angle , int stop_angle)
{
if( start_angle < stop_angle )
{
for( ; start_angle <= stop_angle ; start_angle++ )
{
CamServo.write(start_angle);
delay(25);
}
}
else if ( start_angle > stop_angle )
{
for( ; start_angle >= stop_angle ; start_angle-- )
{
CamServo.write(start_angle);
delay(25);
}
}
}
/**************************************************************************************
void interruptPin_isr()
{
interruptPin_isPressed = true;
}
Capacitor 10 µF
× 1
Microchip ATtiny85
× 1
× 1
LED (generic)
× 1
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
CODE
#include <SoftwareSerial.h> //Software Serial Port
#define RxD 1
#define TxD 2
#define DEBUG_ENABLED 1
SoftwareSerial blueToothSerial(RxD,TxD);
int led = 4;
void setup()
{
pinMode(RxD, INPUT);
pinMode(TxD, OUTPUT);
setupBlueToothConnection();
pinMode(led,OUTPUT);
digitalWrite(led,HIGH);
void loop()
{ int count=0;
char recvChar;
while(1){
//check if there's any data sent from the remote bluetooth shield
if(blueToothSerial.available()){
recvChar = blueToothSerial.read();
count++ ;
if(count%2==0)
digitalWrite(led,HIGH);
else
digitalWrite(led,LOW);
}
}
}
void setupBlueToothConnection()
{
blueToothSerial.begin(9600); //Set BluetoothBee BaudRate to default
baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in
slave mode
blueToothSerial.print("\r\n+STNA=HC-05\r\n"); //set the bluetooth name
as "HC-05"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to
connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should
be forbidden here
× 1
Mjolnir is Thor's trusty hammer, and will always return to his hand
when thrown (as depicted in the Marvel Cinematic Universe, anyhow).
So how do we build our own legendary flying hammer? With Arduinos,
of course!
The heart of this hammer is not a dying star, but rather a micro racing
drone. The hammer itself is a foam and balsa wood frame built around
the quadcopter with plenty of open areas for air flow.
The true test of worthiness, however, is throwing Mjolnir and
summoning it back to your hand. That trick is done with an Arduino
Uno controlling the quadcopter transmitter via digital potentiometers.
Push buttons mounted to a wrist brace control pitch and throttle, and an
accelerometer maps hand movements to the quadcopter's roll. With
some patience, this makes Mjolnir controllable with one hand, leaving
your other hand free to catch Thor's hammer!
This is not a beginner project, and a lot of the hammer's design was
modified on the fly (pun intended), so the final product doesn't map
perfectly to the provided CAD files. There's also a ton of variability in
receivers and transmitters, so you will need strong troubleshooting and
trial-and-error skills, and even then Mjolnir handles like a fat cow in
the air. You have been warned!
Hammer Materials:
The hammer body is mostly made of foam sheet is from Dollar Tree;
you'll have to peel off the paper lamination before you begin
constructing the hammer! A rectangular frame made of balsa wood
holds the quadcopter in place, it's made by laminating two 1/8" thick
parts with Titebond III for strength. The adhesives used are 3M 78 for
gluing foam to foam, hot glue for everything else, and foam safe CA
glue to fix boo-boos after crashes.
The svg used for laser cutting the parts are all on this page. For the
foam, all the angled edges were beveled to 22.5 degrees with a utility
knife before being glued together. The faces of the hammer are hot
glued to the head because the edges didn't line up, and a fillet of glue
was needed for structure. The handle of the hammer was not laser cut,
because it's just a 4"x10" rectangle of foam rolled up and hot glued
shut along the seam.
The frame is the tricky bit, the included files are an older design where
the quadcopter was higher up in the hammer. It turns out that the props
need to be very close to the bottom of the hammer head to work
properly. So in the final design, just the outer rectangular shape of the
frame is kept and the prop guards of the quadcopter are incorporated
into the structure. The quadcopter used here is an Emax Babyhawk
running on a 3S 260mAh Lipo battery, which is tucked into a box
above the handle (which was ultimately made to fit the dimensions of
the battery by hand, rather than the laser cut part). The handle and
battery box are hot glued to the bottom of the quadcopter.
Setting up the Babymax is a whole other tutorial on it's own which is
covered extensively elsewhere. I used a Spektrum DSMX racing
receiver, which is hot glued to the Babymax camera mount, with the
camera gutted since we don't need FPV of the inside of a hammer and
it saves a few grams of weight. You'll notice the hammer is two
separate parts, with a "base" hot glued directly to the prop guards of the
quadcopter, and a top "case" that rests on top. Two rectangular strips of
foam were glued to the base to help guide the case on top of the base,
and a small set of neodymium magnets secures the case to the base.
Don't forget the paint! Normal spray paints will eat away your beautiful
foam creation, so you'll need to use an acrylic paint. If you're fancy,
use an airbrush, if you're just a little less fancy like me, use an acrylic
based spray paint like Liquitex.
Opening the Transmitter
This technique should work on any RC transmitter with potentiometer
joysticks. We're going to be adding 3 wire connectors so the joysticks
can be bypassed and the transmitter directly controlled by an Arduino
via AD5206 10K digital potentiometer.
Splice in to the Potentiometers
I used servo extension cables, that way the transmitter can easily be
used as normal or connected to an Arduino. Make sure you label your
wires! Drill some holes into the transmitter back for the wires to come
out from, and close the transmitter back up.
This switch is mapped as the "arm" switch in betaflight. I'll also be
adding an extension wire to this
Connect to Arduino via AD5206
Check out the code included with this tutorial! Refer to your datasheet,
the code, and your transmitter to work out wiring the potentiometer to
the transmitter. Match the transmitter pot's ground, wiper, and v+ to b,
w, and a of the digital pot. This Arduino tutorial is a good
resource. Find a couple push buttons and an LIS3DH accelerometer
(same one used for firebending!) and connect them as shown in the
schematic attached to this tutorial. You'll notice a toggle switch in
parallel to a pushbutton switch as input to pin 6; that represents
whatever you've chosen as the arm switch on your transmitter. The
push button becomes your new arm switch, and the Arduino simply
reads the state of the switch so it knows when to throttle up or down.
Load up the included code, plug your Babyhawk into your computer
and connect to Betaflight Configurator, and do a system test! You
should be able to see the receiver values change by pressing the buttons
and tilting the accelerometer.
Mount the Electronics
I used a wrist brace to mount the throttle button, pitch button, and
accelerometer. They connect to the Arduino Uno through about 3 feet
of wire. The transmitter, Arduino Uno, and digital pot are all just taped
to a board of wood with foam mounting tape. Everything fits into a
fashionable red sling backpack!
Are You Worthy?!
Mjolnir flies about as well as you'd expect a brick shaped object to fly.
Any slight gusts of wind knock the poor thing around like crazy, and
there isn't really a good way to launch or land. Almost every time the
hammer "lands", the handle will probably break off. But that's what
glue's for! After a solid day of filming I managed the successfully
"throw" and catch Mjolnir about twice, but both times the shock of
catching the hammer ended up breaking it. What I'm saying is there is
lots of room for improvement here! (Especially since I used the stock
PID settings XD)
SCHEMATICS
CODE
// include the SPI library:
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
// set pin 10 as the slave select for the AD5206 digital pot:
const int slaveSelectPin = 10;
int accelValue = 0;
int rollValue = 0;
int rollValuePrev = 0;
int throttleValue = 0;
int pitchValue = 0;
// two buttons for pitch and throttle
const int pitchPin = 7;
const int throtPin = 6;
int throttle = 0;
int roll = 1;
int pitch = 2;
int flag = 0;
int pitchFlag = 0;
//value must be determined empirically:
int maxThrottle = 120;
// I2C
Adafruit_LIS3DH lis = Adafruit_LIS3DH();
void setup() {
// set the slaveSelectPin as an output:
pinMode(slaveSelectPin, OUTPUT);
pinMode(pitchPin, INPUT_PULLUP);
pinMode(throtPin, INPUT);
// initialize SPI:
SPI.begin();
Serial.begin(9600);
Serial.println("LIS3DH test!");
if (! lis.begin(0x18)) { // change this to 0x19 for alternative i2c address
Serial.println("Couldnt start");
while (1);
}
Serial.println("LIS3DH found!");
lis.setRange(LIS3DH_RANGE_2_G); // 2, 4, 8 or 16 G!
Serial.print("Range = "); Serial.print(2 << lis.getRange());
Serial.println("G");
//initialize the pots at reasonable values
digitalPotWrite(pitch, 60);
digitalPotWrite(throttle, 51);
}
void loop() {
lis.read();
accelValue = lis.z;
//values must be determined empirically:
accelValue = constrain(accelValue, -16383, 16383);
rollValue = map(accelValue, -16383, 16383, 51, 204);
//hand tilt controls roll
digitalPotWrite(roll, rollValue);
pitchValue = digitalRead(pitchPin);
throttleValue = digitalRead(throtPin);
× 1
× 1
× 1
Geared DC Motor, 12 V
× 2
wheels 60cm
× 2
castor wheel
× 1
NECESSARY TOOLS AND MACHINES
Drill, Screwdriver
APPS AND ONLINE SERVICES
Blynk
Arduino IDE
#include <SoftwareSerial.h>
SoftwareSerial SwSerial(9, 10); // RX, TX
const int enb=6;
const int in4=12;
const int in3=11;
const int ena=3;
const int in2=5;
const int in1=4;
#include <BlynkSimpleSerialBLE.h>
#include <SoftwareSerial.h>
char auth[] = "5b4640909c9b4c818d9afdffc7a1ba08";
BLYNK_WRITE(V0)
{
int button=param.asInt();
if(button==1)
{
digitalWrite(in4,HIGH);
digitalWrite(in3,LOW);
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
}
else if(button==0)
{
digitalWrite(in4,LOW);
digitalWrite(in3,HIGH);
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
}
}
BLYNK_WRITE(V1)
{
int pinValue = param.asInt(); // assigning incoming value from pin V1 to a
variable
analogWrite(enb,pinValue);
}
BLYNK_WRITE(V2)
{
int pinValue = param.asInt(); // assigning incoming value from pin V1 to a
variable
analogWrite(ena,pinValue);
}
BLYNK_WRITE(V3)
{
int pinValue=param.asInt();
if(pinValue==1)
{
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
digitalWrite(in4,LOW);
digitalWrite(in3,HIGH);
analogWrite(ena,255);
analogWrite(enb,255);
delay(500);
}
else
{
digitalWrite(in1,HIGH);
digitalWrite(in2,HIGH);
digitalWrite(in4,HIGH);
digitalWrite(in3,HIGH);
analogWrite(ena,0);
analogWrite(enb,0);
delay(200);
}
}
BLYNK_WRITE(V4)
{
int pinValue=param.asInt();
if(pinValue==1)
{
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
digitalWrite(in4,HIGH);
digitalWrite(in3,LOW);
analogWrite(ena,255);
analogWrite(enb,255);
delay(500);
}
else
{
digitalWrite(in1,HIGH);
digitalWrite(in2,HIGH);
digitalWrite(in4,HIGH);
digitalWrite(in3,HIGH);
analogWrite(ena,0);
analogWrite(enb,0);
delay(200);
}
}
void setup()
{
// Debug console
Serial.begin(9600);
SerialBLE.begin(9600);
Blynk.begin(SerialBLE, auth);
void loop()
{
Blynk.run();
}
Arduino MKR1000
× 1
LED (generic)
× 3
Breadboard (generic)
× 1
× 1
× 1
APPS AND ONLINE SERVICES
Arduino Web Editor
CODE
/*
*/
#include <GoPRO.h>
#define CONNECT_PRESSED 1
#define ON_PRESSED 2
#define CAPTURE_PRESSED 3
void setup() {
// put your setup code here, to run once:
pinMode(buttonConnect, INPUT_PULLUP);
pinMode(buttonOn, INPUT_PULLUP);
pinMode(buttonCapture, INPUT_PULLUP);
pinMode(connectLED, OUTPUT);
pinMode(onLED, OUTPUT);
pinMode(captureLED, OUTPUT);
digitalWrite(connectLED, LOW);
digitalWrite(onLED, HIGH);
digitalWrite(captureLED, LOW);
void loop() {
switch (isButtonPressed()) {
default: break;
case CONNECT_PRESSED:
if (!GoPRO.checkConnection()) {
if (GoPRO.begin(ssid, pass)) {
digitalWrite(connectLED, HIGH);
else {
digitalWrite(connectLED, LOW);
else {
digitalWrite(connectLED, HIGH);
break;
case ON_PRESSED:
if (GoPRO.checkConnection()) {
onStatus = !onStatus;
if (onStatus) {
if (GoPRO.turnOn())
digitalWrite(onLED, HIGH);
}
else {
if (GoPRO.turnOff())
digitalWrite(onLED, LOW);
break;
case CAPTURE_PRESSED:
if (GoPRO.checkConnection()) {
captureStatus = !captureStatus;
if (captureStatus) {
if (GoPRO.startCapture())
digitalWrite(captureLED, HIGH);
else {
if (GoPRO.stopCapture())
digitalWrite(captureLED, LOW);
}
}
break;
delay(100);
}
int isButtonPressed() {
else return 0;
}
206) Arduino What is Interrupts
COMPONENTS AND SUPPLIES
Arduino UNO & Genuino UNO
× 1
LED (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Code !
const int ledPin = 12; //ledPin
const int buttonPin = 2; //Button to perform interrupt
int x=0, y=0; //some variables to increment
int ledToggle = LOW; //led state
//variables to keep track of the timing of recent interrupts
unsigned long button_time = 0;
unsigned long last_button_time = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(buttonPin), button_ISR, CHANGE);
}
void loop(){
Serial.print("loop " );
Serial.print(x++ );
Serial.println();
delay(500);
}
void button_ISR(){
button_time = millis();
//check to see if increment() was called in the last 250 milliseconds
if (button_time - last_button_time > 250){
Serial.print("Interrupt ");
Serial.print(y++);
Serial.println();
ledToggle = !ledToggle;
digitalWrite(ledPin, ledToggle);
last_button_time = button_time;
}
}
Why that millis() used ?
One common problem with interrupts is they often can trigger multiple
times for a single event. if you press the button just once, y will increment
many times. A button push might seem like a single step, but in reality the
mechanical parts within that button come into contact multiple times
before settling into a particular state. There are several ways to remedy
this. Often you can fix bounce issues with hardware by adding an
appropriate RC filter to smooth the transition. Another option is to
address it in software by temporarily ignoring further interrupts for a
small time frame after the first interrupt is triggered. that's why millis() is
used here.
result
Here controller immediately shifting from loop to interrupt service
routine.This is how an Interrupt can be useful to trigger any important task
in between of normal execution.
Interrupt Priority Levels
What happens when two interrupts occur at the same time? Most AVRs do
not support what we call interrupt priority levels. Should two interrupts
occur simultaneously or there are two or more interrupts waiting in a
queue, the priority is determined by the order of their vector addresses.
Lower vector addresses are serviced first, Reset will take precedence over
all interrupt requests. Again, your datasheet will have more information on
your specific board.
SCHEMATICS
CODE
const int ledPin = 12; //ledPin
const int buttonPin = 2; //Button to perform interrupt
int x=0, y=0; //some variables to increment
int ledToggle = LOW; //led state
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(buttonPin), button_ISR, CHANGE);
}
void loop(){
Serial.print("loop " );
Serial.print(x++ );
Serial.println();
delay(500);
}
void button_ISR(){
button_time = millis();
//check to see if increment() was called in the last 250 milliseconds
if (button_time - last_button_time > 250){
Serial.print("Interrupt ");
Serial.print(y++);
Serial.println();
ledToggle = !ledToggle;
digitalWrite(ledPin, ledToggle);
last_button_time = button_time;
}
}
207) Arduino Air Quality Monitor
× 1
DSM501A Dust sensor module × 1
Alphanumeric LCD, 16 x 2
× 1
LED (generic)
× 5
× 1
int pin2 = 3;
int pin1 = 2;
unsigned long duration1;
unsigned long duration2;
void setup() {
Serial.begin(9600);
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(wLed,OUTPUT);
pinMode(gLed,OUTPUT);
pinMode(yLed,OUTPUT);
pinMode(rLed,OUTPUT);
pinMode(bLed,OUTPUT);
starttime = millis();//get the current time;
lcd.begin(16, 2);
}
void loop() {
duration1 = pulseIn(pin1, LOW);
duration2 = pulseIn(pin2, LOW);
lowpulseoccupancy1 = lowpulseoccupancy1+duration1;
lowpulseoccupancy2 = lowpulseoccupancy2+duration2;
if ((millis()-starttime) > sampletime_ms)//if the sampel time == 30s
{
ratio1 = lowpulseoccupancy1/(sampletime_ms*10.0); // Integer percentage 0=>100
concentration1 = 1.1*pow(ratio1,3)-3.8*pow(ratio1,2)+520*ratio1+0.62; // using spec sheet
curve
lcd.setCursor(0, 0);
lcd.print("PM10 ");
lcd.setCursor(6, 0);
lcd.print(concentration1,3);
Serial.print("concentration1 = ");
Serial.print(concentration1);
Serial.print(" pcs/0.01cf - ");
Serial.print("concentration2 = ");
Serial.print(concentration2);
Serial.print(" pcs/0.01cf - ");
lcd.setCursor(4, 1);
lcd.print("CLEAN");
digitalWrite(wLed, HIGH);
digitalWrite(gLed, LOW);
digitalWrite(yLed, LOW);
digitalWrite(rLed, LOW);
digitalWrite(bLed, LOW);
}
if (concentration1 > 1000 && concentration1 < 10000) {
lcd.setCursor(4, 1);
lcd.print("GOOD");
digitalWrite(wLed, LOW);
digitalWrite(gLed, HIGH);
digitalWrite(yLed, LOW);
digitalWrite(rLed, LOW);
digitalWrite(bLed, LOW);
}
lcd.setCursor(4, 1);
lcd.print("ACCEPTABLE");
digitalWrite(wLed, LOW);
digitalWrite(gLed, LOW);
digitalWrite(yLed, HIGH);
digitalWrite(rLed, LOW);
digitalWrite(bLed, LOW);
}
if (concentration1 > 20000 && concentration1 < 50000) {
lcd.setCursor (0, 1);
for (int i = 0; i < 16; ++i)
{
lcd.write(' ');
}
lcd.setCursor(4, 1);
lcd.print("HEAVY");
digitalWrite(wLed, LOW);
digitalWrite(gLed, LOW);
digitalWrite(yLed, LOW);
digitalWrite(rLed, HIGH);
digitalWrite(bLed, LOW);
}
lcd.setCursor(4, 1);
lcd.print("HAZARD");
digitalWrite(wLed, LOW);
digitalWrite(gLed, LOW);
digitalWrite(yLed, LOW);
digitalWrite(rLed, LOW);
digitalWrite(bLed, HIGH);
lowpulseoccupancy1 = 0;
lowpulseoccupancy2 = 0;
starttime = millis();
}
}
208) Arduino Contyrol AC Water Heater Temperature
× 1
Arduino Nano R3
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
void setup() {
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();
// define arduino PWM as an output
pinMode(SugarPin,OUTPUT);
//define Button as an input with PullUp resistor
// pinMode(Sugar_Pot ,INPUT);
MainMenu();
display.display();
delay(3000);
display.clearDisplay();
display.display();
ControlPanel();
}
void MainMenu()
{
display.setTextSize(3);
display.setTextColor(WHITE);
display.setCursor(20,5);
display.print("Sugar");
display.setCursor(20,35);
display.print("Device");
delay(3000);
}
void UpdateReading()
{
display.setTextSize(3);
display.setCursor(20,30);
display.setTextColor(WHITE);
switch(MenuCounter)
{
case 1:
display.print(Target_T);
break;
case 2:
display.print(Temp);
break;
case 3:
display.print(voltage_perc);
break;
}
display.display();
MenuCounter++;
if(MenuCounter>3){MenuCounter=1;}
}
void ControlPanel()
{
display.clearDisplay();
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
switch(MenuCounter)
{
case 1:
display.setCursor(5,5);
display.print("Sensor T");
break;
case 2:
display.setCursor(5,5);
display.print("Target T");
break;
case 3:
display.setCursor(5,5);
display.print("AC volt%");
break;
}
display.display();
}
void loop()
{
ReadTempSensor();
delay(500);
ControlPanel();
UpdatePWM();
UpdateReading();
}
void UpdatePWM()
{
T_diff=Target_T-Temp;
if(T_diff>=40)
{
HeaterPWM=64;//full voltage;
voltage_perc=100;
}
else if(T_diff<40&&T_diff>=30 )
{
HeaterPWM=54;//full voltage;
voltage_perc=85;
}
else if(T_diff<30&&T_diff>=20 )
{
HeaterPWM=48; //60%
voltage_perc=75;
}
else if(T_diff<20&&T_diff>=10 )
{
HeaterPWM=38; //50%
voltage_perc=50;
}
else if(T_diff<10&&T_diff>=2 )
{
HeaterPWM=30; //30%
voltage_perc=30;
}
else if(T_diff<2 )
{
HeaterPWM=12; //0%
voltage_perc=0;
}
analogWrite(SugarPin,HeaterPWM);
}
void ReadTempSensor()
{
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if ( !ds.search(addr)) {
ds.reset_search();
delay(250);
return;
}
// the first ROM byte indicates which chip
switch (addr[0]) {
case 0x10:
type_s = 1;
break;
case 0x28:
type_s = 0;
break;
case 0x22:
type_s = 0;
break;
default:
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion, with parasite power on at the end
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
× 1
IR receiver (generic)
× 1
IR Remote Control
× 1
× 1
SPDT 5V Relay
× 2
APPS AND ONLINE SERVICES
Arduino IDE
LiquidCrystal lcd(12,10,7,6,5,4);
int RECV_PIN = 11; // the pin where you connect the output pin of IR
sensor
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
lcd.begin(16,2); // Start the LCD
irrecv.enableIRIn(); // Start the IR receiver
pinMode(app1, OUTPUT);
pinMode(app2, OUTPUT);
lcd.setCursor(0,0);
lcd.print("Made by Naman"); // Made by Naman Chauhan
lcd.setCursor(0,1);
lcd.print("Chauhan");
delay(1500);
lcd.clear();
lcd.setCursor(3,0);
lcd.print("Arduino IR"); //Arduino IR Switch Board
lcd.setCursor(2,1);
lcd.print("Switch Board");
delay(1500);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("(1) Fan : OFF"); //Showing intial status on LCD
lcd.setCursor(0,1);
lcd.print("(2) Bulb : OFF");
void loop()
{
if (irrecv.decode(&results)) {
unsigned int value = results.value;
switch(value) {
case code1:
if(status[1] == 1) { // if first app is ON then
digitalWrite(app1, LOW); // turn it off when button is pressed
status[1] = 0; // and set its state as off
lcd.setCursor(10,0); //printing status on LCD
lcd.print("OFF");
}
case code2:
if(status[2] == 1) {
digitalWrite(app2, LOW);
status[2] = 0;
lcd.setCursor(11,1); //printing status on LCD
lcd.print("OFF");
}
else {
digitalWrite(app2, HIGH);
status[2] = 1;
lcd.setCursor(11,1); //printing status on LCD
lcd.print("ON ");
}
break;
case code3:
if(status[1] == 1 && status[2] == 1) {
digitalWrite(app1, LOW);
status[1] = 0;
lcd.setCursor(10,0);
lcd.print("OFF");
digitalWrite(app2, LOW);
status[2] = 0;
lcd.setCursor(11,1);
lcd.print("OFF");
}
else {
digitalWrite(app1, HIGH);
status[1] = 1;
lcd.setCursor(10,0);
lcd.print("ON ");
digitalWrite(app2, HIGH);
status[2] = 1;
lcd.setCursor(11,1);
lcd.print("ON ");
}
}
Serial.println(value);
irrecv.resume(); // Receive the next value
}
}
× 1
Breadboard (generic)
× 1
Resistor 1k ohm
× 4
× 2
Photo resistor
× 4
SCHEMATICS
CODE
//Ingeimaks
#include <Servo.h>
//definiamo i servomotori orizzontale e verticale
Servo servohori;
int servoh = 0;
int servohLimitHigh = 160;
int servohLimitLow = 60;
Servo servoverti;
int servov = 0;
int servovLimitHigh = 160;
int servovLimitLow = 60;
//Pin fotoresistenze
int ldrtopl = 2; //top left
int ldrtopr = 1; //top right
int ldrbotl = 3; // bottom left
int ldrbotr = 0; // bottom right
void setup ()
{
servohori.attach(10);
servohori.write(60);
servoverti.attach(9);
servoverti.write(60);
Serial.begin(9600);
delay(500);
void loop()
{
servoh = servohori.read();
servov = servoverti.read();
//Valore Analogico delle fotoresistenza
int topl = analogRead(ldrtopl);
int topr = analogRead(ldrtopr);
int botl = analogRead(ldrbotl);
int botr = analogRead(ldrbotr);
// Calcoliamo una Media
int avgtop = (topl + topr) ; //average of top
int avgbot = (botl + botr) ; //average of bottom
int avgleft = (topl + botl) ; //average of left
int avgright = (topr + botr) ; //average of right
× 1
× 2
Speaker: 0.25W, 8 ohms
× 1
× 1
× 1
Capacitor 22 µF
× 1
24C512
× 1
ABOUT THIS PROJECT
A doorbell project for Arduino Uno with ATMEGA328P device. The
EEPROM 24C512 is 512Kbits and it can store up to 3 seconds wave
file of 22.050KHz, 8 bits, mono.
The Arduino reads the ROM bytes in a sequential read mode and
stream each byte to the PWM generator at a rate of about 22 KHz. The
I2C bus works at 200 KHz for the purpose of managing to process 22
Kbits per second. Changing the bus frequency changes the speed of the
sound.
The transistors are a push-pull buffer for driving the speaker, any
replacement can be used.
The I2C lib doesn't have a function for sequential read, so I added a
routine.
To load sound file to the eeprom do this:
Convert sound file to .wav PCM 22.050KHz, 8 bits, mono
Change the file name extension from wav to bin.
Load the bin file to the EEPROM Programmer.
SCHEMATICS
CODE
#include <Wire.h>
void setup() {
// put your setup code here, to run once:
pinMode(ring, INPUT_PULLUP);
//PWM Timer0
OCR0A = 64;
TCCR0A = _BV(COM0A1) | _BV(WGM01) | _BV(WGM00); //output in
phase, fast PWM mode
TCCR0B = _BV(CS00); // 16MHz/256 = 64KHz
void loop()
{
unsigned int i;
ringPB=digitalRead(ring);
if(ringPB==LOW) //pushbutton
{
pinMode(audio, OUTPUT);
//go to address 0
Wire.beginTransmission(0x50);
Wire.write((int)(0)); //MSB of eeprom address
Wire.write((int)(0)); // LSB
Wire.endTransmission();
relay
× 1
fan
× 1
computer fan
9V battery (generic)
× 1
× 1
lm35
× 1
ABOUT THIS PROJECT
void setup() {
void loop() {
int okunanDeger = analogRead(A0); //Read analog value
float derece = okunanDeger / 9.31; //centigrade calculated
Serial.println(derece); //centigrade print on screen
delay(1000); // wait 1 sec
if(derece >25)
digitalWrite(role,HIGH); //relay power on
else
digitalWrite(role,LOW); //relay power off
}
× 1
Buzzer
× 1
DC motor (generic)
its not a ordinary motor, it is a micro × 1
vibrating motor that i took from old
celphone.
Jumper wires (generic)
× 1
Slide Switch
Here in this project i used a toggle switch,
but you can use a slide switch . it also work × 1
9V battery (generic)
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
Today in this project we are going to make a smart blind stick for
visually impaired persons.
Have you noticed blind people?
Their life is full of risk. They can't walk without the help of others.
Their lives always depends upon others. Let's make something for
them. Yesterday when I was walking to my college, a blind person who
was walking through the street. He faces difficulty walking on that
busy street. Fortunately I could help him at that time. At that moment, I
also thought I needed to do something for blind people. In the evening
of that day I came up with this idea: the smart blind stick. My aim is
that this can be cheap and easy-to-make. Even a kid can make it easily
in a couple of hours from scratch.
Using this smart blind stick, a visually impaired person can walk
without anyone's help. The smart blind stick automatically detects the
obstacle in front of the person and gives a response to the person by
vibrating the stick and with a warning sound.
Through this the blind person can be aware of the obstacles in front of
him.
I used an ultrasonic sensor for detecting the obstacles. It cost me just
10$ to make one.
So, it is cheap and also easy to make - not need for much soldering.
Keep reading to find out how to make it!
Step 1: Collect the Parts
Firstly, we need to collect all the parts that we needed.
Here are the parts you need to collect:
an Arduino Uno
an ultrasonic sensor (HCSR04)
a mini breadboard
a 9 volt battery
a 9 volt battery connector
DC male power jack
a buzzer
some jumper wires
a broken cellphone from scratch
a toggle switch
Other tools and parts used in this project:
3/4 inch diameter PVC pipe (used for making the stick)
3/4 inch diameter PVC elbow
insulation tape
some small screws for mounting the Arduino
screwdriver
utility knife
instant adhesive glue
a box to put your Arduino and other electronics in, or think about it
later
I thinks that's all we needed.
After collecting all the parts that we need, let's go to the next step!
Step 2: Take the Vibrator Motor from a Cellphone
First we need the vibrator motor. Find a broken cellphone.
Do this step with care and patience.
I used a micro vibrator motor from an old broken cellphone that was
lying around my home. The reason I used this: it is very small in size
and almost works with low voltage.
Unscrew the cellphone and disassemble all the parts like shown in the
above images. You can see the vibrator motor placed a side of the
phone's case. Take out the motor carefully from the cellphone.
Please note: different cellphones have different vibrator motor (in size and shape).
Now solder the motor on a small piece of general purpose PCB, then
solder two wires to the terminals of the motor like shown in the above
images.
Now we got the vibrator motor.
Step 3: Wiring the Arduino
Now it's time for wiring the Arduino!
See the above schematics and carefully connect all parts to the
Arduino.
I used a mini breadboard to connect the ultrasonic sensor to the
Arduino using jumper wires. The other parts like the buzzer and motor
are directly connected to the Arduino.
It's pretty easy does not have complicated wiring.
You can see the wiring diagram from the above image. Here I will
explain part by part:
Ultrasonic VCC to Arduino 5v
Ultrasonic GND to Arduino GND
Ultrasonic TRIG to Arduino D12
Ultrasonic ECHO to Arduino D11
Buzzer RED to Arduino D8
Buzzer BLACK to Arduino GND
Vibrator motor pin 1 to Arduino D7
Vibrator motor pin 2 to Arduino GND
9 volt battery RED to Toggle switch pin 1
9 volt battery BLACK to DC male power jack(-)
Toggle switch pin 2 to DC male power jack (+)
Now we finished the wiring!
Step 4: Arduino Sketch
Now it's time for uploading the sketch to the Arduino. The Arduino
code is attached with this project. Just copy and paste the code to your
Arduino IDE and plug your Arduino into the PC. Just click the upload
button. After successfully uploading, unplug the Arduino board.
Step 5: Let's Make the Stick
I used a PVC pipe for making the stick.
If you have a walking stick lying around your home, use that, or else
follow this step. Take a look at the above images to make the stick.
I used a 3/4 inch diameter PVC pipe and a 'L' shaped elbow for making
the stick.
I will describe to you in words how to make one:
First take a PVC pipe (3/4 inch diameter), then cut a piece of one
and half meter.
Take an 'L' shaped elbow and attach it one of the ends of the pipe.
Take another small piece of PVC pipe (10 cm long), then attach it
the other end of the elbow.
Simply glue it.
I just wrapped the stick with black insulation tape. No specific reason
for that except that I like the color black. You can even use paint to get
a cool look.
Step 6: Fitting the Circuit on the Stick
Now its time for fixing everything on the stick.
This is the hardest step in this project. It took me hours to design and
fix the parts onto the stick.
Find a box yourself that we can use to put all the electronics together. I
used a foam board to make a box myself. You can also simply do that (I
don't think you need a explanation for that).
Fix your Arduino into the box, use screws for a strong fixing. Make
two holes for fixing the ultrasonic sensor on the closing lid of the box
as shown in the above image. I fixed the buzzer outside of the box for a
clear sound. I also fixed the toggle switch onto a side of the box and a
small hole for connecting the vibrating motor to Arduino. Fix the
battery inside of the box and connect the power jack to the Arduino.
Mount the ultrasonic sensor on the closing lid of the box. Fix the
buzzer on the top of the box. Take out the vibrator motor to outside of
the box (we need to fix it on the stick's hand). See the above pictures
for how I put together all the parts.
Now attach the box to the stick, you can either use screw or glue it.
Here I used a instant adhesive glue, because it is very strong.
After attaching the box to the stick, take out the vibrator motor and fix
it below the elbow. I used insulation tape to fix the motor.
Step 7: Done
We made the smart blind stick. Make more features for the smart blind
stick and contribute something yourself to humanity. Bring more
automation ideas to help others.
SCHEMATICS
CODE
#define trigPin 13
#define echoPin 12
#define motor 7
#define buzzer 6
void setup()
{ pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motor, OUTPUT);
pinMode(buzzer,OUTPUT);
}
void loop()
{ long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
if (distance < 70) // Checking the distance, you can change the value
{
digitalWrite(motor,HIGH); // When the the distance below 100cm
digitalWrite(buzzer,HIGH);
} else
{
digitalWrite(motor,LOW);// when greater than 100cm
digitalWrite(buzzer,LOW);
} delay(500);
}
× 1
HCF4511
× 1
× 1
× 1
470 ohm resistor
× 1
Breadboard (generic)
× 1
2. HCF4511
HCF4511B is a BCD to 7 segment decoder driver able to drive LEDs and
other displays directly.
5. The Code
As you can see the code is very simple. Every time the button is pressed,
the counter will be increased and the number's converted to binary!
/*
Example of how to drive a seven segment display using HCF4511 or
similar
This sketch drive the display in order to show a number from 0 to 9
everytime a button connected to A0 is pressed.
author: Arturo Guadalupi
*/
//Declaration of Arduino pins used as HCF4511 inputs
const int A=2;
const int B=3;
const int C=4;
const int D=5;
void setup() {
pinMode(A0, INPUT);
pinMode(A, OUTPUT); //LSB
pinMode(B, OUTPUT);
pinMode(C, OUTPUT);
pinMode(D, OUTPUT); //MSB
}
int count = 0; //the variable used to show the number
void loop() {
if (digitalRead(A0) == L
SCHEMATICS
CODE
/*
Example of how to drive a seven segment display using HCF4511 or similar
This sketch drive the display in order to show a number from 0 to 9 everytime a button
connected to A0 is pressed.
*/
void setup() {
pinMode(A0, INPUT);
pinMode(A, OUTPUT); //LSB
pinMode(B, OUTPUT);
pinMode(C, OUTPUT);
pinMode(D, OUTPUT); //MSB
void loop() {
if (digitalRead(A0) == LOW) //if button is pressed
{
count++;
delay(200); //the delay prevent from button bouncing
if (count == 10) //we want to count from 0 to 9!
count = 0;
to_BCD(); //convert to binary
}
if (count == 10)
count = 0;
void to_BCD()
{
if (count == 0) //write 0000
{
digitalWrite(A, LOW);
digitalWrite(B, LOW);
digitalWrite(C, LOW);
digitalWrite(D, LOW);
}
× 1
× 1
Breadboard (generic)
× 1
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
APPS AND ONLINE SERVICES
MIT App Inventor
Arduino IDE
SCHEMATICS
CODE
/*
Example of how to drive a seven segment display using HCF4511 or similar
This sketch drive the display in order to show a number from 0 to 9 everytime a button
connected to A0 is pressed.
*/
void loop() {
if (digitalRead(A0) == LOW) //if button is pressed
{
count++;
delay(200); //the delay prevent from button bouncing
if (count == 10) //we want to count from 0 to 9!
count = 0;
to_BCD(); //convert to binary
}
if (count == 10)
count = 0;
void to_BCD()
{
if (count == 0) //write 0000
{
digitalWrite(A, LOW);
digitalWrite(B, LOW);
digitalWrite(C, LOW);
digitalWrite(D, LOW);
}
Breadboard (generic)
× 1
× 1
× 1
APPS AND ONLINE SERVICES
Arduino IDE
This project was a project designed specifically because I did not have a
timer on hand. To use this project you simply just upload the code to your
arduino (any type will work) you will just need upload the code to the
arduino and the countdown will automatically start. Should you want to
change the total time you will need to change this part of code.
REMEMBER!!! 1000= 1 sec. so 60000 = sec 60 or the equation
(SECx1000) will give you your total number to insert into the place of the
60000. Finally when you press the reset button the counter automatically
restarts.
long n = 60000; //start time -> CAN CHANGE TO WHATEVER TIME
YOU WANT
SCHEMATICS
CODE
//7 segement pin number - 7 segement light - arduino pin number
//pin 11 - A = 12
//pin 7 - B = 10
//pin 4 - C = 8
//pin 2 - D = 7
//pin 1 - E = 6
//pin 10 - F = 11
//pin 5 - G = 9
//pin 3 is decimal
/*
12 11 10 9 8 7
| | | |||
A
---
F| |B
|G|
---
E| |C
| |
--- . dec
D
||||||
123456
*/
long n = 60000; //start time -> CAN CHANGE TO WHATEVER TIME YOU WANT
int x = 100;
int del = 55; //delay value
void setup()
{
pinMode(d1, OUTPUT);
pinMode(d2, OUTPUT);
pinMode(d3, OUTPUT);
pinMode(d4, OUTPUT);
pinMode(a, OUTPUT);
pinMode(b, OUTPUT);
pinMode(c, OUTPUT);
pinMode(d, OUTPUT);
pinMode(e, OUTPUT);
pinMode(f, OUTPUT);
pinMode(g, OUTPUT);
pinMode(p, OUTPUT);
pinMode(startStopReset, INPUT);
digitalWrite(startStopReset, HIGH);
}
void loop()
{
digitalWrite (p, HIGH);
clearLEDs();
pickDigit(1);
pickNumber((n/x/1000)%10);
delayMicroseconds(del);
clearLEDs();
pickDigit(2);
pickNumber((n/x/100)%10);
delayMicroseconds(del);
clearLEDs();
pickDigit(3);
dispDec(3);
pickNumber((n/x/10)%10);
delayMicroseconds(del);
clearLEDs();
pickDigit(4);
pickNumber(n/x%10);
delayMicroseconds(del);
if (digitalRead(13) == LOW)
{
n = 60000; //re-start time -> CHANGE TO WHATEVER TIME YOU ORIGONALLY SET
(start time)
}
}
switch(x)
{
case 1:
digitalWrite(d1, LOW);
break;
case 2:
digitalWrite(d2, LOW);
break;
case 3:
digitalWrite(d3, LOW);
digitalWrite(p, HIGH); //new
break;
default:
digitalWrite(d4, LOW);
break;
}
}
void dispDec(int x)
{
digitalWrite(p, LOW);
}
void clearLEDs()
{
digitalWrite(a, LOW);
digitalWrite(b, LOW);
digitalWrite(c, LOW);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
digitalWrite(p, LOW);
}
void zero()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, LOW);
}
void one()
{
digitalWrite(a, LOW);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
}
void two()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, LOW);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, LOW);
digitalWrite(g, HIGH);
}
void three()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, HIGH);
}
void four()
{
digitalWrite(a, LOW);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
}
void five()
{
digitalWrite(a, HIGH);
digitalWrite(b, LOW);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, LOW);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
}
void six()
{
digitalWrite(a, HIGH);
digitalWrite(b, LOW);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
}
void seven()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
}
void eight()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
}
void nine()
{
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, LOW);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
}
× 1
If you are looking to test a lux value of light with Arduino, then this
project is suitable for you its easy and cool! Just connect the BH1750
module, upload the code, and run the serial monitor.
SCHEMATICS
CODE
#include <Wire.h>
#include <BH1750.h>
BH1750 lightMeter;
void setup(){
Serial.begin(9600);
lightMeter.begin();
Serial.println("Running...");
}
void loop() {
uint16_t lux = lightMeter.readLightLevel();
Serial.print("Light: ");
Serial.print(lux);
Serial.println(" lx");
delay(1000);
}
218) Arduino Outomatic Door and Counter Prototype
Ultrasonic Sensor
× 2
NECESSARY TOOLS AND MACHINES
Soldering iron (generic)
SCHEMATICS
CODE
//Adds libraries needed for the project
#include <Servo.h>
#include <NewPing.h>
#include <LiquidCrystal.h>
void setup(){
//Start Serial
Serial.begin(9600);
//Initiate LCD
lcd.begin(16,2);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Hello");
printToLCD();
getPing();
// derf = incoming;
}
void getPing(){
delay(50); // Wait 50ms between pings (about 20 pings/sec).
29ms should be the shortest delay between pings.
unsigned int uS = sonar[0].ping(); // Send ping, get ping time in
microseconds (uS).
// Serial.print("Ping1: ");
pinged = uS / US_ROUNDTRIP_CM;
// Serial.print(pinged); // Convert ping time to distance in cm and print
result (0 = outside set distance range)
// Serial.println("cm");
void openEnter(){
myOtherServo.write(0);
delay(10);
myOtherServo.write(80);
delay(100);}
void closeEnter(){
myOtherServo.write(80);
delay(10);
myOtherServo.write(0);
delay(100);}
void openExit(){
myservo.write(80);
delay(10);
myservo.write(0);
delay(100);
}
void closeExit(){
myservo.write(0);
delay(10);
myservo.write(80);
delay(100);}
void printToLCD(){
if (inside == 0){
// delay(100);
closeEnter();
}
inside = incoming - outgoing;
× 1
rfid522a
× 1
lcd 20*4
× 1
microservo 9g
× 1
× 1
× 2
× 1
Buzzer
× 1
LED (generic)
× 2
× 30
Breadboard (generic)
× 1
APPS AND ONLINE SERVICES
Arduino IDE
int red=A0;
int green=A1;
MFRC522 nfc(SDAPIN, RESETPIN); // Init of the library using the UNO pins declared
above
void setup() {
Servo1.attach(servoPin);
pinMode(A0, OUTPUT);
pinMode(A1, OUTPUT);
pinMode(A2, OUTPUT);
lcd.begin(20, 4);
// Print a message to the LCD.
lcd.setCursor(0,0);
lcd.print("RFID SECURITY SYSTEM"); // give here the comments you need show the
display
delay(200);
lcd.setCursor(2,1);
lcd.print(" PROJECT DONE BY "); // give here the comments you need show the display
delay(200);
lcd.setCursor(0,3);
lcd.print(" S6 ELS 2014-2017"); // give here the comments you need show the display
delay(1000);
lcd.setCursor(0,2);
lcd.print(" LIJIN ASHOK "); // give here the comments you need show the display
delay(2000);
lcd.setCursor(0,2);
lcd.print(" MIDHUN M S"); // give here the comments you need show the display
delay(2000);
lcd.setCursor(0,2);
lcd.print(" PRABHU Y RAJ"); // give here the comments you need show the display
delay(2000);
lcd.setCursor(0,2);
lcd.print(" SARATH P "); // give here the comments you need show the display
delay(2000);
lcd.setCursor(0,2);
lcd.print(" SREEJITH R S "); // give here the comments you need show the display
delay(2000);
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
SPI.begin();
Serial.begin(9600);
void loop() {
Servo1.write(0);
delay(300);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("RFID SECURITY SYSTEM");
lcd.setCursor(4,3);
lcd.print("SHOW YOUR ID");
lcd.noDisplay();
delay(200);
lcd.display();
delay(250);
String GoodTag="False"; // Variable used to confirm good Tag Detected
if (FoundTag == MI_OK) {
delay(200);
Serial.println("Tag detected.");
Serial.print("Serial Number: ");
for (int i = 0; i < 4; i++) { // Loop to print serial number to serial monitor
Serial.print(TagSerialNumber[i], HEX);
Serial.print(", ");
}
Serial.println("");
Serial.println();
// Check if detected Tag has the right Serial number we are looking for
for(int i=0; i < 4; i++){
if (GoodTagSerialNumber[i] != TagSerialNumber[i]) {
break;
}
if (i == 3) {
GoodTag="TRUE";
}
}
if (GoodTag == "TRUE"){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("RFID SECURITY SYSTEM");
lcd.setCursor(3, 1);
lcd.print("ACCESS GRANTED");
lcd.setCursor(0,3);
digitalWrite(A1, HIGH);
lcd.print(" +----WELCOME----+");
digitalWrite(A2, HIGH);
delay(300);
digitalWrite(A2, LOW);
delay(300);
digitalWrite(A2, HIGH);
delay(300);
digitalWrite(A2, LOW);
delay(300);
digitalWrite(A2, HIGH);
delay(300);
digitalWrite(A2, LOW);
delay(300);
digitalWrite(A2, HIGH);
delay(300);
digitalWrite(A2, LOW);
delay(300);
digitalWrite(A2, HIGH);
delay(300);
digitalWrite(A2,LOW);
Servo1.write(180);
delay(7000);
Servo1.write(0);
digitalWrite(A1, LOW);
}
else {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("RFID SECURITY SYSTEM");
lcd.setCursor(3, 1);
lcd.print("ACCESS DENIED");
digitalWrite(A1,LOW);
delay(100);
lcd.setCursor(0,3);
lcd.print(" UNAUTHORIZED ENTRY");
digitalWrite(A2, HIGH);
delay(150);
digitalWrite(A2, LOW);
delay(150);
digitalWrite(A2, HIGH);
delay(150);
digitalWrite(A2, LOW);
delay(150);
digitalWrite(A2, HIGH);
delay(150);
digitalWrite(A2,LOW);
delay(150);
digitalWrite(A2, HIGH);
delay(150);
digitalWrite(A2, LOW);
delay(150);
digitalWrite(A2, HIGH);
delay(150);
digitalWrite(A2,LOW);
digitalWrite(A0, HIGH);
delay(3000);
digitalWrite(A0, LOW);
}
delay(200);
}
}
× 1
Alphanumeric LCD, 20 x 4
× 1
NECESSARY TOOLS AND MACHINES
Breadboard, 270 Pin
APPS AND ONLINE SERVICES
Arduino IDE
SCHEMATICS
CODE
#include <LiquidCrystal.h>
void setup()
{
pinMode(pulse_ip,INPUT);
lcd.begin(16, 4);
lcd.clear();
lcd.print("Freq:");
lcd.setCursor(0,1);
lcd.print("Ton:");
lcd.setCursor(0,2);
lcd.print("Toff:");
lcd.setCursor(0,3);
lcd.print("Duty:");
}
void loop()
{
ontime = pulseIn(pulse_ip,HIGH);
offtime = pulseIn(pulse_ip,LOW);
period = ontime+offtime;
freq = 1000000.0/period;
duty = (ontime/period)*100;
lcd.setCursor(4,1);
lcd.print(ontime);
lcd.print("us");
lcd.setCursor(5,2);
lcd.print(offtime);
lcd.print("us");
lcd.setCursor(5,0);
lcd.print(freq);
lcd.print("Hz");
lcd.setCursor(6,3);
lcd.print(duty);
lcd.print('%');
delay(1000);
}