Tuesday, May 12, 2015

Combination of leds, servo, push button

         In this improvement, we used yellow, green, red leds, 2 push buttons and 1 servo. This mini project is a combination of 3 different hardware components. Our task is by looking the state of push buttons, changing the servo state. If push button 1 is low, we increase the servo state. If push button 2 is low, we decrease the servo state. Our 2nd task is, by looking this servo state we changed the states of these 3 leds. We did this by a simple way; using if else statements.

Berrak Şişman, İlker Çam
Our circuit photo is given below.


#include "servo.h"

const int LedRed = 13;
const int LedGreen = 11;
const int LedYellow = 12;

const int btn1 = 2;
const int btn2 = 3;

const int servoPin = 9;
Servo servo1;
unsigned int ServoPosition = 90;
void setup() {
  // put your setup code here, to run once:
  servo1.attach(servoPin);
  pinMode(btn1,INPUT);
  pinMode(btn2,INPUT);

  pinMode(LedRed,OUTPUT);
  pinMode(LedGreen,OUTPUT);
  pinMode(LedYellow,OUTPUT);
  servo1.write(ServoPosition);
  Serial.begin(9600);
}

void loop() {
  int btn1State,btn2State;
  unsigned int servoStateHasBeenChanged = 0;
  btn1State = digitalRead(btn1);
  btn2State = digitalRead(btn2);
  Serial.println(ServoPosition);
  if(btn1State == LOW){
    ServoPosition = ((ServoPosition + 4 )%180);
    servoStateHasBeenChanged = 1;
    Serial.println("BTN 1 Pressed\n");
  }else if(btn2State == LOW){
    ServoPosition = ((ServoPosition - 4 )%180);
    servoStateHasBeenChanged = 1;
    Serial.println("BTN 2 Pressed\n");
  }
  if(ServoPosition<92 data-blogger-escaped-servoposition=""> 88){
    digitalWrite(LedGreen,LOW);
    digitalWrite(LedRed,LOW);
    digitalWrite(LedYellow,HIGH);
  }else if(ServoPosition<90 data-blogger-escaped-digitalwrite="" data-blogger-escaped-edgreen="" data-blogger-escaped-edred="" data-blogger-escaped-edyellow="" data-blogger-escaped-else="" data-blogger-escaped-ervoposition="" data-blogger-escaped-if="">90){
    digitalWrite(LedGreen,LOW);
    digitalWrite(LedRed,HIGH);
    digitalWrite(LedYellow,LOW);
  }

  if(servoStateHasBeenChanged == 1){
    servo1.write(ServoPosition);
  }
  delay(50);
}

Servo with Relay State Improvement


In this improvement, we used relay and servo motor. A relay is basically an electrically controlled mechanical switch. Inside that harmless looking plastic box is an electromagnet that, when it gets a jolt of energy, causes a switch to trip.We are changing the position of servo with looking the state of relay. 
Berrak Şişman& İlker Çam

#include "Servo.h"

const int relayPin = 2;     // use this pin to drive the transistor
const int timeDelay = 1000; // delay in ms for on and off phases
const int onPin = 7;
const int offPin = 8;
const int servoPin = 6;
int onOff = 1;
Servo servo1;

void setup()
{
  pinMode(relayPin, OUTPUT);  // set pin as an output
  pinMode(onPin,INPUT);
  pinMode(offPin,INPUT);
  servo1.attach(servoPin);
  Serial.begin(9600);
}


void loop()                
{

  digitalWrite(relayPin,HIGH);
  delay(500);
  readRelayState();
  digitalWrite(relayPin,LOW);
  delay(500);
  readRelayState();

}

void readRelayState(){
  int onState, offState;
  onState = digitalRead(onPin);
  offState = digitalRead(offPin);
  Serial.println(onState);
  Serial.println(offState);
  if(onState == HIGH && offState == LOW || onOff==1?true:false){
    onOff=0;
    for(int position = 0; position < 180; position += 2)
  {
    servo1.write(position);  // Move to next position
    delay(2);               // Short pause to allow it to move
  }
    Serial.println("Servo is at 180 degrees");
  }else if(onState == LOW && offState == HIGH || onOff==0?true:false){
    onOff=1;
      for(int position = 180; position >= 0; position -= 1)
  {                            
    servo1.write(position);  // Move to next position
    delay(2);               // Short pause to allow it to move
  }
    Serial.println("Servo is at 0 degrees");
  }
  delay(100);


}

