Wednesday, November 12, 2014

Interfacing DHT11 humidity and temperature sensor with PIC16F877A

After interfacing the DHT11 with Arduino uno board at the following post:
ARDUINO Humidity & Temperature Measurement Using DHT11 Sensor
Now we are going to see how to interface this sensor with microchip pic16f877a.
There are some descriptions of how this sensor work  in the above link.
The circuit:
The below picture shows the schematic diagram of our circuit, the LCD is 16x2 and crystal is 12MHz.



A brief description of the code:
The code is written using MikroC compiler.
 First we must send a start signal to the sensor, we do that by configuring the pic pin connected to the sensor as output, the mcu sends 0 for 18ms then sends 1 for 30us.
After sending start signal to the sensor, the sensor will send a response signal to the mcu. To detect this signal mcu pin must be configured as input.
When the sensor finishes the response signal, it begins sending humidity and temperature data serially.
If there is a problem with the sensor or there is no sensor connected to the circuit, the LCD displays "there is no response from the sensor". And if there is a problem in the sensor which means the values are incorrect the LCD displays "Check sum error".


This video shows temperature and humidity in my home at: 18:33 11/13/2014 :
 




// LCD module connections
 sbit LCD_RS at RB5_bit;
 sbit LCD_EN at RB4_bit;
 sbit LCD_D4 at RB3_bit;
 sbit LCD_D5 at RB2_bit;
 sbit LCD_D6 at RB1_bit;
 sbit LCD_D7 at RB0_bit;
 sbit LCD_RS_Direction at TRISB5_bit;
 sbit LCD_EN_Direction at TRISB4_bit;
 sbit LCD_D4_Direction at TRISB3_bit;
 sbit LCD_D5_Direction at TRISB2_bit;
 sbit LCD_D6_Direction at TRISB1_bit; 
 sbit LCD_D7_Direction at TRISB0_bit;
 // End LCD module connections
 char *text,mytext[4];
 unsigned char  a = 0, b = 0,i = 0,t1 = 0,t2 = 0,
               rh1 = 0,rh2 = 0,sum = 0;
 void StartSignal(){
 TRISD.F2 = 0;    //Configure RD2 as output
 PORTD.F2 = 0;    //RD2 sends 0 to the sensor
 delay_ms(18);
 PORTD.F2 = 1;    //RD2 sends 1 to the sensor
 delay_us(30);
 TRISD.F2 = 1;    //Configure RD2 as input
  }
 void CheckResponse(){
 a = 0;
 delay_us(40);
 if (PORTD.F2 == 0){
 delay_us(80);
 if (PORTD.F2 == 1)   a = 1;   delay_us(40);}
 }
 void ReadData(){
 for(b=0;b<8;b++){
 while(!PORTD.F2); //Wait until PORTD.F2 goes HIGH
 delay_us(30);
 if(PORTD.F2 == 0)    i&=~(1<<(7-b));  //Clear bit (7-b)
 else{i|= (1<<(7-b));               //Set bit (7-b)
 while(PORTD.F2);}  //Wait until PORTD.F2 goes LOW
 }
 }
 void main() {
 TRISB = 0;        //Configure PORTB as output
 PORTB = 0;        //Initial value of PORTB
 Lcd_Init();
 while(1){
 Lcd_Cmd(_LCD_CURSOR_OFF);        // cursor off
 Lcd_Cmd(_LCD_CLEAR);             // clear LCD
  StartSignal();
  CheckResponse();
  if(a == 1){
  ReadData();
  rh1 =i;
  ReadData();
  rh2 =i;
  ReadData();
  t1 =i;
  ReadData();
  t2 =i;
  ReadData();
  sum = i;
  if(sum == rh1+rh2+t1+t2){
  text = "Temp:  .0C";
  Lcd_Out(1,6,text);
  text = "Humidity:  .0%";
  Lcd_Out(2,2,text);
  ByteToStr(t1,mytext);
  Lcd_Out(1,11,Ltrim(mytext));
  ByteToStr(rh1,mytext);
  Lcd_Out(2,11,Ltrim(mytext));}
  else{
  Lcd_Cmd(_LCD_CURSOR_OFF);        // cursor off
  Lcd_Cmd(_LCD_CLEAR);             // clear LCD
  text = "Check sum error";
  Lcd_Out(1,1,text);}
  }
  else { 
  text="No response";
  Lcd_Out(1,3,text);
  text = "from the sensor";
  Lcd_Out(2,1,text);
  }
  delay_ms(2000);
  }
  }

Saturday, November 8, 2014

PIC16F877A LCD Example

This is just an example to show how to interface 16x2 lcd with pic16f877a. The lcd is going to display "PIC16F877A" in the the first line and "LCD Example" in the second line. The code is written using MikroC compiler.
The  circuit diagram and MikroC code are below:





// LCD module connections
sbit LCD_RS at RB5_bit;
sbit LCD_EN at RB4_bit;
sbit LCD_D4 at RB3_bit;
sbit LCD_D5 at RB2_bit;
sbit LCD_D6 at RB1_bit;
sbit LCD_D7 at RB0_bit;
sbit LCD_RS_Direction at TRISB5_bit;
sbit LCD_EN_Direction at TRISB4_bit;
sbit LCD_D4_Direction at TRISB3_bit;
sbit LCD_D5_Direction at TRISB2_bit;
sbit LCD_D6_Direction at TRISB1_bit;
sbit LCD_D7_Direction at TRISB0_bit;
// End LCD module connections
char *text;
void main() {
TRISB = 0;
PORTB = 0;
Lcd_Init();
Lcd_Cmd(_LCD_CURSOR_OFF);        // cursor off
Lcd_Cmd(_LCD_CLEAR);             // clear LCD
text = "PIC16F877A" ;
Lcd_Out(1,4,text);
text = "LCD Example";
Lcd_Out(2,4,text);
while(1);                     //infinite loop
}

Tuesday, November 4, 2014

Real Time Clock

Now, I'm going to work with real time clocks, for that I will use the integrated circuit DS1307serial real time clock. I will use this ic with Arduino uno board and also I have to return to the pic microcontroller chip PIC16F877A. For the pic mcu I will use Microc and the full codes and schematics will be available on the next posts.
The DS1307 provides clock and calender. The clock shows seconds, minutes and hours and the calender shows day, month and year. The ds1307 uses I2C serial interface to transfer information with the microcontroller. More information in its datasheet.


Sunday, November 2, 2014

Cd-Rom 3 phase Sensored BLDC Motor Arduino Controller

BLDC (brushless dc) motors are three phase dc motors, unlike the simple dc motors the bldc motors are more difficult to control. These motors are used in many applications for examples rc airplans and rc cars.






In this post we will see how to control cd-rom sensored BLDC motor using Arduino uno board. But first there are some things we should know in order to control the motor in easy way.
The bldc motor that we are going to use is sensored via hall effect sensors (position sensors) attached with the motor(3 sensors). Each sensor outputs digital high for 180 electrical degrees and low for the other 180 electrical degrees.these sensors are used to tell us where is the position of the motor, then when we know the position of the motor we will energize just tow windings (of three). The below figure shows how sensors outputs and the corresponding voltage applied to the motor:



The motor is driven by a 3 phase bridge which contains 6 mosfets like the figure below:



And for the bridge I used to run the motor visit this post below:
Three Phase BLDC Motor Bridge
We can run the bldc motor in the cw or ccw rotaion but the sensor of the cw rotaion is different from the sensor of the ccw direction. The tow tables below show the sensor and the coils that activated at each phase:


Also for more information for the hall effect sensors and how to test it visit this link:
The complete circuit is shown below:


The Arduino code is below:
I used timer 2 interrupt every about 30ms to read the analog value and generate the corresponding pwm signal. For the pwm I used PWM.h library to generate 20KHz easily. Also in the code there are tow functions one for forward rotation and the other for the backward rotation.

