Why would a sonar sensor return a value of -1 and not respond? In our case the distance is fixed at around 45 mm. It doesn’t make any difference if we use mm, inch or cm and we have switched the input and output on the cortex. Is it a programming problem?
Sonar returns -1 when out of range (object too close or too far away), or when not initialized properly by your software, or when input/output are not correctly connected to the cortex.
The input goes to the first dgtl port and the output to the second or succeeding dgtl port correct? I’ve tried changing out the sensor and we get the same result. I suspect its the software (Robot C) not interfacing with the sonar sensor correctly. What exactly would I do to correct that?
Here is the simple code I’m using just to get the sensors communicating. We are building pin ball machines and int player is the scoring mechanism.
pinball test.c (822 Bytes)
int player = 0;
int sonar_value;
while (true)
sonar_value = SensorValue(sonarSensor);
{
}
This section of code is the problem; when you have a while loop that is not immediately followed by an opening brace (and later closed with a closing brace), the loop will only execute the next line of code. In this case, the sonar_value variable will be continually updated with the value of the sonar sensor but nothing else will run.
Instead, make sure that the variable assignment is placed inside of the while loop’s curly braces to ensure that the entirety of the code is looped:
int player = 0;
int sonar_value;
while (true)
{
sonar_value = SensorValue(sonarSensor);
if (SensorValue[lineFollower] < 2800)
{
player +=100;
}
if (SensorValue[sonarSensor] < 35)
{
player +=50;
}
else
{
player ++;
}
if (SensorValue[limit] == 1)
{
player +=75;
}
if (SensorValue[limit2] == 1)
{
player +=25;
}
clearDebugStream();
writeDebugStream("Player: %d", player);
}
Edit: Note that you are running a tight loop; because the loop will be running (and checking conditions/modifying scores) continually, you may see your score skyrocket fairly quickly.
John Watson I changed the code as you suggested by putting the sonar_value inside the loop, that doesn’t work either, we do get escalating scores however, so will work on that.
If I try a different sonar sensor and take it out of the pinball machine it just reads 6187 and 6188 in the sensor debug window. It looks like its trying to respond as we wave something in front as those two numbers flash red and white.
You do have a battery plugged in? I know it sounds like a silly question but using the USB cable you can program but without the battery the sensors will not work.
Can you hear the ultrasonic sensor clicking?
hahahahaha Yes I’ve got the battery connected and the cortex turned on.
I have three other sensors on the same program that are all returning values: 2 limit switches and a line follower.