Формат печати в ардуино

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;  // float distance ;

void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculating the distance
distance= duration*0.034/2;

// Prints the distance on the Serial Monitor
Serial.println(distance);
}

я хочу получить

1 как 01 для целого числа

2.54 как 02.54 для числа с плавающей запятой

в моем последовательном мониторе Arduino. Пожалуйста, как мне поступить. Мой датчик отправляет значение, не помещая перед ним ноль, что нормально. Как я могу изменить формат печати. Спасибо вам всем


person Coffmann    schedule 27.05.2020    source источник
comment
Может быть, это? arduino.stackexchange.com/questions/34929/ Или, возможно, этот forum.arduino.cc/index.php?topic=43562.0   -  person aMike    schedule 27.05.2020


Ответы (1)


Самый простой способ:

if (distance < 10) Serial.write('0'); Serial.println(distance);

Не обращает внимания на отрицательные целые числа, что может быть допустимо на расстоянии

person datafiddler    schedule 27.05.2020