#include <PWM.h>
int32_t frequency = 20000; //pwm frequency in Hz
unsigned int n = 0, timer2_initial_value, s = 0;
void setup(){
  InitTimersSafe();
  bool success = SetPinFrequencySafe(9, frequency);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(0, INPUT);
  pinMode(1, INPUT);
  pinMode(2, INPUT);
  pinMode(10, INPUT_PULLUP);
  pinMode(11, INPUT_PULLUP);
  pinMode(12, INPUT_PULLUP);
  // initialize timer2 interrupt for adc reading 
  noInterrupts();           // disable all interrupts
  TCCR2A = 0;
  TCCR2B = 0;
  timer2_initial_value = 0;  
  TCNT2 = timer2_initial_value;   // preload timer
  TCCR2B |= (1 << CS22) |(1 << CS21) | (1 << CS20); // 1024 prescaler 
  TIMSK2 |= (1 << TOIE2);   // enable timer overflow interrupt
  interrupts();             // enable all interrupts
}
 ISR(TIMER2_OVF_vect)        // interrupt service routine 
 {
  TCNT2 = timer2_initial_value;   // preload timer
  n++;
  if (n>20){
    n = 0;
   if (s != analogRead(A0)){
   s = analogRead(A0); 
  pwmWrite(9,s/4);}}
 }
int fwd(){
   while(1){
if (digitalRead(2)==1){
    if (digitalRead(1)==0){
      if (digitalRead(0)==1){
        digitalWrite(8,0);digitalWrite(7,0);digitalWrite(6,0);
        digitalWrite(5,1);digitalWrite(4,1);digitalWrite(3,0);}
      else {
        digitalWrite(8,1);digitalWrite(7,0);digitalWrite(6,0);
        digitalWrite(5,1);digitalWrite(4,0);digitalWrite(3,0);}}
        
     if (digitalRead(1)==1){
      if (digitalRead(0)==0){
        digitalWrite(8,1);digitalWrite(7,0);digitalWrite(6,0);
        digitalWrite(5,0);digitalWrite(4,0);digitalWrite(3,1);}}}
        
   
 if (digitalRead(2)==0){
    if (digitalRead(1)==1){
      if (digitalRead(0)==0){
        digitalWrite(8,0);digitalWrite(7,0);digitalWrite(6,1);
        digitalWrite(5,0);digitalWrite(4,0);digitalWrite(3,1);}
      else {
        digitalWrite(8,0);digitalWrite(7,1);digitalWrite(6,1);
        digitalWrite(5,0);digitalWrite(4,0);digitalWrite(3,0);}}
        
     if (digitalRead(1)==0){
      if (digitalRead(0)==1){
        digitalWrite(8,0);digitalWrite(7,1);digitalWrite(6,0);
        digitalWrite(5,0);digitalWrite(4,1);digitalWrite(3,0);}}}
   if (digitalRead(12)==0) break;}
}
 int bwd(){
   while(1){
if (digitalRead(2)==1){
    if (digitalRead(1)==0){
      if (digitalRead(0)==1){
        digitalWrite(8,0);digitalWrite(7,0);digitalWrite(6,1);
        digitalWrite(5,0);digitalWrite(4,0);digitalWrite(3,1);}
      else {
        digitalWrite(8,0);digitalWrite(7,1);digitalWrite(6,1);
        digitalWrite(5,0);digitalWrite(4,0);digitalWrite(3,0);}}
        
     if (digitalRead(1)==1){
      if (digitalRead(0)==0){
        digitalWrite(8,0);digitalWrite(7,1);digitalWrite(6,0);
        digitalWrite(5,0);digitalWrite(4,1);digitalWrite(3,0);}}}
        
   
 if (digitalRead(2)==0){
    if (digitalRead(1)==1){
      if (digitalRead(0)==0){
        digitalWrite(8,0);digitalWrite(7,0);digitalWrite(6,0);
        digitalWrite(5,1);digitalWrite(4,1);digitalWrite(3,0);}
      else {
        digitalWrite(8,1);digitalWrite(7,0);digitalWrite(6,0);
        digitalWrite(5,1);digitalWrite(4,0);digitalWrite(3,0);}}
        
     if (digitalRead(1)==0){
      if (digitalRead(0)==1){
        digitalWrite(8,1);digitalWrite(7,0);digitalWrite(6,0);
        digitalWrite(5,0);digitalWrite(4,0);digitalWrite(3,1);}}}
   if (digitalRead(12)==0) break;}
}
     