Project 1- Car routing with Iphone application

In this project, we wrote some of our codes in arduino, some of them in IOS. Our car can go any degrees with any rate, given by user. We also used compass in our car.We create an iphone application which can be shown in the video given below. This is a very simple interface and a user can easily control the car. The car can go forward or back with any speed value. We can increase or decrease the rate of the car. 



Find all codes including iOS & arduino at GitHub : https://github.com/ilkerc/ArduinoRobot-With-iOS-Bluetooth

Berrak Şişman and İlker Çam

Smart Home with IOS Application

The concept of the "Internet of Things" has tied in closely with the popularization of  home automation. There are lots of smart home applications such as Home security,  access control,  lighting control, home health care, fire detection, leak detection energy efficiency, solar panel monitoring and control etc.                                                      
 In this project, we aim to create a smart home application. We used ethernet shield. It works as a webserver in this project. Also we made an iphone application. By the help of this application, user can  control tv, garage door, temperature, light and learn the moisture of the room  while he is far away from his home. 8 way 5V relay is used for this aim. We build a 3-tier structure. The first layer is Arduino, second one is web service and the third one is an Iphone application. Our circuit is given below.




#include "SPI.h"
#include "Ethernet.h"
#include "WebServer.h"
#include "TimerOne.h"
#include 

template
inline Print &operator <<(Print &obj, T arg)
{
  obj.print(arg);
  return obj;
}


// CHANGE THIS TO YOUR OWN UNIQUE VALUE
static uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// CHANGE THIS TO MATCH YOUR HOST NETWORK
static uint8_t ip[] = { 192, 168, 2, 57 };

#define PREFIX ""

WebServer webserver(PREFIX, 80);

void jsonDigitalCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete)
{
  if (type == WebServer::POST)
  {
    server.httpFail();
    return;
  }

  //server.httpSuccess(false, "application/json");
  server.httpSuccess("application/json");

  if (type == WebServer::HEAD)
    return;

  int i;
  server << "{ ";
  for (i = 0; i <= 13; ++i)
  {
    // ignore the pins we use to talk to the Ethernet chip
    int val = digitalRead(i);
    server << "\"" << i << "\": " << val;
    if (i != 13)
      server << ", ";
  }
  server << " }";
}

void jsonAnalogCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete)
{
  if (type == WebServer::POST)
  {
    server.httpFail();
    return;
  }

  //server.httpSuccess(false, "application/json");
  server.httpSuccess("application/json");

  if (type == WebServer::HEAD)
    return;

  int i;
  server << "{ ";
  for (i = 0; i <= 5; ++i)
  {
    int val = analogRead(i);
    server << "\"" << i << "\": " << val;
    if (i != 5)
      server << ", ";
  }

  server << " }";
}

void outputPins(WebServer &server, WebServer::ConnectionType type, bool addControls = false)
{
  P(htmlHead) =
    ""
    ""
    "Arduino Web Server"
    ""
    ""
    "";

  int i;
  server.httpSuccess();
  server.printP(htmlHead);

  if (addControls)
    server << "
"; server << "

Digital Pins

"; for (i = 0; i <= 9; ++i) { // ignore the pins we use to talk to the Ethernet chip int val = digitalRead(i); server << "Digital " << i << ": "; if (addControls) { char pinName[4]; pinName[0] = 'd'; itoa(i, pinName + 1, 10); server.radioButton(pinName, "1", "On", val); server << " "; server.radioButton(pinName, "0", "Off", !val); } else server << (val ? "HIGH" : "LOW"); server << "
"; } server << "

Analog Pins

"; for (i = 0; i <= 5; ++i) { int val = analogRead(i); server << "Analog " << i << ": " << val << "
"; } server << "

"; if (addControls) server << "
"; server << ""; } void formCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) { if (type == WebServer::POST) { bool repeat; char name[16], value[16]; do { repeat = server.readPOSTparam(name, 16, value, 16); if (name[0] == 'd') { int pin = strtoul(name + 1, NULL, 10); int val = strtoul(value, NULL, 10); digitalWrite(pin, val); } } while (repeat); server.httpSeeOther(PREFIX "/form"); } else outputPins(server, type, true); } void defaultCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) { outputPins(server, type, false); } const int analogCounter[] = {0, 1, 2, 3, 4 ,5}; const int analogAddr[] = {6, 9, 12, 15, 18, 21}; bool readAnalogValues = false; void setup() { // set pins 0-8 for digital input for(int i = 0; i <= 5; i++){ EEPROM.write(analogCounter[i], 0); EEPROMWritelong(analogAddr[i], 0); } Timer1.initialize(5000000); // initialize timer1, and set a 1/2 second period Timer1.pwm(9, 512); // setup pwm on pin 9, 50% duty cycle Timer1.attachInterrupt(changeSensorFlag); // attaches readSensors() as a timer overflow interrupt for (int i = 0; i <= 13; ++i) pinMode(i, OUTPUT); Ethernet.begin(mac, ip); webserver.begin(); Serial.begin(9600); webserver.setDefaultCommand(&defaultCmd); webserver.addCommand("jsonDigital", &jsonDigitalCmd); webserver.addCommand("jsonAnalog", &jsonAnalogCmd); webserver.addCommand("form", &formCmd); } void loop() { webserver.processConnection(); // if you wanted to do other work based on a connecton, it would go here if (readAnalogValues) { readSensors(); } } void changeSensorFlag(){ readAnalogValues = !readAnalogValues; } void readSensors(){ for(int i = 0; i<=5; i++){ long sensorVal = (long)analogRead(i); long beforeValue = EEPROMReadlong(analogAddr[i]); int counterValue = EEPROM.read(analogCounter[i]); int newCounter = counterValue + 1; long newSensorValue = sensorVal + beforeValue; EEPROMWritelong(analogAddr[i], newSensorValue); EEPROM.write(analogCounter[i], newCounter); } readAnalogValues = false; } double readSensorsValueAtMeanValue(int sensor){ long sensorAllCollectedData = EEPROMReadlong(analogAddr[sensor]); int dataCount = EEPROM.read(analogCounter[sensor]); return ((double)sensorAllCollectedData / dataCount==0 ? 1 : dataCount); } void EEPROMWritelong(int address, long value) { //Decomposition from a long to 4 bytes by using bitshift. //One = Most significant -> Four = Least significant byte byte four = (value & 0xFF); byte three = ((value >> 8) & 0xFF); byte two = ((value >> 16) & 0xFF); byte one = ((value >> 24) & 0xFF); //Write the 4 bytes into the eeprom memory. EEPROM.write(address, four); EEPROM.write(address + 1, three); EEPROM.write(address + 2, two); EEPROM.write(address + 3, one); } long EEPROMReadlong(long address) { //Read the 4 bytes from the eeprom memory. long four = EEPROM.read(address); long three = EEPROM.read(address + 1); long two = EEPROM.read(address + 2); long one = EEPROM.read(address + 3); //Return the recomposed long by using bitshift. return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF); }

Game of Thrones, using buzzer

We run this code in class hours of cse342. This music can done by using a Piezo Buzzer. This is just for fun :)
İlker Çam Berrak Şişman


#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978
int sensorPin=6;
int speakerPin=4;
void GameOfThrones();
void setup()
  {
    pinMode(speakerPin,OUTPUT);
    pinMode(sensorPin,INPUT);
  }
void loop()
  {  //play when entering or leaving you thrones, chair etc.
      //im using negative logic infrared sensor(if positive logic, use HIGH insted of LOW)
    if(digitalRead(sensorPin)==LOW)
    {
     delay(50);
     if(digitalRead(sensorPin)==LOW)
      {
       GameOfThrones();
      } 
    } 
  }

  
