Hi I need a bit of help with my code for a project. I originally had it working with 2 sensors and an analog output (pwm):
I am having a few problems which include:
Refresh rate isn't what I am specifying.
Is not outputting 0-5v (pwm 0-255) values specified
I am using the Parallax Ping ultrasonic sensors.
int PINOUT = 3; //pwm pin 3. (output)
unsigned long timeOn = 5; // Change the number to set seconds to hold relays
unsigned long timeDeactivate = 10;
unsigned long timeOfDeactivation = 0;
unsigned long timeOfRelay1 = 0;
const double sensor1min = 100.00;
const double sensor1max = 10.00;
const double sensor2min = 75.00;
const double sensor2max = 5.00;
const double sensor3min = 120.00;
const double sensor3max = 10;
const int S1PIN = 7;
const int S2PIN = 8;
const int S3PIN = 9;
void setup() {
// initialize serial communication:
Serial.begin(9600);
pinMode(PINOUT, OUTPUT);
}
void loop()
{
if ( 0 && 0 ) { //Deactivate
timeOfDeactivation = millis();
Serial.println("==AUTOMATIC IS OFF==");
} else if (timeOfDeactivation != 0) {
Serial.println("==AUTOMATIC IS OFF==");
} else if ((((timeDeactivate * 1000) + timeOfDeactivation) < millis()) || timeOfDeactivation == 0){
timeOfDeactivation = 0;
long s1cm, s2cm, s3cm;
int s1pro, s2pro, s3pro, proout;
s1cm = getdistance(S1PIN);
if (s1cm < sensor1max) {
s1pro = 255;
} else if (s1cm > sensor1min) {
s1pro = 0;
} else {
s1pro = ((sensor1min - s1cm)/(sensor1min - sensor1max))*255;
}
analogWrite(PINOUT,proout);
s2cm = getdistance(S2PIN);
if (s2cm < sensor2max) {
s2pro = 255;
} else if (s2cm > sensor2min) {
s2pro = 0;
} else {
s2pro = ((sensor2min - s2cm)/(sensor2min - sensor2max))*255;
}
if (proout < s2pro) proout = s2pro;
analogWrite(PINOUT,proout);
s3cm = getdistance(S3PIN);
if (s3cm < sensor3max) {
s3pro = 255;
} else if (s3cm > sensor3min) {
s3pro = 0;
} else {
s3pro = ((sensor3min - s3cm)/(sensor3min - sensor3max))*255;
}
if (proout < s3pro) proout = s3pro;
analogWrite(PINOUT,proout);
Serial.print("Sensor 1: ");
Serial.print(s1cm);
Serial.print(" Sensor 2: ");
Serial.print(s2cm);
Serial.print(" Proportional Out (0-255): ");
Serial.print(s1pro);
Serial.print(" ; ");
Serial.print(s2pro);
Serial.print(" ; ");
//Serial.print(((sensor2min - s2cm)/(sensor2min - sensor2max))*255);
Serial.print(proout);
Serial.println();
}
delay(10);
}
long getdistance(int pin) {
long duration;
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(2);
digitalWrite(pin, HIGH);
delayMicroseconds(5);
digitalWrite(pin, LOW);
pinMode(pin, INPUT);
duration = pulseIn(pin, HIGH);
return duration / 29 / 2;
}