void loop(){
  digitalWrite(13, LOW);
  pwmWrite(9,s);
  digitalWrite(8,0);digitalWrite(7,0);digitalWrite(6,0);
  digitalWrite(5,0);digitalWrite(4,0);digitalWrite(3,0);
  if (digitalRead(10)==0) {digitalWrite(13, HIGH);bwd();}
  if (digitalRead(11)==0) {digitalWrite(13, HIGH);fwd();}
}


This videos shows my work:


Saturday, November 1, 2014

Sensored Cd-Rom BLDC Motor Hall Effect Sensors

In this post I will show how to test the hall effect sensors attached with the sensored bldc motor.
The hall effect sensors are necessary to know the position of the motor in order to energize just tow windings.
The hall effect sensor is a small IC has 4 pins in the cd-rom drive motor, vcc, gnd and the tow others are data pins.
This schematic diagram shows how to test the hall effect sensors:





This video shows how should it work:


Friday, October 31, 2014

Three Phase BLDC Motor Bridge

To control a three phase bldc motor you must have a bridge to switch the three phases on and off. This bridge consists of switches and some other electronic components. I used in my three phase bridge 6 mosfets, 3 N-type and 3 P-type. I used some other transistors and resistors to turn these mosfets on and off.
The schematic diagram of the three phase circuit is shown below:


We will use this circuit to control a cd-rom sensored three phase bldc motor speed and direction using arduino uno board.

Wednesday, October 29, 2014

Arduino DC Motor Control 2

After controlling a dc motor speed and direction using arduino uno board at this link Arduino DC Motor Control 1 I am going to remove the potentiometer and add two push buttons to control the speed up and down.
In the arduino uno board there are two external interrupts: int0 on digital pin 2 and int1 on digital pin 3. We will use int0 to speed up the motor and int1 to reduce the speed of our motor. I added an led to show that the speed is at maximum value (at pin 12).
The code of the interrupt is as:
  attachInterrupt(0, speed_up, FALLING);
  attachInterrupt(1, speed_down, FALLING);
 
 When the interrupt at pin 2 occurs a function called speed_up will be called and the 
 speed of our motor will be raised. When the interrupt at pin 3 occurs a function called
 speed_down will be called and the speed is going to go down.
 The circuit is shown below: 



The arduino code is below:


#include <PWM.h>
int32_t frequency = 20000; //pwm frequency in Hz
  int s = 0;
   void setup(){
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  attachInterrupt(0, speed_up, FALLING);
  attachInterrupt(1, speed_down, FALLING);
   InitTimersSafe();
  bool success = SetPinFrequencySafe(9, frequency);
  }
 int fwd(){
   while(1){
   digitalWrite(0,HIGH);
   digitalWrite(1,LOW);
   if (digitalRead(6)==0) break;}}
  
 int pwd(){
   while(1){
   digitalWrite(0,LOW);
   digitalWrite(1,HIGH);
   if (digitalRead(6)==0) break;}}
   
  void loop()
 {
  digitalWrite(0,LOW);
  digitalWrite(1,LOW);
  digitalWrite (12,LOW);
  digitalWrite(13, LOW);
  pwmWrite(9,s);
  if (digitalRead(4)==0) {digitalWrite(13, HIGH);fwd();}
  if (digitalRead(5)==0) {digitalWrite(13, HIGH);pwd();}
 }
 void speed_up(){
   s = s + 5;
   if (s >255){
    s = 255;
    digitalWrite (12,HIGH);}
    else digitalWrite (12,LOW);
 pwmWrite(9,s);
  }
 void speed_down(){
   s = s - 5;
   if (s <5) s = 0;
   pwmWrite(9,s);
   digitalWrite (12,LOW);
  }

Last this video has some explanations:


Saturday, October 25, 2014

Arduino DC Motor Control 1

