Wikipédia de RayMind
acs712
De RayMind wiki
Révision datée du 23 janvier 2017 à 10:00 par Jean-Claude (discussion | contributions)
Détection de courant à base du module ACS712 et arduino
Code arduino :
[1]- ↑ // Advanced Sensing with ASC712 // Using Calibration to find sensor 0 // then sensing by compiling multiple readings to obtain an RMS (Root Mean Square). // Derived from these forum posts: https://forum.arduino.cc/index.php?topic=179541.0 // NOTE: Forum posters did not account for device sensitivity /////////////////////////////////////////////////////////////////////////////////// const int currentPin = 0; // Sampling Parameters const unsigned long sampleTime = 100000UL; // sample over 100ms const unsigned long numSamples = 250UL; // the number of samples divides sampleTime exactly, // but low enough for the ADC to keep up const unsigned long sampleInterval = sampleTime/numSamples; // the sampling interval // must be longer than then ADC conversion time #define SENSITIVITY 185 // from ACS712 data sheet for 5A version, in mV/A int adc_zero; // variable to hold calibrated sensor quiescent voltage boolean occupied = false; float occupancy_threshold = .0259; float current = 0; float prev_current; void setup() { Serial.begin(9600); Serial.println("\nACS712 Current Sensing Basic Demonstration\nMultiple Readings converted to RMS at 1 second intervals\nValues for quiescent output are determined by Calibration.\n\nCalibrating the sensor:\n"); adc_zero = determineVQ(currentPin); //Quiescent output voltage - the average voltage ACS712 shows with no load (0 A) delay(1000); } void loop(){ float avg_current; prev_current = current; current = readCurrent(currentPin, adc_zero); avg_current = (current + prev_current)/2; occupied = avg_current > occupancy_threshold; Serial.print("Current Sensed:"); Serial.print(current * 1000 ,1); Serial.print(" mA\t\t"); Serial.print("The block is "); if(occupied){ Serial.println("occupied"); } else { Serial.println("not occupied"); } delay(1000); } int determineVQ(int PIN) { Serial.print("estimating avg. quiscent voltage:"); long VQ = 0; //read 5000 samples to stabilize value for (int i=0; i<5000; i++) { VQ += analogRead(PIN); delay(1);//depends on sampling (on filter capacitor), can be 1/80000 (80kHz) max. } VQ /= 5000; Serial.print(map(VQ, 0, 1023, 0, 5000)); Serial.println(" mV"); return int(VQ); } float readCurrent(int PIN, float adc_zero) { float currentAcc = 0; unsigned int count = 0; unsigned long prevMicros = micros() - sampleInterval ; while (count < numSamples) { if (micros() - prevMicros >= sampleInterval) { float adc_raw = analogRead(PIN) - adc_zero; // Electical offset voltage adc_raw /= SENSITIVITY; // convert to amperes currentAcc += (adc_raw * adc_raw); ++count; prevMicros += sampleInterval; } } //https://en.wikipedia.org/wiki/Root_mean_square float rms = sqrt((float)currentAcc / (float)numSamples); return rms; }