Go Down

Topic: How use two ultrasonic sensors in arduino and pyserial (Read 1 time) previous topic - next topic

upendra123

I used two ultrasonic sensors. I want to sense the distance from both ultrasonic sensors and display some text in LCD display. I use arduino mega 2560.

This is my Arduino code 

Code: [Select]
int trigPin=36; //For first sensor
int echoPin=37; 
float pingTime; 
float targetDistance;
float speedOfSound=776.5;


int trigPin2=38; //For second sensor
int echoPin2=39;
float pingTime2; 
float targetDistance2;


// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(30, 31, 32, 33, 34, 35);


String str;

void setup() {
 
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  lcd.begin(16, 2);
  lcd.setCursor(0, 2);
 
}



void loop() {

//Read first sensor     
      digitalWrite(trigPin, LOW); //Set trigger pin low
      delayMicroseconds(2000); //Let signal settle
      digitalWrite(trigPin, HIGH); //Set trigPin high
      delayMicroseconds(15); //Delay in high state
      digitalWrite(trigPin, LOW); //ping has now been sent
      delayMicroseconds(10); //Delay in low state
      pingTime = pulseIn(echoPin, HIGH);  //pingTime is presented in microceconds
      pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000   (microseconds in a second)
      pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
      targetDistance= speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
      targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
      targetDistance= targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)
      Serial.print(targetDistance);
     
 //Read second sensor     
      digitalWrite(trigPin2, LOW); //Set trigger pin low
      delayMicroseconds(2000); //Let signal settle
      digitalWrite(trigPin2, HIGH); //Set trigPin high
      delayMicroseconds(15); //Delay in high state
      digitalWrite(trigPin2, LOW); //ping has now been sent
      delayMicroseconds(10); //Delay in low state
      pingTime2 = pulseIn(echoPin2, HIGH);  //pingTime is presented in microceconds
      pingTime2=pingTime2/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
      pingTime2=pingTime2/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
      targetDistance2= speedOfSound * pingTime2;  //This will be in miles, since speed of sound was miles per hour
      targetDistance2=targetDistance2/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
      targetDistance2= targetDistance2*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)
      Serial.println(targetDistance2);     
     
 
     
if (Serial.available()) { 
      str = "";                               // clear the current string content
      str = Serial.readStringUntil('\n');    // read the string until new line found \n 
      lcd.setCursor(0, 2);                   // set the cursor For 0,2
      if(str=="Free to park"){               // check for the first condition
        lcd.clear();                         // clear the LCD
        lcd.print("Free to Park..!");          // print the place where cursor set   
      }
      else if(str=="No Space"){
        lcd.clear();
        lcd.print("No Space..!");       
      }     
      delay(100);

}

}





this is my python code


Code: [Select]
from __future__ import print_function   
import pypyodbc
import serial
import time
import datetime
s = serial.Serial('COM31', 9600)
time.sleep(2)

conn = pypyodbc.connect('DRIVER={SQL Server};SERVER=IROSHEN-PC;DATABASE=EasyParkDB')
cur = conn.cursor()


while (1==1):
    #if (s.inWaiting()>0):
        myData = s.readline()
        myData2 = s.readline2()
        #print (myData
        distance = float(myData)
        distance2 = float(myData2)
        if(distance < 6 and distance2<6): 
            #cur.execute ("UPDATE TblBlock SET CurrentState=1 WHERE BlockID='3'")
            cur.execute('''UPDATE TblBlock SET CurrentState='1' WHERE BlockID='3';''')
            conn.commit()
            print (distance)
            s.write('No Space\n')
        else:
            cur.execute('''UPDATE TblBlock SET CurrentState='0' WHERE BlockID='3';''')
            conn.commit()
            print ("lk")
            s.write('Free to park\n')



There is an error in line

Code: [Select]

myData = s.readline()



I don't know how to read sense data from both sensors at same time..
please help me to solve this problem........

UKHeliBob

Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

upendra123

In python shell show this error


Traceback (most recent call last):
  File "D:\Arduino\Python\test.py", line 17
    myData2 = s.readline2()
AttributeError: 'Serial' object has no attribute 'readline2'

UKHeliBob

What has the Python error got to do with the Arduino reading two ultrasonic sensors ?

Surely all you have to do is read the first line into a variable then use the same method to read the second line into a second variable.
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

Robin2

In python shell show this error

AttributeError: 'Serial' object has no attribute 'readline2'
It is telling you clearly what the error is. Why are you trying to use the non existent readline2() ?

Your code should be
Code: [Select]
      myData = s.readline()
        myData2 = s.readline()



You may be interested in this Python comms demo.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

PaulS

Suppose that the first sensor results in a distance of 32, and that the second sensor results in a distance of 18. What the Arduino is sending is "3216".

How on earth do you propose to make sense of THAT on the other end?

Don'tyousupposesomekindofseparatorwouldbeagoodidea?
The art of getting good answers lies in asking good questions.

Robin2

Two or three hours spent thinking and reading documentation solves most programming problems.

PaulS

The art of getting good answers lies in asking good questions.

Go Up