I have finished with constructing the circuit of controlling the speed and direction of 12V dc motor with arduino uno board via 3 wires, 1 for the speed and the 2 others for the direction. This circuit uses pwm technique to control the speed, and the direction is selected by turning 4 mosfets on and off, these 4 mosfets makes our H bridge circuit (For the H-bridge circuit I used visit this TOPIC).
Also the pwm frequency is 20KHz through pin 9. (about arduino pwm: Arduino PWM)
In the circuit the are 7 LEDs connected to shift register 74HC164N to show the speed level of our motor.
In the program I used timer 2 interrupt every about 300ms to read the analog value at A0 to generate the pwm signal and display the speed level.
The H-bridge circuit is shown below:

The complete circuit is:


And the code is below:


#include <PWM.h>
unsigned char k=0, l=0, m=0, n=0;
int32_t frequency = 20000; //pwm frequency in Hz
  int timer2_initial_value,s;
   void setup(){
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
   InitTimersSafe();
  bool success = SetPinFrequencySafe(9, frequency);
      
  // initialize timer2 interrupt for adc reading 
  noInterrupts();           // disable all interrupts
  TCCR2A = 0;
  TCCR2B = 0;
  timer2_initial_value = 0;  
  TCNT2 = timer2_initial_value;   // preload timer
  TCCR2B |= (1 << CS22) |(1 << CS21) | (1 << CS20); // 1024 prescaler 
  TIMSK2 |= (1 << TOIE2);   // enable timer overflow interrupt
  interrupts();             // enable all interrupts
 }

 ISR(TIMER2_OVF_vect)        // interrupt service routine 
 {
  TCNT2 = timer2_initial_value;   // preload timer
  n++;
  if (n>20){
    n = 0;
    k = 0;
    if (s != analogRead(A0)){
   s = analogRead(A0); 
  pwmWrite(9,s/4);
  if (s > 950) l = 0;
  else{ if (s > 850) l = 1;
        else{ if (s > 720) l = 3;
              else{ if (s > 600) l = 7;
                    else{ if (s > 480) l = 15;
                          else{ if (s > 350) l = 31;
                                else{ if (s > 150) l = 63;
                                      else l = 127;}}}}}}
 for(m=0;m<7;m++){  //send data serially to speed level via shift register
   digitalWrite (12,bitRead(l,k));
   digitalWrite (11,1);
   digitalWrite (11,0);k++;}
  }
 }
 }
 int fwd(){
   while(1){
   digitalWrite(0,HIGH);
   digitalWrite(1,LOW);
   if (digitalRead(4)==0) break;}}
  
 int pwd(){
   while(1){
   digitalWrite(0,LOW);
   digitalWrite(1,HIGH);
   if (digitalRead(4)==0) break;}}
   
  void loop()
 {
   k = 0;
   l = 127;   //all 7 leds are off
  digitalWrite(0,LOW);
  digitalWrite(1,LOW);
  digitalWrite(13, LOW);
  if (digitalRead(2)==0) {digitalWrite(13, HIGH);fwd();}
  if (digitalRead(3)==0) {digitalWrite(13, HIGH);pwd();}
  
  for(m=0;m<7;m++){
   digitalWrite (12,bitRead(l,k));
   digitalWrite (11,1);
   digitalWrite (11,0);k++;}
 }


Monday, October 20, 2014

H Bridge Circuit

I have constructed my own h bridge circuit to control the speed and direction of 12V dc motor. With the H-bridge I can control dc motor forward and backward using two wires, and the speed is controlled by a third wire witch is connected to a pwm signal.
Basic Operation Of The H-Bridge:
The basic circuit of the H-bridge is simply contains a dc voltage source,4 switches and load as shown in the following figure:



Now, if S1 and S4 are ON (S2 and S3 must be OFF) the current will flow from positive to negative across the motor and the motor will run at the forward direction.



If S2 and S3 are ON (S1 and S4must be OFF) the current will flow according to the following diagram and our motor will have backward direction:


