Advertisement
microrobotics

ZMPT101B AC Voltage Sensor

Apr 4th, 2023
3,505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Here's an example code for interfacing a ZMPT101B AC Voltage Sensor with an Arduino. This code will allow you to measure the AC voltage up to 250V.
  3.  
  4. This code initializes the ZMPT101B sensor on analog pin A0 and takes readings of the AC voltage every second. It also includes a calibration function that you can use to calibrate the sensor to get accurate voltage readings.
  5.  
  6. Please note that this code assumes that your Arduino board has a 5V reference voltage, and the ZMPT101B sensor has a sensitivity of 200 mV per V. Be sure to check your specific board and sensor specifications before using this code. Additionally, working with high voltage can be dangerous; take all necessary precautions and safety measures while working with AC voltage.
  7. */
  8.  
  9. #include <Arduino.h>
  10.  
  11. // Pin definitions
  12. const int sensorPin = A0; // Analog input pin connected to the ZMPT101B output
  13. const float VOLTAGE_REF = 5.0; // Reference voltage of the Arduino (5V for most boards, but check your specific board)
  14. const float SENSOR_SENSITIVITY = 200.0; // Sensitivity of the ZMPT101B module (200 mV per V)
  15.  
  16. // Calibration variables
  17. const int calibrationSamples = 1000; // Number of samples for calibration
  18. const float calibrationVoltage = 110.0; // Voltage of your AC source for calibration (e.g., 110V or 220V)
  19.  
  20. void setup() {
  21.   Serial.begin(9600);
  22.   pinMode(sensorPin, INPUT);
  23.  
  24.   // Calibrate the sensor
  25.   float calibration = calibrate();
  26.   Serial.print("Calibration value: ");
  27.   Serial.println(calibration);
  28. }
  29.  
  30. void loop() {
  31.   float voltage = readVoltage();
  32.   Serial.print("AC Voltage: ");
  33.   Serial.print(voltage);
  34.   Serial.println(" V");
  35.   delay(1000);
  36. }
  37.  
  38. float calibrate() {
  39.   float sum = 0;
  40.   for (int i = 0; i < calibrationSamples; i++) {
  41.     sum += analogRead(sensorPin);
  42.     delay(1);
  43.   }
  44.   float avg = sum / calibrationSamples;
  45.   return (avg * VOLTAGE_REF) / (1023 * SENSOR_SENSITIVITY);
  46. }
  47.  
  48. float readVoltage() {
  49.   const int numSamples = 100;
  50.   float maxVal = 0;
  51.   for (int i = 0; i < numSamples; i++) {
  52.     float sensorValue = (analogRead(sensorPin) * VOLTAGE_REF) / 1023;
  53.     if (sensorValue > maxVal) {
  54.       maxVal = sensorValue;
  55.     }
  56.     delay(1);
  57.   }
  58.   return maxVal / calibrate();
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement