Sie sind auf Seite 1von 34

Programming in Arduino

Year: 2016

Project 15: Hacking Buttons

march 8, 2016march 10, 2016 • programminginarduino • leave a comment


This is the last project in the Arduino Starter Kit. We hope you enjoy it!

Before starting you must know that in this project a bu on is going to be hacked. This bu on
can be from whatever electronic device which has one. In this post, the explanations are
referred to a digital recording module which records and play back sound.

CAUTION: you must know that whatever device you use, when hacking it, you will lose de
device’s warranty.

That’s why our team has decided not to build this project. Notwithstanding this, everything is
going to be properly-explained as in all the previous posts.

Hacking a bu on means that Arduino will press the bu on instead of having to do it manually
by someone. To this end an optocoupler will be required to make the circuit. As you may well
know, optocouplers are integrated circuits that allow to control another one without any
electrical connection between both.

In order to make the properly connections, the following image will help you. If it’s possible,
try to do it without soldering any wires.
When making the connections with the electronic device be careful and do exactly what we
say here. First of all, look for the playback bu on and remove it from the recording. Under
this bu on are two small metal plates. These are the two sides of the switch and they get
connected when pressing the bu on.

In this case, as anyone is going to press it, you should connect one wire to each of the small
metal plates in order to connect them to the optocoupler (do it exactly as it is shown in the
previous picture). We recommend to do it using tape instead of soldering.

After making all the required connections, it’s time to do the code. As always, all the steps are
perfectly explain below. Is to notice that there is no particular difficulty in this program.
//Naming a constant for the optocoupler control pin
const int optoPin=2;
void setup() {
//Setting the optocoupler as an OUTPUT
pinMode(optoPin,OUTPUT);
}

void loop() {
//Pulling the optoPin HIGH for a few milliseconds. Time enough to c
digitalWrite(optoPin,HIGH);
delay(15);
//Pullong the optoPin LOW for 21 seconds, then the recording will st
digitalWrite(optoPin,LOW);
delay(21000);
}

To execute this project you must record a 20 seconds (or less) sound. Afterwards, power the
Arduino with the USB cable. The recording should start to play and a few momentss after
finishing, it should start again.

A video which exemplifies this project is the following. Notice that is not recorded by our
team and in this case a LED is being hacked instead of a recorder. Anyway, we hope it helps
you.

Arduino Project 15: Hacking Buttons

And now is time to think about what would you like to create with Arduino. Your ideas could
change our lifes. So please, don’t heasitate and start realizing them.
Advertisements

REPORT THIS AD

REPORT THIS AD

Project 14: Tweak the Arduino Logo

march 8, 2016march 10, 2016 • programminginarduino • leave a comment


Hi everyone! Welcome to our new post. We hope you are enjoying the Arduino Starter Kit
Projects. You should know that they are about to finish. Nevertheless, don’t feel melancholy;
in fact, a wonderful project is bound to start. But let’s begin with this new project called Tweak
the Arduino Logo.

What is this project about? In this case serial communication is going to be used to control a
program on your computer with your Arduino. As you may know, when programming in
Arduino, a connection between the computer and the microcontroller is opened. On this
project, this connection is going to be used to send data back and forth to other applications.