void GameOfThrones()
  {
    for(int i=0; i<4; i++)
    {
    tone(speakerPin, NOTE_G4);
    delay(500);
    noTone(speakerPin);
    tone(speakerPin, NOTE_C4);
    delay(500);
    noTone(speakerPin);
    tone(speakerPin, NOTE_DS4);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_F4);
    delay(250);
    noTone(speakerPin);
    }
    for(int i=0; i<4; i++)
    {
    tone(speakerPin, NOTE_G4);
    delay(500);
    noTone(speakerPin);
    tone(speakerPin, NOTE_C4);
    delay(500);
    noTone(speakerPin);
    tone(speakerPin, NOTE_E4);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_F4);
    delay(250);
    noTone(speakerPin);
    }
        tone(speakerPin, NOTE_G4);
        delay(500);
        noTone(speakerPin);
        tone(speakerPin, NOTE_C4);
        delay(500);
        tone(speakerPin, NOTE_DS4);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_F4);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_D4);
        delay(500);
        noTone(speakerPin);
    for(int i=0; i<3; i++)
    {
    tone(speakerPin, NOTE_G3);
    delay(500);
    noTone(speakerPin);
    tone(speakerPin, NOTE_AS3);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_C4);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_D4);
    delay(500);
    noTone(speakerPin);
    }//
        tone(speakerPin, NOTE_G3);
        delay(500);
        noTone(speakerPin);
        tone(speakerPin, NOTE_AS3);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_C4);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_D4);
        delay(1000);
        noTone(speakerPin);
        
        tone(speakerPin, NOTE_F4);
        delay(1000);
        noTone(speakerPin);
        tone(speakerPin, NOTE_AS3);
        delay(1000);
        noTone(speakerPin);
        tone(speakerPin, NOTE_DS4);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_D4);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_F4);
        delay(1000);
        noTone(speakerPin);
        tone(speakerPin, NOTE_AS3);
        delay(1000);
        noTone(speakerPin);
        tone(speakerPin, NOTE_DS4);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_D4);
        delay(250);
        noTone(speakerPin);
        tone(speakerPin, NOTE_C4);
        delay(500);
        noTone(speakerPin);
    for(int i=0; i<3; i++)
    {
    tone(speakerPin, NOTE_GS3);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_AS3);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_C4);
    delay(500);
    noTone(speakerPin);
    tone(speakerPin, NOTE_F3);
    delay(500);
    noTone(speakerPin);
    }
          tone(speakerPin, NOTE_G4);
          delay(1000);
          noTone(speakerPin);
          tone(speakerPin, NOTE_C4);
          delay(1000);
          noTone(speakerPin);
          tone(speakerPin, NOTE_DS4);
          delay(250);
          noTone(speakerPin);
          tone(speakerPin, NOTE_F4);
          delay(250);
          noTone(speakerPin);
          tone(speakerPin, NOTE_G4);
          delay(1000);
          noTone(speakerPin);
          tone(speakerPin, NOTE_C4);
          delay(1000);
          noTone(speakerPin);
          tone(speakerPin, NOTE_DS4);
          delay(250);
          noTone(speakerPin);
          tone(speakerPin, NOTE_F4);
          delay(250);
          noTone(speakerPin);
          tone(speakerPin, NOTE_D4);
          delay(500);
          noTone(speakerPin);
    for(int i=0; i<4; i++)
    {
    tone(speakerPin, NOTE_G3);
    delay(500);
    noTone(speakerPin);
    tone(speakerPin, NOTE_AS3);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_C4);
    delay(250);
    noTone(speakerPin);
    tone(speakerPin, NOTE_D4);
    delay(500);
    noTone(speakerPin);
    }
}

CSE342 photos and videos










Playing notes with buzzer

If you turn the voltage on and off hundreds of times a second, the piezo buzzer will produce a tone. And if you string a bunch of tones together, you’ve got music! Here in this improvement, we gave the beats, and notes. We have 2 push buttons in our code. By using the push buttons, we change the frequency of our music.
Berrak Şişman İlker Çam


const int btnPin1 = 3;
const int btnPin2 = 2;
const int potansPin = 0;
const int buzzerPin = 9;

const int songLength = 18;

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

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

int tempo = 150;

