Floating points numbers, round, analogWrite

I've had trouble diagnosing this issue in my code,

analogWrite(LED, round(getDist()) % 100);

returns
Compilation error: invalid operands of types 'float' and 'int' to binary 'operator%'
this is the full code

#include <math.h>
#define LED 15
#define trigPin 19
#define echoPin 18
#define MAX_DISTANCE 700
float timeOut = MAX_DISTANCE * 60;
int soundVelocity = 340;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(trigPin,OUTPUT);
 pinMode(echoPin,INPUT);
 Serial.begin(115200);

}

void loop() {
  
  delay(100);
  Serial.println("Distance: ");
  Serial.print(getDist());
  Serial.println("cm");
  analogWrite(LED, round(getDist()) % 100);
}

float getDist() {
 unsigned long pingTime;
 float distance;
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);
 pingTime = pulseIn(echoPin, HIGH, timeOut);
 distance = (float)pingTime * soundVelocity / 2 / 10000;
 return distance;
}

Try


analogWrite(LED, ((int)round(getDist()))% 100);

operator% is remainder of integer division - try casting the double result of round to int

analogWrite(LED, (int)(round(getDist())) % 100);
1 Like

What is your intention with this bit? Do you really want to use "remainder of integer division"?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.