Thanks to serial communication, your Arduino and your PC will exchange bits of
information. Is important to notice that to successfully establish this communication the speed
they exchange information must be the same. So that, we will get values from the analog
inputs and use them into a program wri en in a different environment: Processing. Don’t
worry it is similar to Java and Arduino as well. However, you can start familiarizing with
Processing looking at some useful tips here: Ge ing Started
(h ps://processing.org/tutorials/ge ingstarted/).
In order to tweak the logo, the analog inputs will be proportionated by a potentiometer. So, in
this case, the circuit in your Arduino is as simple as that:

Furthermore, you must install in your computer Processing – just click here
(h ps://processing.org/download/?processing) to install the last version (3.0.2) of this
software,the same as we have used.

In this case, we should write two codes, one in Arduino and another in Processing. Pay
a ention to the explications made below. And ask us if there is any doubt.
The code in Arduino is:

void setup() {
// starting serial communication. Make sure Processing and Arduino ha
Serial.begin(9600);
}

void loop() {
// Sending to the serial connection the analug inputs introcued by th
// As only is possible to send values from 0 to 255, devide de Analog
Serial.write(analogRead(A0)/4);
// After sending the byte, let the ADC stabilize.
delay(33);
}
And in Processing:

//including the serial ports external lybrary


import processing.serial.*;
Serial myPort;
//Creating an object for the image
PImage logo;
//Creating a variable to store the background colour
int bgcolor=0;
void setup(){
//Setting the colour mode. In this case we're useing HSB(HueSaturation
colorMode(HSB,255);
//loading the image directly form the Internet
logo=loadImage("http://arduino.cc/logo.png");
// you can use "size(logo.width,logo.height)" to automatically adjust
//if you have problems, adjust it manually:
size(170,120);
//Printing a list with all the serial ports your computer has when the
println("Available serial ports:");
printArray(Serial.list());
//Telling Processing information about the serial connection. The para
myPort=new Serial(this,Serial.list()[0],9600);
}
//Analog function to void loop() in Arduino
void draw(){
//Reading Arduino data from the serial port
if(myPort.available()>0){
bgcolor=myPort.read();
println(bgcolor);
}
//changing the image background
background(bgcolor,255,255);
//Displaying the image and starting drawing on top left (0.0)
image(logo,0,0);
}

If executing this program, the result should be the following:


Project 14 - Part 1

Now it’s time to use your imagination. Some cute variations are:

Changing the Arduino logo by a heart. You just have to change the URL for a new one.

Project 14 - Part 2

Replacing the potentiometer by a photoresistor. In this case, the colour will be changing
depending on the light.
Project 14 - Part 3

Project 13: Touchy-feely Lamp

march 6, 2016march 10, 2016 • programminginarduino • 1 comment


In this project the main objective is to control the states of a lamp with a sensitive mode.

We will use a led, two resistors (1 MOhm and 220 Ohm) and a metal foil. In our experiment
the metal foil will be the touchy-detector and the led will act as a lamp.

First of all, we will have to set up the electrical circuit to continue with the project. In the
image we can see how to connect the elements:
As we can see, there’s no line connected to 5V. The reason is that we will use a library in the
code which will allow us to create a capacitor from two pins and 1 MOhm resistor, avoiding
us to provide a 5V potential difference from the Arduino Board.

The following step will be to write the Arduino code and implement it on the board.
//Import a library from the Arduino folder
#include <CapacitiveSensor.h>
//Select the two pins that will act as a capacitor
CapacitiveSensor capSensor = CapacitiveSensor(4,2);
//Insert the minimum value provided by the sensor to detect the touch
int threshold = 1000;
const int ledPin = 12;

void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}

void loop() {
//Read the sensor value
long sensorValue = capSensor.capacitiveSensor(30);
Serial.println(sensorValue);
//Touch detected
if (sensorValue > threshold) {
//Turn on the led
digitalWrite(ledPin, HIGH);
}
//Touch undetected
else {
//Turn off the led
digitalWrite(ledPin, LOW);
}
delay(10);
}

We have used a new library to write the function: CapacitiveSensor.h


(h p://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense). It has been
implemented to help us and simplify the code.

Here is a demonstration of how it works:


Project 13: Touchy-feely Lamp

To brush up some concepts acquired in the projects made before, we have created a thief
detector using a buzzer, a led and the capacitive sensor executed before. We have designed
this function to detect if a thief is trying to break into our home. The sensor has to be put in
the door, and the led and the buzzer have to be installed in an habitated room. Here you have
a video of the variation made:

Project 13 (thief detector)

Project 12: Knock Lock

march 6, 2016march 10, 2016 • programminginarduino • leave a comment


In this project we’ll build our own lock system that only can be unlocked by knocking 3 times.
For this project we need 3 different colour Led, some resistors, a switch, a capacitor and a
servomotor.

By pressing the bu on the system will get locked, which will be indicated by the red LED.
The knocks will be captured by the buzzer (remember that the buzzer can act like a speaker
and a vibration sensor), and each time it detects a knock, the yellow LED will blink once.
When we had knocked 3 times, the servomotor will turn 90º and the green led will be on.
Indicating that the system is unlocked.

We will know the current state of the system because it will be displayed (if it’s un/locked,
knocks left…).

We need to connect our buzzer to an analogic pin, due it generates a wide data range, not
only 1 or 0.

The 3 LED’s will be connected to digital outputs, and the signal pin of our servomotor will be
connected to a digital pin too. But remember to connect it to pin that can act like an analogic
output trough PWM (as seen on previous projects).

The capacitor’s function is to stabilize the electric signal.

The main objective of the program is to turn 90º the servomotor and turn the red light on
when the bu on is pressed. Then, it will start the knock countdown. Each time the buzzer
detects a knock the yellow light will blink. When the system has detected 3 knocks will return
the servo to its natural position and turn the green light on.
// import the library
#include <Servo.h>
// create an instance of the servo library
Servo myServo;

const int piezo = A0;


const int switchPin = 2;
const int yellowLed = 3;
const int greenLed = 4;
const int redLed = 5;
//defines LED's and piezo's pins.
// variable for the piezo value
int knockVal;
// variable for the switch value
int switchVal;
// variables for the high and low limits of the knock value
const int quietKnock = 10;
const int loudKnock = 100;
// variable to indicate if locked or not
boolean locked = false;
// how many valid knocks you've received
int numberOfKnocks = 0;

void setup(){
// attach the servo to pin 9
myServo.attach(9);
// make the LED pins outputs
pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
// set the switch pin as an input
pinMode(switchPin, INPUT);
// start serial communication for debugging
Serial.begin(9600);
// turn the green LED on
digitalWrite(greenLed, HIGH);
// move the servo to the unlocked position
myServo.write(0);
// print status to the serial monitor
Serial.println("the box is unlocked!");
}
void loop(){
// if the box is unlocked
if(locked == false){
// read the value of the switch pin
switchVal = digitalRead(switchPin);
// if the button is pressed, lock the box
if(switchVal == HIGH){
// set the locked variable to "true"
locked = true;
// change the status LEDs
digitalWrite(greenLed,LOW);
digitalWrite(redLed,HIGH);
// move the servo to the locked position
myServo.write(90);
// print out status
Serial.println("the box is locked!");
// wait for the servo to move into position
delay (1000);
}
}
// if the box is locked
if(locked == true){
// check the value of the piezo
knockVal = analogRead(piezo);
// if there are not enough valid knocks
if(numberOfKnocks < 3 && knockVal > 0){
// check to see if the knock is in range
if(checkForKnock(knockVal) == true){
// increment the number of valid knocks
numberOfKnocks++;
}
// print status of knocks
Serial.print(3 - numberOfKnocks);
Serial.println(" more knocks to go");
}
// if there are three knocks
if(numberOfKnocks >= 3){
// unlock the box
locked = false;
// move the servo to the unlocked position
myServo.write(0);
// wait for it to move
delay(20);
// change status LEDs
digitalWrite(greenLed,HIGH);
digitalWrite(redLed,LOW);
Serial.println("the box is unlocked!");
}
}
}
// this function checks to see if a
// detected knock is within max and min range
boolean checkForKnock(int value){
// if the value of the knock is greater than
// the minimum, and larger than the maximum
if(value > quietKnock && value < loudKnock){
// turn the status LED on
digitalWrite(yellowLed, HIGH);
delay(50);
digitalWrite(yellowLed, LOW);
// print out the status
Serial.print("Valid knock of value ");
Serial.println(value);
return true;
}
// if the knock is not within range
else {
// print status
Serial.print("Bad knock value ");
Serial.println(value);
return false;
}
}

Once coded and assembled everything is time to check our knock lock system out.

Project 12: Knock lock


Project 11: Crystal Ball

march 5, 2016march 10, 2016 • programminginarduino • 1 comment


In this project we learnt to deal with a Liquid Crystal Display, known be er by its
abbreviation to LCD. Although the LCD is connected to various signals as it receives different
type of information, there is already an available Liquid Crystal Library which makes it easier
to configure and control the characters displayed on the screen without dealing with low-level
basics of how the screen actually works.

The screen has up to 16 pins, ranging from digital pins to power supplies (Vcc, Vss, LED+-,
etc.). The R/W sets up if the panel should be used to write or to read. Pin number 6, or E
warns when it is to receive an instruction. Pin number 3 sets the luminosity of the screen.

The creative part of this project consisted in using the screen as a fortune teller. If we turn the
breadboard upside down, the screen will search between its answers a random one and
display it onscreen. The potentiometer regulates the luminosity.

We assembled this circuit:


#include <LiquidCrystal.h>

LiquidCrystal lcd(12,11,5,4,3,2); // generates an instance


in the lcd

const int switchPin = 6;


int switchState = 0;
int prevSwitchState = 0;
int reply;

void setup() {
lcd.begin(16,2);

pinMode(switchPin, INPUT);
lcd.print("Preguntame");
lcd.setCursor(0,1); // changes the Cursor to continue
writing in the second row
lcd.print("Bola de Cristal");
}
void loop() {
switchState=digitalRead(switchPin);

if (switchState != prevSwitchState) {
if (switchState == LOW) {
reply = random(8);
lcd.clear(); // clears the writing
lcd.setCursor(0,0);
lcd.print("La bola dice:");
lcd.setCursor(0,1);

switch(reply){ // the program will enter the case


assigned to the switch
case 0:
lcd.print("Si");
break;
case 1:
lcd.print("Es probable");
break;
case 2:
lcd.print("Ciertamente");
break;
case 3:
lcd.print("Buenas perspectivas");
break;
case 4:
lcd.print("No es seguro");
break;
case 5:
lcd.print("Pregunta de nuevo");
break;
case 6:
lcd.print("Ni idea");
break;
case 7:
lcd.print("No");
break;
}
}
}

The video shows the results:


Project 11: Crystal Ball

Project 10: Zoetrope

march 5, 2016march 10, 2016 • programminginarduino • 1 comment


On the previous project we got acquainted with motors and transistors in Arduino. However,
until this unit we were not able to control the direction in which the motor spinned without
manually swapping the ground and power wires. This activity aims to learn this new ability.
To do this, we must first explain a fundamental element : the H-Bridge

To learn the following we had to do a li le research ourselves, and we found this page
(h p://panamahitek.com/el-puente-h-invirtiendo-el-sentido-de-giro-de-un-motor-con-
arduino/) to be quite of help. Things will get a li le technical for a moment, so if you don’t
want to deal with this, you can skip to a later brief summary.

As explained, a motor will spin clockwise or anticlockwise depending on the direction of


current flow, which is imposed by the voltage across its terminals . We want to be able to
control the direction of current to direct the spin of the motor.

The next scheme illustrates an electrical circuit of an H-bridge, similar to how the Arduino
one might work.
Notice that this scheme has 5 components: resistors, diodes, transistors, the motor and two
voltage sources. In this circuit current doesn’t flow in any direction, because the switch
highlighted in green is open. Current doesn’t move across the resistors that are connected to
the transistor’s gate. The transistors, which act as ‘switches’ are left open. The diodes do not
allow current to flow against the such drawn ‘arrow’, therefore it doesn’t ma er whether the
second voltage source is connected to the terminals: there is no path for current to take.
Current cannot take its usual direction from the positive to the negative sign. The circuit is
deactivated and the motor doesn’t move.

Let’s say we turn the highlighted green switch to the SW1 position. Imagine which resistors
are now electrically feeded. This resistors will turn the ‘digital switch’ (as we now imagine
transistors to be), on. Now the voltage applied to the transistor’s gate will allow current to
flow from the source to the drain. The idea is that electricity has a path through the motor and
so the motor spins.

If the green switch takes the other position, the resistors feeded are R1 and R4, as shown in
the image below. Current flows in the other direction thus the motor spins anticlockwise.
And this is the story of how this li le Arduino component does its magic.

This is the first Integrated Circuit we encounter, and it was interesting to learn how it worked
on the inside. On the same site where we got all this information, there was a scheme to build
an H-bridge with Arduino at a large scale. We might post another video later if we find the
time to build it ourselves.
Briefly, as it is explained in the Starter’s book the H-Bridge polarizes the voltage applied to
make the motor turn one way or another.

Back to the project, the book integrates the motor into a cardboard-made-zoetrope, which can
be built following these instructions.

There are two bu on switches: one will serve to either turn the motor on or off and the other
to switch the direction in which the motor is spinning. The potentiometer will regulate the
speed. As before, we will need a 9V ba ery to feed the motor.

The H-Bridge has many pins that we will try to explain shortly.
(h ps://itp.nyu.edu/physcomp/labs/motors-and-transistors/dc-motor-control-using-an-h-
bridge/)

This IC allows us to connect and control two different motors, as it has one bridge on each
side (it is kind of antisymmetric). The pins named EN enable or disable the motor depending
on the entering voltage. Each pin enables the motor connected to the terminals separated by
commas. The Logic pins denoted by A make the motor turn left or right, or anything
indicated by the table. The motor terminals are plugged into the Y pins. The middle pins serve
as ground and the two pins left are for the power supply.

This is the code we used:


const int controlPin1 = 2;// the control pins will carry the
logic - direction to turn and applied to the H-Bridge
const int controlPin2 = 3;
const int enablePin = 9; // attached to the pin EN
const int directionSwitchPin = 4;// 4 and 5 carry the values
of buttonSwitches
const int onOffSwitchStateSwitchPin = 5;
const int potPin = A5; // analogic signal, because it is a
potentiometer delivering continuous values
int onOffSwitchState = 0;
int previousOnOffSwitchState = 0;
int directionSwitchState = 0;
int previousDirectionSwitchState = 0;

int motorEnabled = 0;
int motorSpeed = 0;
int motorDirection = 1;

void setup() {
pinMode(directionSwitchPin,INPUT);
pinMode(onOffSwitchStateSwitchPin,INPUT);
pinMode(controlPin1,OUTPUT);
pinMode(controlPin2,OUTPUT);
pinMode(enablePin,OUTPUT);

digitalWrite(enablePin,LOW);// the motor initializes at OFF


}
void loop() {
onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
delay(1);
directionSwitchState = digitalRead(directionSwitchPin);
motorSpeed = analogRead(potPin)/4;

if(onOffSwitchState != previousOnOffSwitchState){ // this


part allows the user to have the motor spin without having to
hold the button itself. Otherwise we should keep pressing the
button switch to turn the motor.
if(onOffSwitchState ==HIGH){ // if the user presses the
button, the state changes. Otherwise, it remains unchanged.
motorEnabled = !motorEnabled;
}
}
if (directionSwitchState != previousDirectionSwitchState) { // analag
if (directionSwitchState == HIGH) {
motorDirection = !motorDirection;
}
}
if(motorDirection == 1){ // If the Direction is 1, turn left.
digitalWrite(controlPin1, HIGH);
digitalWrite(controlPin2, LOW);
}
else { // If the Direction is 0, turn right.
digitalWrite(controlPin1, LOW);
digitalWrite(controlPin2, HIGH);
}

if(motorEnabled == 1) { // If the motor should be enabled,


set EN to HIGH and the motorSpeed indicated by the
Potentiometer
analogWrite(enablePin, motorSpeed);
}
else {
analogWrite(enablePin, 0); // If the motor is turned Off,
set EN to LOW
}

previousDirectionSwitchState = directionSwitchState; //
These lines are very important to keep the current state!
previousOnOffSwitchState = onOffSwitchState;
}

The end result looks like this:


Project 10: Zoetrope

We had some troubles holding the motor correctly, because the wires made a poor contact
sometimes. Later we had to sold the wires (for a second time) to the motor, as it pulled off. At
a few moments in the video one can observe (especially hear) that the motor had problems to
start spinning, particularly at low speeds. We found the project to be fun in a technical sense,
but discontented with the presentation we set the motor in another gears left at home.

Project 10: Another application

Project 09: Motorized Pinwheel

march 4, 2016march 10, 2016 • programminginarduino • leave a comment


In this project, we made a motorized pinwheel. In other words, we wanted a motor to spin.
The first issue we had to deal with was that the motor included in the Starter Kit needed more
current and voltage than the maximum dispensable by the Arduino’s output pins. To solve it,
we used a ba ery of 9V.

Another point was that we had to control the ba ery and the motor (high voltage) with low
voltage (outputs from the Arduino’s pins). In order to achieve it, we needed to use a new
element: a transistor. A transistor consists in three “parts”, each one connected to the
protoboard: the gate, the source and the drain. When low voltage (the one that provides
Arduino’s pins) hits the gate, it closes the circuit between the source and the drain allowing
you to turn on motors, ba eries… and control them.

Now you can see a picture of a transistor:

And here, there’s a picture of how we built the circuit:

As you can see there’s a black diode in parallel with the motor. This is because when the
motor receives electricity, a magnetic field is generated. In consequence, voltage is created in
the opposite direction that is conducted to the motor. It is called back voltage. When you turn
off the power supply and the motor is spinning, owing to the inertia it will continue moving
for a while. Then the back voltage becomes a problem and can damage the circuit. The diode
avoids this situation protecting the circuit.

The code used has been:

//Introducing the constants of the switch and the motor


const int switchPin=2;
const int motorPin=9;
int switchState=0;

void setup() {
//Selecting as an input and output the switch and the motor
pinMode(switchPin,INPUT);
pinMode(motorPin,OUTPUT);
}

void loop() {
//Reading if the switch has been pushed
switchState=digitalRead(switchPin);
if(switchState==HIGH){
//If the switch has been pushed make the motor spin
digitalWrite(motorPin,HIGH);
}
else{
//If the switch hasn't been pushed don't make the motor spin
digitalWrite(motorPin,LOW);
}
}

To make it funnier, we used a circular coloured paper and it looked this way!
P09 Motorized Pinwheel

P.S. We have to say we had several problems with the wires of the motor. We had to weld
each wire once (the positive and the negative) because the soldering had broken. Be careful
with it, at the beginning it was hard to realize it was broken!

Programming in Arduino
Create a free website or blog at WordPress.com.

Das könnte Ihnen auch gefallen