From 31fbeec32a36a86ba434754081c8c963c30a6806 Mon Sep 17 00:00:00 2001
From: Arnaud Watlet <arnaud.watlet@umons.ac.be>
Date: Wed, 22 Feb 2023 15:36:46 +0100
Subject: [PATCH] fixes strategy condition

---
 ohmpi.py | 35 ++++++++++++++++++++++++++++-------
 1 file changed, 28 insertions(+), 7 deletions(-)

diff --git a/ohmpi.py b/ohmpi.py
index 585bdc35..12afc362 100644
--- a/ohmpi.py
+++ b/ohmpi.py
@@ -315,12 +315,12 @@ class OhmPi(object):
         # select a polarity to start with
         self.pin0.value = True
         self.pin1.value = False
-        I=0 
-        vmn=0
-        count=0
 
         # implement different strategy
         if strategy == 'vmax':
+            I=0
+            vmn=0
+            count=0
             while I < 3 or abs(vmn) < 20 :  # I supérieur à 1 mA et Vmn surpérieur
                 if count >0 :
                     volt = volt + 2
@@ -377,11 +377,32 @@ class OhmPi(object):
             vab = factor * volt * 0.8
             if vab > tx_max:
                 vab = tx_max
-
-        elif strategy == 'constant':
-            vab = volt
         else:
-            vab = 5
+            if strategy == 'constant':
+                vab = volt
+            else:
+                vab = 5
+
+            # autogain
+            self.ads_current = ads.ADS1115(self.i2c, gain=2 / 3, data_rate=860, address=self.ads_current_address)
+            self.ads_voltage = ads.ADS1115(self.i2c, gain=2 / 3, data_rate=860, address=self.ads_voltage_address)
+            gain_current = self._gain_auto(AnalogIn(self.ads_current, ads.P0))
+            gain_voltage0 = self._gain_auto(AnalogIn(self.ads_voltage, ads.P0))
+            gain_voltage2 = self._gain_auto(AnalogIn(self.ads_voltage, ads.P2))
+            gain_voltage = np.min([gain_voltage0, gain_voltage2])
+            self.ads_current = ads.ADS1115(self.i2c, gain=gain_current, data_rate=860, address=self.ads_current_address)
+            self.ads_voltage = ads.ADS1115(self.i2c, gain=gain_voltage, data_rate=860, address=self.ads_voltage_address)
+            # we measure the voltage on both A0 and A2 to guess the polarity
+            I = AnalogIn(self.ads_current, ads.P0).voltage * 1000. / 50 / self.r_shunt  # noqa measure current
+            U0 = AnalogIn(self.ads_voltage, ads.P0).voltage * 1000.  # noqa measure voltage
+            U2 = AnalogIn(self.ads_voltage, ads.P2).voltage * 1000.  # noqa
+
+            # check polarity
+            polarity = 1  # by default, we guessed it right
+            vmn = U0
+            if U0 < 0:  # we guessed it wrong, let's use a correction factor
+                polarity = -1
+                vmn = U2
 
         self.DPS.write_register(0x09, 0) # DPS5005 off
         # print('polarity', polarity)
-- 
GitLab