char btnNotes[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int note = 0;

void setup()
{
  pinMode(buzzerPin, OUTPUT);
  pinMode(btnPin1,INPUT);
  pinMode(btnPin2,INPUT);
  pinMode(potansPin,INPUT);
  Serial.begin(9600);
}


void loop()
{
  //Serial.write("readValues ex\n");
  int btnState1 = 0,btnState2 = 0, potansValue = 0;
  btnState1 = digitalRead(btnPin1);
  btnState2 = digitalRead(btnPin2);
  potansValue = analogRead(potansPin);

  if(btnState1 == LOW && btnState2 == HIGH){
    tone(buzzerPin, frequency(btnNotes[note++]), 1000);
    note%=8;
    Serial.write("Playing Note\n");
    delay(50);
  }else if(btnState2 == LOW && btnState1 == HIGH){
    tempo = map(potansValue, 0, 1023, 100, 200);
    Serial.println(potansValue);
    playSong();
  }
  delay(100);

}

void playSong(){
 

  int i, duration;

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

    duration = beats[i] * tempo;  // length of note/rest in ms
    if (notes[i] == ' ')          // is this a rest?
    {
      delay(duration);            // then pause for a moment
    }
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }
}

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

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



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

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency
    }
  }
  return(0);
}

Controlling red, green and blue leds with push buttons and a potentiometer

In this improvement, we read the value of potentiometer using analogRead() function. We have also 3 push buttons. By using the 4 independent informations coming from potentiometer and 3 pushbuttons, we change the brightness of the leds. While doing this, we used analogWrite function. We write the potentiometer value to leds.

Berrak Şişman and İlker Çam
Our video is given below.

int ledRed = 13;
int ledGreen = 12;
int ledBlue = 11;
int potansPin = 0;

int button1Pin = 2;
int button2Pin = 3;
int button3Pin = 4;
int controlled; // 1 Red -> 2 Green -> 3 Blue -> 4 ALL

long timePASSED;

void setup() {
controlled = ledRed;
pinMode(ledRed,OUTPUT);
pinMode(ledGreen,OUTPUT);
pinMode(ledBlue,OUTPUT);

//Potans is been read by analogRead
pinMode(button1Pin,INPUT);
pinMode(button2Pin,INPUT);
pinMode(button3Pin,INPUT);
Serial.begin(9600);
timePASSED = millis();
}

// the loop function runs over and over again forever
void loop() {
  int potansValue = analogRead(potansPin);
  Serial.write(potansValue);
  int btn1State,btn2State,btn3State;
  btn1State = digitalRead(button1Pin);
  btn2State = digitalRead(button2Pin);
  btn3State = digitalRead(button3Pin);

  if(btn1State == LOW && btn2State == LOW && btn3State ==LOW){
    controlled = 4;
  } else if(btn1State == LOW){
    controlled = 1;
  } else if(btn2State == LOW){
    controlled = 2;
  } else if (btn3State == LOW){
    controlled = 3;
  }

  switch(controlled){
    case 1:
      analogWrite(ledRed,potansValue);
      break;
    case 2:
      analogWrite(ledGreen,potansValue);
      break;
    case 3:
      analogWrite(ledBlue,potansValue);
      break;
    case 4:
      analogWrite(ledRed,potansValue);
      analogWrite(ledGreen,potansValue);
      analogWrite(ledBlue,potansValue);
      break;
  }

  if((timePASSED+potansValue) < millis()){
      analogWrite(ledRed,0);
      analogWrite(ledGreen,0);
      analogWrite(ledBlue,0);
      timePASSED = millis();
  }
  delay(50);
}

Saturday, April 18, 2015

Converting a number from digital to binary and show the binary form using leds

In this improvement, we are getting integer numbers from serial port. With modula operation (%2) and with some basic calculus, we convert this integer number to binary form. Our last step is showing the binary representation of this number using 8 leds. The photo of this improvement is given below.

İlker Çam & Berrak Şişman



int datapin = 2;
int clockpin = 3;
int latchpin = 4;

byte data = 0;


