Continue to Site

Reply to thread

got it, i rectified the code. but now the problem is im getting my distance as 0:


[syntax=C]#include <reg51.h>

#define lcd_data P2

sbit rs=P1^0; //reg select

sbit rw=P1^1; //rewrite

sbit en=P1^2;  //enable

sbit trig=P1^3;

sbit echo=P1^4;

int distance;

int time;

int i=0,j=0;

char str[4];


void lcd_init();

void cmd(unsigned char a);

void dat(unsigned char b);

void show(unsigned char *s);

void lcd_delay();


void lcd_init()

{

    cmd(0x38);   //defining is first, the peripherals and the line

    cmd(0x0e); 

    cmd(0x01);

    cmd(0x06);  //entry mode - after refreshing we're ready to use it

    cmd(0x0c);  //defining cursor

    cmd(0x80);    // start from the first row first column

}


void cmd(unsigned char a)

{

    lcd_data=a;

    rs=0;   //registers select

    rw=0; // write mode

    en=1; //enabling writing to the registers, power should be on when in use

    lcd_delay();

    en=0;

}


void dat(unsigned char b)

{

    lcd_data=b;

    rs=1;

    rw=0;

    en=1;

      lcd_delay();

    en=0;

}


void show(unsigned char *s)

{

    while(*s) {

        dat(*s++);

    }

}


void lcd_delay(){

    int i;

    for (i=0;i<10000;i++){

    }

}

      

void send_pulse(){

    trig=1;

    TMOD = 0x01;

    TH0 = 0xff;

    TL0 = 0xf6;

    TR0 = 1;      

  while (TF0 == 0);

  TR0 = 0;     

    TF0 = 0;         

    trig=0;

}


unsigned int ultrasonic(){

    TMOD = 0x01;         

  TH0 = 0x00;          

  TL0 = 0x00;

    TR0=1;

    send_pulse();

    while (!echo);

    while (echo);

    TR0=0;

    time=(TH0 << 8) | TL0;

    return time/58;

}


void intToString(unsigned int num, char *str) {

    int i = 0,k=0,j=0;

    do {

        str[i++] = (num % 10) + '0';

        num /= 10;

    } while (num != 0);

    str[I] = '\0';

    for ( j = 0, k = i - 1; j < k; j++, k--) {

        char temp = str[j];

        str[j] = str[k];

        str[k] = temp;

    }

}


void main(){

    lcd_init();

    while(1){

              cmd(0x80);

            show("Distance");

                    distance=ultrasonic();

              intToString(distance, str);

                    cmd(0xc0);

                    show (str);

                    lcd_delay();

                    cmd(0x01);

                    lcd_delay();

    }

}[/syntax][/I]


Part and Inventory Search

Back
Top