Problem with trinket and MaxSonar sensor

Adafruit's tiny microcontroller platform. Please tell us which board you are using.
For CircuitPython issues, ask in the Adafruit CircuitPython forum.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
BecksBC3
 
Posts: 1
Joined: Fri Nov 18, 2016 5:49 pm

Problem with trinket and MaxSonar sensor

Post by BecksBC3 »

I'm trying to build a simple proximity sensor that will beep every time an object gets within a certain distance of the sensor. However, the sensor is going off continuously, despite there being nothing for it to detect. I'm wondering if it's a problem with the code I'm using, and I'm hoping someone here can tell me if there are problems with it. Without further ado:

//November 18, 2016
//trinket pro 5v 16MHz with MaxSonar 1260 ultrasonic sensor and buzzer

//Digital pin 5 for reading in the pulse width from the MaxSonar device.
//This variable is a constant because the pin will not change throughout execution of this code.
const int pwPin = 5;
//Digital pin 4 for controlling voltage to the alarm buzzer
const int sound = 4;
//set threshold distance below which the alarm will sound (inches)
const int threshold=20;
//variables needed to store values
long pulse, inches, cm;

void loop()
{
pinMode(pwPin, INPUT);
pinMode(sound, OUTPUT);

//Used to read in the pulse that is being sent by the MaxSonar device.
//Pulse Width representation with a scale factor of 147 uS per Inch.

pulse = pulseIn(pwPin, HIGH);
//147uS per inch
inches = pulse / 147;
//change inches to centimetres
cm = inches * 2.54;

if( inches < threshold ){
digitalWrite( sound, HIGH);
delay(2000);
digitalWrite( sound, LOW);
}
}

I've gone through it line by line and it all seems to make sense, but I'm very new to this so what do I know. Thanks for the help.

User avatar
caitlinsdad
 
Posts: 627
Joined: Fri Feb 24, 2012 4:23 pm

Re: Problem with trinket and MaxSonar sensor

Post by caitlinsdad »

Could you post a pic of your wiring to the sensor and the board? From the datasheet http://www.maxbotix.com/documents/XL-Ma ... asheet.pdf it looks like pin 2 on the sensor should give the pulse width read by pin 5 on your Trinket.

I haven't used the sensor you have but when running the sketch, it is helpful to have the serial monitor running in the IDE. You can add serial.begin and serial.print commands to display the values of variables as the program is running to see if the data being read makes sense. Good luck.

Locked
Please be positive and constructive with your questions and comments.

Return to “Trinket ATTiny, Trinket M0”