Et hop voilà le code version 2.
// # Author : Hugues Lepesant // # Date : 24/04/2014 // # Version : 0.2 // # URM Code based on Jiang's work from DFRobot // # Product name:ultrasonic scanner Kit // # Product SKU:SEN0001 // # Description: // # The Sketch for scanning 180 degree area 4-500cm detecting range // # Connection: // # Pin 1 VCC (URM V3.2) -> VCC (Arduino) // # Pin 2 GND (URM V3.2) -> GND (Arduino) // # Pin 4 PWM (URM V3.2) -> Pin 3 (Arduino) // # Pin 6 COMP/TRIG (URM V3.2) -> Pin 5 (Arduino) // # Pin mode: PWM // # Working Mode: PWM passive control mode. // # If it is your first time to use it,please make sure the two jumpers to the right hand // # side of the device are set to TTL mode. You'll also find a secondary jumper on // # the left hand side, you must break this connection or you may damage your device. int URPWM=3; // PWM Output 0-25000us,every 50us represent 1cm int URTRIG=5; // PWM trigger pin int pinGreen = 2; int pinYellow = 6; int pinRed = 7; int duration = 1000; int distMinimum = 100; // 100 cm int distMedium = 150; // 150 cm boolean up=true; // create a boolean variable unsigned long time; // create a time variable unsigned long urmTimer = 0; // timer for managing the sensor reading flash rate unsigned int Distance=0; uint8_t EnPwmCmd[4]={0x44,0x22,0xbb,0x01}; // distance measure command void setup() { // Serial initialization Serial.begin(9600); // Sets the baud rate to 9600 pinMode(pinGreen, OUTPUT); digitalWrite(pinGreen, LOW); pinMode(pinYellow, OUTPUT); digitalWrite(pinYellow, LOW); pinMode(pinRed, OUTPUT); digitalWrite(pinRed, LOW); PWM_Mode_Setup(); } void loop() { Distance = PWM_Mode(); Serial.print("Distance = "); Serial.print(Distance); Serial.println(" cm"); if ( Distance > distMedium ) { digitalWrite(pinGreen, HIGH); digitalWrite(pinYellow, LOW); digitalWrite(pinRed, LOW); } if ( Distance > distMinimum && Distance < distMedium ) { digitalWrite(pinGreen, LOW); digitalWrite(pinYellow, HIGH); digitalWrite(pinRed, LOW); } if ( Distance < distMinimum ) { digitalWrite(pinGreen, LOW); digitalWrite(pinYellow, LOW); digitalWrite(pinRed, HIGH); tone(8, 330, duration); // noTone(8); } delay(2000); } void PWM_Mode_Setup(){ pinMode(URTRIG,OUTPUT); // A low pull on pin COMP/TRIG digitalWrite(URTRIG,HIGH); // Set to HIGH pinMode(URPWM, INPUT); // Sending Enable PWM mode command for (int i=0;i<4;i++) { Serial.write(EnPwmCmd[i]); } } int PWM_Mode(){ // a low pull on pin COMP/TRIG triggering a sensor reading digitalWrite(URTRIG, LOW); digitalWrite(URTRIG, HIGH); // reading Pin PWM will output pulses unsigned long DistanceMeasured=pulseIn(URPWM,LOW); if (DistanceMeasured==50000) { // the reading is invalid. return 0; } else { return DistanceMeasured/50; // every 50us low level stands for 1cm } }