evenjc

myLDR-objekt

Feb 26th, 2020
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //myLDR Object - Step 1
  2. class myLDR {
  3.   public:
  4.     int pin;
  5.     int min_value = 1023;
  6.     int max_value = 0;
  7.  
  8.     int read_sensor() {
  9.       return analogRead(pin);
  10.     }
  11. };
  12.  
  13. myLDR sensor;
  14.  
  15. void setup() {
  16.   sensor.pin = A5;
  17.   Serial.begin(9600);
  18.  
  19. }
  20.  
  21. void loop() {
  22.   Serial.println(sensor.read_sensor());
  23. }
  24.  
  25. //myLDR Object - Step 2
  26. class myLDR {
  27.   public:
  28.     int pin;
  29.     int min_value = 1023;
  30.     int max_value = 0;
  31.  
  32.     int read_sensor() {
  33.       return analogRead(pin);
  34.     }
  35.  
  36.     void calibrate_sensor() {
  37.       int read_val = read_sensor();
  38.       if (read_val > max_value) max_value = read_val;
  39.       if (read_val < min_value) min_value = read_val;
  40.     }
  41.  
  42.     int read_calibrated() {
  43.       int readval = read_sensor();
  44.       return map(readval, min_value, max_value, 0, 1023);
  45.     }
  46. };
  47.  
  48. myLDR sensor;
  49.  
  50. void setup() {
  51.   sensor.pin = A5;
  52.   Serial.begin(9600);
  53.   int n = 0;
  54.   while (n < 1000) {
  55.     sensor.calibrate_sensor();
  56.     delay(10);
  57.     n++;
  58.   }
  59.   Serial.print("The lowest i found was: ");
  60.   Serial.println(sensor.min_value);
  61.   Serial.print("The highest i found was: ");
  62.   Serial.println(sensor.max_value);
  63. }
  64.  
  65. void loop() {
  66.   Serial.print(sensor.read_sensor());
  67.   Serial.print("\t");
  68.   Serial.println(sensor.read_calibrated());
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment