salve a tutti. Sono un nuovo utente ed ho cominciato da ieri ad usare arduino. Conosco abbastanza bene la programmazione quindi ho voluto cimentarmi direttamente con un progetto un pò più complicato rispetto ai tutorial accendi e spegni un led. Sto provando a collegare il sensore SRF02 ad arduino duemilanove per comandare l'intensità luminosa di un led. Questo è lo sketch su cui sto lavorando
#include <Wire.h>
#define srfAddress 0x73 // Address of the SRF08
#define cmdByte 0x00 // Command byte
#define rangeByte 0x02 // Byte for start of ranging data
byte highByte = 0x00; // Stores high byte from ranging
byte lowByte = 0x00; // Stored low byte from ranging
int brightness = 0; // how bright the LED is
int fadeAmount = 10; // how many points to fade the LED by
void setup(){
Serial.begin(9600); // Begins serial port for LCD_03
Wire.begin();
delay(100);
pinMode(11, OUTPUT);
}
void loop(){
int rangeData = getRange(); // Calls a function to get range
Serial.println(rangeData);
delay(100);
if (rangeData <= 60){
// set the brightness of pin 9:
analogWrite(11, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 50) {
fadeAmount = -fadeAmount ;
}
}
else {
digitalWrite(11, LOW);
}
}
int getRange(){ // This function gets a ranging from the SRF08
int range = 0;
Wire.beginTransmission(srfAddress); // Start communticating with SRF08
Wire.write((byte)cmdByte); // Send Command Byte
Wire.write(0x51); // Send 0x51 to start a ranging
Wire.endTransmission();
delay(100); // Wait for ranging to be complete
Wire.beginTransmission(srfAddress); // start communicating with SRFmodule
Wire.write(rangeByte); // Call the register for start of ranging data
Wire.endTransmission();
Wire.requestFrom(srfAddress, 2); // Request 2 bytes from SRF module
while(Wire.available() < 2); // Wait for data to arrive
highByte = Wire.read(); // Get high byte
lowByte = Wire.read(); // Get low byte
range = highByte*256 + lowByte; // Put them together
return(range); // Returns Range
}
questo codice fa più o meno ciò che voglio. In pratica se il sensore rileva qualcosa abbastanza vicino, finchè questa cosa resta vicina, il sensore cambia la sua intensità luminosa. Nel momento in cui la distanza aumenta il led si spegne. Ho due problemi. Il sensore non è preciso; ci sono infatti momenti in cui le rilevazioni sballano e il led dunque si spegne. Inoltre il processo di aumento e diminuzione della luminosità non è fluido. Avevo pensato che fosse legato al delay inserito nella funzione getRange() ed effettivamente provando ad abbassarlo l'effetto diventa più fluido. tuttavia se vado sotto i 100 millisecondi, le rilevazioni della distanza sballano completamente.
Come posso risolvere questi problemi?
Grazie a tutti in anticipo