我利用红外测距传感器和一个恒流驱动模块控制led灯的明暗,为什么我的pwm电压不会变,灯一直是暗的呢?
程序如下:
int pin = 9; //analog outint apin0 = A0; //analog in0
int apin1 = A1; //analog in1
int apin2 = A2; //analog in2
int sensorvalue0=0, sensorvalue1=0, sensorvalue2=0; //three values provided by sensors
int sensorvalue; //the sensor which is the largest, i.e. the right sensor value to use
int outputvalue=255; //output value for the PWM, 255 corresponds to the lowest output voltage, in order to protect the LEDs
int dpin0 = 2; //digital out, that is to control the relay
int dpin1 = 3;
int dpin2 = 4;
void setup()
{
//define each pin INPUT or OUTPUT
pinMode(pin, OUTPUT);
pinMode(apin0, INPUT);
pinMode(apin1, INPUT);
pinMode(apin1, INPUT);
pinMode(dpin0, OUTPUT);
pinMode(dpin1, OUTPUT);
pinMode(dpin2, OUTPUT);
Serial.begin(9600);
}
void loop()
{
//read the values provided by the sensors
//constrain these values between 0 and 500
sensorvalue0 = analogRead(apin0);
sensorvalue0 = constrain(sensorvalue0, 0, 500);
sensorvalue1 = analogRead(apin1);
sensorvalue1 = constrain(sensorvalue1, 0, 500);
sensorvalue2 = analogRead(apin2);
sensorvalue2 = constrain(sensorvalue2, 0, 500);
//select the largest value from the three
//then put the corresponding pin selected from dpin0, dpin1 and dpin2 to HIGH and put the others to LOW
if(sensorvalue0>sensorvalue1){
if(sensorvalue2>sensorvalue0 && sensorvalue2>200){
sensorvalue = sensorvalue2;
digitalWrite(dpin2, HIGH);
digitalWrite(dpin0, LOW);
digitalWrite(dpin1, LOW);
}
if(sensorvalue0>=sensorvalue2 && sensorvalue0>200){
sensorvalue = sensorvalue0;
digitalWrite(dpin0, HIGH);
digitalWrite(dpin1, LOW);
digitalWrite(dpin2, LOW);
}
}
else{
if(sensorvalue2>sensorvalue1 && sensorvalue2>200){
sensorvalue = sensorvalue2;
digitalWrite(dpin2, HIGH);
digitalWrite(dpin0, LOW);
digitalWrite(dpin1, LOW);
}
if(sensorvalue1>=sensorvalue2 && sensorvalue1>200){
sensorvalue = sensorvalue1;
digitalWrite(dpin1, HIGH);
digitalWrite(dpin0, LOW);
digitalWrite(dpin2, LOW);
}
}
//remap the input values from the sensor to the range for output(245~255)
//!!NOTE: if the number of the LEDs has changed, then the lower bound of the range needs to be changed also
//255--0ma 0--700ma
//so if the number of LEDs has increased, then you have to change the 245 to a lower number, I have written down this relation on the paper I give you
outputvalue = map(sensorvalue, 0, 500, 245, 255);
outputvalue = constrain(outputvalue, 0,255);
analogWrite(pin, outputvalue);
//used for debug using the serial(usb) port
//Serial.print("sensor = " );
//Serial.print(sensorvalue);
//Serial.print("\t output = ");
//Serial.println(outputvalue);
delay(2);
}
有大神能帮我解答吗,谢了~
|