void setup()
{
  // Set the three SPI pins to be outputs:

  pinMode(datapin, OUTPUT);
  pinMode(clockpin, OUTPUT);
  pinMode(latchpin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready to read...");
}


void loop()
{


  if(Serial.available() > 0){
    int readFromSerial = Serial.parseInt();
    Serial.println("Readed From Input");
    Serial.println(readFromSerial);
    readIntAsBinary(readFromSerial);
  }
}

void readIntAsBinary(int number){
  int tmp = number;
  int counter;


  for(int i = 0;i<=7;i++){
    shiftWrite(i, LOW);
    delay(10);
  }
  do{
    int b = tmp%2;
    Serial.println(b);
    tmp/=2;
    shiftWrite(counter++, b==0 ? LOW : HIGH);
    delay(20);
  }while(tmp>0);
  for(;counter<=7;counter++){
    shiftWrite(counter,LOW);
    delay(20);
  }
}


void shiftWrite(int desiredPin, boolean desiredState)
{
  bitWrite(data,desiredPin,desiredState);

  shiftOut(datapin, clockpin, MSBFIRST, data);

  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);
}

void oneAfterAnother()
{
  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);
    delay(delayTime);              
  }

  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, LOW);
    delay(delayTime);
  }
}


/*
oneOnAtATime()

This function will step through the LEDs, lighting one at at time.
*/

void oneOnAtATime()
{
  int index;
  int delayTime = 100; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}


/*
pingPong()

This function will step through the LEDs, lighting one at at time,
in both directions.
*/

void pingPong()
{
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // step through the LEDs, from 0 to 7

  for(index = 0; index <= 7; index++)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }

  // step through the LEDs, from 7 to 0

  for(index = 7; index >= 0; index--)
  {
    shiftWrite(index, HIGH);    // turn LED on
    delay(delayTime);       // pause to slow down the sequence
    shiftWrite(index, LOW); // turn LED off
  }
}


/*
randomLED()

This function will turn on random LEDs. Can you modify it so it
also lights them for random times?
*/

void randomLED()
{
  int index;
  int delayTime = 100; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching

  // The random() function will return a semi-random number each
  // time it is called. See http://arduino.cc/en/Reference/Random
  // for tips on how to make random() more random.

  index = random(8);    // pick a random number between 0 and 7

  shiftWrite(index, HIGH);  // turn LED on
  delay(delayTime);     // pause to slow down the sequence
  shiftWrite(index, LOW);   // turn LED off
}


/*
marquee()

This function will mimic "chase lights" like those around signs.
*/

void marquee()
{
  int index;
  int delayTime = 200; // Time (milliseconds) to pause between LEDs
                       // Make this smaller for faster switching

  // Step through the first four LEDs
  // (We'll light up one in the lower 4 and one in the upper 4)

  for(index = 0; index <= 3; index++)
  {
    shiftWrite(index, HIGH);    // Turn a LED on
    shiftWrite(index+4, HIGH);  // Skip four, and turn that LED on
    delay(delayTime);       // Pause to slow down the sequence
    shiftWrite(index, LOW); // Turn both LEDs off
    shiftWrite(index+4, LOW);
  }
}


/*
binaryCount()

Numbers are stored internally in the Arduino as arrays of "bits",
each of which is a 1 or 0. Just like the base-10 numbers we use
every day, The position of the bit affects the magnitude of its
contribution to the total number:

Bit position   Contribution
0              1
1              2
2              4
3              8
4              16
5              32
6              64
7              128

To build any number from 0 to 255 from the above 8 bits, just
select the contributions you need to make. The bits will then be
1 if you use that contribution, and 0 if you don't.

This function will increment the "data" variable from 0 to 255
and repeat. When we send this value to the shift register and LEDs,
you can see the on-off pattern of the eight bits that make up the
byte. See http://www.arduino.cc/playground/Code/BitMath for more
information on binary numbers.
*/

void binaryCount()
{
  int delayTime = 1000; // time (milliseconds) to pause between LEDs
                        // make this smaller for faster switching

  // Send the data byte to the shift register:

  shiftOut(datapin, clockpin, MSBFIRST, data);

  // Toggle the latch pin to make the data appear at the outputs:

  digitalWrite(latchpin, HIGH);
  digitalWrite(latchpin, LOW);

  // Add one to data, and repeat!
  // (Because a byte type can only store numbers from 0 to 255,
  // if we add more than that, it will "roll around" back to 0
  // and start over).

  data++;

  // Delay so you can see what's going on:

  delay(delayTime);
}