In our circuit we are going to use mosfets as switches.
2 X IRF4905 (P-type)
2 X IRF3205 (N-type)
The full circuit is shown in the following figure:
IN1 & IN2 to control the direction of the motor
If IN1 = IN2 = 0 the motor is at OFF state (1 means 5V and 0 gnd)
If IN1 =1 & IN2 = 0 forward direction
If IN1 =0 & IN2 = 1 backward direction
Note that IN1 & IN2 must not equal to 1 at the same time.
PWM pin is connected to a pwm signal. If pwm = 1 means full speed.






Sunday, October 5, 2014

Arduino PWM

Arduino uno board uses timers to generate pwm signals on pins 3,5,6,9,10 and 11 using analogwrite() command. These pwm signals have fixed frequency of 490Hz unless pins 5 and 6 have frequency equals to 980Hz. if we need different frequency we will use the pwm library.
Using pwm library for arduino we can adjust our pwm frequency in easy way, this library works with some pins in the arduino uno board, and the command used is:
  pwmWrite(pin_number,duty_cycle);
 Here is an example which generate a pwm signal on pin 9 with a frequency of 20KHz:
 
#include <PWM.h>

int32_t frequency = 20000;

void setup(){
  InitTimersSafe();
  bool success = SetPinFrequencySafe(9, frequency);
  if(success) {
    pinMode(13, OUTPUT);
    digitalWrite(13, HIGH);    
  }
}
void loop(){
  int s = analogRead(A0);
  pwmWrite(9,s/4);
  delay(30);
 
}  


Sunday, September 14, 2014

ARDUINO Humidity & Temperature Measurement Using DHT11 Sensor

In this project we are going to interface the arduino uno with DHT11 digital humidity and temperature sensor.
About DHT11 humidity and temperature sensor:
The DHT11 sensor comes in a single row 4-pin package and operates from 3.5 to 5.5V power supply. It can measure temperature from 0-50 °C with an accuracy of ±2°C and relative humidity ranging from 20-95% with an accuracy of  ±5%. The sensor provides fully calibrated digital outputs for the two measurements. It has got its own proprietary 1-wire protocol, and therefore, the communication between the sensor and a microcontroller is not possible through a direct interface with any of its peripherals. The protocol must be implemented in the firmware of the MCU with precise timing required by the sensor.



The following timing diagrams describe the data transfer protocol between a MCU and the DHT11 sensor. The MCU initiates data transmission by issuing a “Start” signal. The MCU pin must be configured as output for this purpose. The MCU first pulls the data line low for at least 18 ms and then pulls it high for next 20-40 us before it releases it. Next, the sensor responds to the MCU “Start“  signal by pulling the line low for 80 us followed by a logic high signal that also lasts for 80 us. Remember that the MCU pin must be configured to input after finishing the “Start“ signal. Once detecting the response signal from the sensor, the MCU should be ready to receive data from the sensor. The sensor then sends 40 bits (5 bytes) of data continuously in the data line. Note that while transmitting bytes, the sensor sends the most significant bit first.


Data consists of decimal and integral parts. A complete data transmission is 40bit, and the sensor sends higher data bit first.
Data format: 8bit integral RH data + 8bit decimal RH data + 8bit integral T data + 8bit decimal T data + 8bit check sum. If the data transmission is right, the check-sum should be the last 8bit of "8bit integral RH data + 8bit decimal RH data + 8bit integral T data + 8bit decimal T data".
The DHT11 is a digital sensor so it sends 1's and 0's, but it is very important to know how it sends the digital data. The figure below shows how the sensor sends its information:


The Circuit:
The figure below shows the wiring of our circuit using arduino uno board, DHT11 sensor and 16X2 LCD display:

   



 #include <LiquidCrystal.h>
 LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
 byte deg[7] = {           //to display ° character
  B01110,
  B01010,
  B01110,
  B00000,
  B00000,
  B00000,
  B00000,
  };
 unsigned char a, b,i,rh1,rh2,t1,t2,sum;
 void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.createChar(0, deg);
 }
 int startsignal(){
  pinMode(8, OUTPUT);
  digitalWrite(8,LOW);
  delay(18);
  digitalWrite(8,HIGH);
  delayMicroseconds(30);digitalWrite(8,LOW);
  pinMode(8, INPUT);}
  
 int checkresponse(){
  a = 0;delayMicroseconds(40);
  if(digitalRead(8)==LOW){
    delayMicroseconds(80);
    if(digitalRead(8)==HIGH)
     a = 1;}
    delayMicroseconds(40);
  }
 
 int readdata(){
 for(b=0;b<8;b++){ 
   while(!digitalRead(8));  //Wait pin8 goes high
   delayMicroseconds(30);
   if(digitalRead(8)==LOW){ 
    bitClear(i,7-b);}
   else { bitSet(i,7-b); 
       while(digitalRead(8));//Wait pin8 goes low
      }
      }
  }
 void loop() {
  startsignal();    //send the start signal to the sensor
  checkresponse();  //check if the sensor sends the response signal
  if (a==1){
   readdata();
   rh1 = i;
   readdata();
   rh2 = i;
   readdata();
   t1=i;
   readdata();
   t2 = i;
   readdata();
   sum = i;
   if (sum == rh1+rh2+t1+t2){      //Checksum
     //Display Temperature  
     lcd.clear();
     lcd.setCursor(0, 0); lcd.print("Temp    =   .0 C");
     lcd.setCursor(10, 0); lcd.print(t1);
     lcd.setCursor(14, 0);lcd.write(byte(0));
     //Display Humidity:
     lcd.setCursor(0, 1); lcd.print("Humidity=   .0%");
     lcd.setCursor(10, 1); lcd.print(rh1);
   }
   else{        //If the checksum is incorrect
   lcd.clear();
     lcd.setCursor(1, 0); lcd.print("Checksum error");}  
 }
   else {       //If the sensor does not respond
    lcd.clear(); 
    lcd.setCursor(2, 0); lcd.print("no response");
    lcd.setCursor(0, 1); lcd.print("from the sensor");
    } 
 delay(1000); 
 }    



Tuesday, September 2, 2014

LED blink without delay, arduino timer interrupt

Blink Without Delay:

Sometimes you need to do two things at once. For example you might want to blink an LED (or some other time-sensitive function) while reading a button press or other input. In this case, you can't use delay(), or you'd stop everything else the program while the LED blinked. The program might miss the button press if it happens during the delay(). This sketch demonstrates how to blink the LED without using delay(). It keeps track of the last time the Arduino turned the LED on or off. Then, each time through loop(), it checks if a long enough interval has passed. If it has, it toggles the LED on or off.

Circuit:


 
We can make this LED blink without delay using tow different codes: 
Code 1:
This code below uses the millis() function, a command that returns the number of milliseconds since the Arduino board started running its current program, to blink an LED.


long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(13, OUTPUT);      
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;  
    // toggle the state of pin 13:
    digitalWrite(13, !digitalRead(13));
  }
}



Code 2:
Resetting the millis() function is not easy and this function stay running and until it reaches the limit value of a 4 byte unsigned number (about 49 continuous days)  then it returns to 0 where our function can not affect anymore 
This code uses timer1 interrupt every 1000 ms to make our led blink.

  int timer1_value;
   void setup()
  {
  pinMode(13, OUTPUT);

  // initialize timer1 
  noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;

  // Set timer1_value to the correct value for our interrupt interval
  timer1_value = 3036;   // preload timer 65536-16MHz/(256*1Hz)
  
  TCNT1 = timer1_value;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler 
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();             // enable all interrupts
 }

 ISR(TIMER1_OVF_vect)        // interrupt service routine 
 {
  TCNT1 = timer1_value;   // preload timer
  digitalWrite(13, !digitalRead(13));
 }

  void loop()
 {
  // write your program...
 }




Arduino Timer/Counter

Timer/Counter:
A timer/counter is a piece of hardware built in the Arduino ATmega microcontroller. It is like a clock, and can be used to measure time events.
The timer can be programmed by some special registers. You can configure the pre-scaler for the timer, or the mode of operation and many other things.
The Arduino board is based on the Atmel AVR ATmega168 or the ATmega328 microcontroller. These chips are pin compatible and only differ in the size of internal memory. Both have 3 timers, called Timer0, Timer1 and Timer2. Timer0 and Timer2 are 8bit timer, where Timer1 is a 16bit timer.

