Weird, I get the same issue with even simpler code (I just do the assignment and then watch the variable in the Stage window). Oddly, I can confirm that it works with the mBot Program for standalone because I tested it with a similar program that lights up the LEDs based on distance.
The pure Scratch program did not work with the ultrasonic sensor returning a zero.
Replacing the when [green flag] clicked block with the mBot Program block, the program worked properly when I uploaded it to to the mBot.
The Arduino source code that was generated from the second program is:
#include <Arduino.h>
#include <Wire.h>
#include <SoftwareSerial.h>
#include <MeMCore.h>
MeDCMotor motor_9(9);
MeDCMotor motor_10(10);
void move(int direction, int speed)
{
int leftSpeed = 0;
int rightSpeed = 0;
if(direction == 1){
leftSpeed = speed;
rightSpeed = speed;
}else if(direction == 2){
leftSpeed = -speed;
rightSpeed = -speed;
}else if(direction == 3){
leftSpeed = -speed;
rightSpeed = speed;
}else if(direction == 4){
leftSpeed = speed;
rightSpeed = -speed;
}
motor_9.run((9)==M1?-(leftSpeed):(leftSpeed));
motor_10.run((10)==M1?-(rightSpeed):(rightSpeed));
}
double angle_rad = PI/180.0;
double angle_deg = 180.0/PI;
double distance;
MeUltrasonicSensor ultrasonic_3(3);
MeRGBLed rgbled_7(7, 7==7?2:4);
void setup(){
}
void loop(){
distance = ultrasonic_3.distanceCm();
if((distance) < (10)){
rgbled_7.setColor(0,150,0,0);
rgbled_7.show();
}else{
if((distance) < (20)){
rgbled_7.setColor(0,150,150,0);
rgbled_7.show();
}else{
rgbled_7.setColor(0,0,150,0);
rgbled_7.show();
}
}
_loop();
}
void _delay(float seconds){
long endTime = millis() + seconds * 1000;
while(millis() < endTime)_loop();
}
void _loop(){
}
I wrote a separate version that doesn’t carry all of the code-generation boilerplate code, but it was essentially the same thing logically:
#include <MeMCore.h>
MeRGBLed leds(7, 2);
MeUltrasonicSensor ul(3);
double distance = 0.0;
void setup() {
Serial.begin(9600); // open serial port for logging
}
void loop() {
distance = ul.distanceCm(); // capture the distance in centimeters
Serial.println("Distance: " + String(distance)); // log the distance to the serial monitor
if (distance < 10) {
leds.setColor(0, 150, 0, 0); // less than 10 cm red leds
} else if (distance < 20) {
leds.setColor(0, 150, 150, 0); // less than 20 cm, greater than 10 yellow leds
} else {
leds.setColor(0, 0, 150, 0); // greater than 20 cm green leds
}
leds.show(); // change the color of the leds
}
It looks like there is something broken in the Scratch code but @tech_support would have to have the developers at Makeblock investigate further.
Regards,
Chuck