Формат печати в Arduino - PullRequest
0 голосов
/ 27 мая 2020
// 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 для int

2.54 как 02.54 для float

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

1 Ответ

0 голосов
/ 27 мая 2020

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

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

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

...