Timer0:
 Timer0 is a 8bit timer.
 In the Arduino world Timer0 is been used for the timer functions, like delay(), millis() and micros().
 If you change Timer0 registers, this may influence the Arduino timer function. So you should know what 
 you are doing.
Timer1:
 Timer1 is a 16bit timer.
 In the Arduino world the Servo library uses Timer1 on Arduino Uno (Timer5 on Arduino Mega).
Timer2:
 Timer2 is a 8bit timer like Timer0.
 In the Arduino work the tone() function uses Timer2.
 
Arduino uno timer/counter1 registers and time frequency:
  • TCCRx - Timer/Counter Control Register. The pre-scaler can be configured here. 
  • TCNTx - Timer/Counter Register. The actual timer value is stored here. 
  • Timer/Counter Interrupt Mask Register. To enable/disable timer interrupts.









Sunday, August 24, 2014

ARDUINO 0-5 V Voltmeter

Using the equipped analog to digital converter with Arduino uno board we can make a 0-5v voltmeter and display it in a 4 digit 7 segment display.




const unsigned char srdata=2, srclk=3, digit4=4, digit3=5, digit2=6, digit1=7;
unsigned int i = 0;
float j = 0;
unsigned char d=0,k=0,l=0,m=0,n=0,s=0;

int seg (){
  if (k==0) l=64;
  if (k==1) l=121;
  if (k==2) l=36;
  if (k==3) l=48;
  if (k==4) l=25;
  if (k==5) l=18;
  if (k==6) l=2;
  if (k==7) l=120;
  if (k==8) l=0;
  if (k==9) l=16;
  return k;
}

void setup() {
  pinMode(srdata, OUTPUT);
  pinMode(srclk, OUTPUT);
  pinMode(digit4, OUTPUT);
  pinMode(digit3, OUTPUT);
  pinMode(digit2, OUTPUT);
  pinMode(digit1, OUTPUT);
    }

void loop(){
  j = analogRead(A0);
  i = j*5000/1023;
   if(d==0) {digitalWrite(digit4,LOW); digitalWrite(digit3,HIGH);
             digitalWrite(digit2,HIGH);digitalWrite(digit1,HIGH);
 k=i%10;
 seg();
 n=0;
 for(m=0;m<7;m++){
   digitalWrite (srdata,bitRead(l,n));
   digitalWrite (srclk,1);
   digitalWrite (srclk,0);n++;
   }delay(4);
   d=1;
 }
 
 if(d==1) {digitalWrite(digit4,HIGH); digitalWrite(digit3,LOW);
           digitalWrite(digit2,HIGH);digitalWrite(digit1,HIGH);
 k=(i/10)%10;
 seg();
 n=0;
 for(int m=0;m<7;m++){
   digitalWrite (srdata,bitRead(l,n));
   digitalWrite (srclk,1);
   digitalWrite (srclk,0);n++;
   }delay(4);d=2;
 }
 
 if(d==2) {digitalWrite(digit4,HIGH); digitalWrite(digit3,HIGH);
             digitalWrite(digit2,LOW);digitalWrite(digit1,HIGH);
 k=(i/100)%10;
 seg();
 n=0;
 for(int m=0;m<7;m++){
   digitalWrite (srdata,bitRead(l,n));
   digitalWrite (srclk,1);
   digitalWrite (srclk,0);n++;
   }delay(4);d=3;
 }
 
 if(d==3) {digitalWrite(digit4,HIGH); digitalWrite(digit3,HIGH);
            digitalWrite(digit2,HIGH);digitalWrite(digit1,LOW);
 k=(i/1000)%10;
 seg();
 n=0;
 for(int m=0;m<7;m++){
   digitalWrite (srdata,bitRead(l,n));
   digitalWrite (srclk,1);
   digitalWrite (srclk,0);n++;
   }delay(4);d=0;
 }
}