LCD improvement

It is the first time that we used LCD in this course. In this improvement, we used timer, interrupt and show the current temperature on LCD screen. We used setCursor() function for the location of the data on the screen. We used analogRead function while reading the temperature value.
                                             Berrak Şişman and İlker Çam


#include 
#include 


const int temperaturePin = 0;
LiquidCrystal lcd(12,11,5,4,3,2);
volatile int readEvent = 0;
void setup()
{

  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("Read Serial!");
  Serial.begin(9600);
  Timer1.initialize(8000000); // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
  Timer1.attachInterrupt(setFlag); // attach the service routine here
}

void loop()
{
    if(readEvent == 2){
      lcd.setCursor(0,1);
      lcd.print("Interrupt Calling");
      Serial.println("Interrupt Calling..");
      getTemp();
      readEvent = 0;
    }
}

void setFlag(){
  readEvent++;
}

void getTemp()
{
  float voltage,degreesC;
  voltage = (analogRead(temperaturePin) * 0.004882814);
  degreesC = (voltage - 0.5) * 100.0;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Temperature : ");
  lcd.print(degreesC);
}

Make a decision and change the speed of the motor : 2 push buttons and data taken from serial port (0 or 1)

In this improvement, we take binary data 0 or 1 from serial port. We have 2 push buttons. With using these three things, we make a decision; whether the speed of the motor increases or decreases. If our first button state is low, and the second one is high and also the data taken from serial port is 1 then, we choose to increase the speed. The other case is   the data taken from serial port is 1 but the button states are inverse of the first case, meaning that first button state low and second button state is high, we decrease the speed. In this code we used analogWrite() function while changing the value of speed. The photo of this improvement is given below.

Berrak Şişman & İlker Çam


Arduino code:


const int btn1Pin = 2;
const int btn2Pin = 3;
const int motorPin = 9;

int theBitThatIReadFromSerialIfTheMotorIsRunningOrNot = 1;
int motorSpeed = 0;
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(btn1Pin, INPUT);
  pinMode(btn2Pin, INPUT);
  Serial.begin(9600);
}


void loop()
{
     //serialSpeed();
     motor();
}

void motor(){
  int btnState, btn2State;
  btnState = digitalRead(btn1Pin);
  btn2State = digitalRead(btn2Pin);

  if(btnState == LOW && btn2State == HIGH && theBitThatIReadFromSerialIfTheMotorIsRunningOrNot == 1){
    motorSpeed = (motorSpeed+40);
    motorSpeed = constrain(motorSpeed,0,255);
    analogWrite(motorPin, motorSpeed);
  }else if(btnState == HIGH && btn2State == LOW && theBitThatIReadFromSerialIfTheMotorIsRunningOrNot == 1){
    motorSpeed = (motorSpeed-40);
    motorSpeed = constrain(motorSpeed,0,255);
    analogWrite(motorPin, motorSpeed);
  }

  if(Serial.available() > 0){
    int readed = Serial.parseInt();
    if(readed == 1){
      theBitThatIReadFromSerialIfTheMotorIsRunningOrNot = 1;
      if(motorSpeed<=0){
        motorSpeed = 200;
        analogWrite(motorPin, motorSpeed);
      }
    }else if(readed == 0){
      theBitThatIReadFromSerialIfTheMotorIsRunningOrNot = 0;
      if(motorSpeed>0){
        motorSpeed = 0;
        analogWrite(motorPin, motorSpeed);
      }
    }
  }

  delay(100);
}

Friday, February 27, 2015

Getting Started With Arduino



Arduino, it's the platform that anybody can prototype it's project with a little knowledge with electronics and programming.

There're many kinds and many manufactures of these platform and while it's open-source any qualified manufacturer can produce it.




The programming environment of arduino is called Arduino IDE, but also advanced users can use C to program the board.

In this blog, I'll weekly post projects which can be build with using SparkFun Inventors Kit.