To configure and work with the OpenAI API key on macOS, follow these step-by-step instructions: Step 1: Sign Up for OpenAI API Access 1. Create an Account: Go to the [OpenAI website](https://www.openai.com/) and sign up for an account if you don’t have one. 2. API Key: Once logged in, navigate to the API section of your account dashboard to generate your API key. Make sure to copy this key, as you will need it later.
Step 2: Install Required Software 1. Install Homebrew (if you don’t have it): - Open Terminal and run: bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
2. Install Python (if you don’t have it): - You can install Python using Homebrew: bash brew install python
3. Install pip (Python package manager): - Pip usually comes with Python, but you can ensure it’s installed by running: bash python3 -m ensurepip --upgrade
Step 3: Set Up a Virtual Environment (Optional) 1. Create a Virtual Environment: - Navigate to your project directory in Terminal and run: bash python3 -m venv myenv
- Replace `myenv` with your desired environment name.
2. Activate the Virtual Environment: - Run: bash source myenv/bin/activate
Step 4: Install OpenAI Python Client 1. Install the OpenAI package**: - With your virtual environment activated, run: bash pip install openai
Step 5: Configure Your API Key 1. Set the API Key in Your Environment**: - You can set your API key as an environment variable. In Terminal, run: bash export OPENAI_API_KEY='your_api_key_here'
- Replace `'your_api_key_here'` with the actual API key you copied earlier.
2. Make it Permanent (Optional): - To make this change permanent, you can add the export command to your shell configuration file (e.g., `.bash_profile`, `.zshrc`, or `.bashrc` depending on your shell). Open the file in a text editor: bash nano ~/.zshrc
- Add the line: bash export OPENAI_API_KEY='your_api_key_here'
- Save and exit (in nano, press `CTRL + X`, then `Y`, and `Enter`). - Run `source ~/.zshrc` to apply the changes.
Step 6: Test the OpenAI API 1. Create a Python Script: - Create a new Python file, e.g., `test_openai.py`: bash touch test_openai.py
2. Write a Simple Script: - Open the file in a text editor and add the following code: python import openai import os
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": "Hello, how are you?"} ] )
print(response.choices[0].message['content'])
3. Run the Script: - In Terminal, run: bash python3 test_openai.py
Step 7: Review the Output - You should see a response from the OpenAI API printed in your Terminal.
Additional Notes - Make sure to keep your API key secure and do not share it publicly. - Refer to the [OpenAI API documentation](https://platform.openai.com/docs/api-reference) for more details on how to use the API effectively.
By following these steps, you should be able to configure and work with the OpenAI API on macOS successfully.
Les conducteurs électriques permettent de transporter l’électricité d’un émetteur vers un récepteur. Ceux-ci doivent être les moins résistant possible au passage du courant afin d’éviter une perte de tension préjudiciable au bon fonctionnement des récepteurs surtout si ce sont des moteurs et aussi afin de limiter l’échauffement des câbles par effet Joule.
Pour éviter ce genre de problème les câbles d’une installation doivent être correctement dimensionnés.
Les trois paramètres qui influencent le dimensionnement des câbles
La nature du conducteur, meilleure est sa conductivité moins sa résistance est importante
La longueur, plus un conducteur est long plus sa résistance est grande ;
Le diamètre, la résistance d’un conducteur est inversement proportionnel au carré de son diamètre.
Les meilleurs conducteurs électriques sont l’argent, le cuivre, l’or et l’aluminium.
Estimation par le calcul
S= r * L * I / V
r : Résistivité du cuivre soit 0,021 ohms L : Longueur totale en mètre I : Courant en A (Ampère) V :Chute de tension
Abaques de section de câble (240/400 Volts)
Une abaque est un tableau sous forme graphique permettant de synthétiser différents calculs numériques avec plus ou moins de précision.
"Un abaque permet une estimation rapide, ne prend pas en compte les cas particuliers, le mode de pose, l’environnement..etc."
Les tableaux suivants sont valables pour un courant monophasé 240 V et triphasé 400 V, 240 V, le cos phi(φ) est de 0,8 (moteur électrique).
Conducteur cuivre avec une chute de tension de 3 % environ (à partir d’un réseau de distribution public à basse tension).
P : signifie puissance consommée en kilowatt (kW) I : intensité du courant en ampères (A).
Chiffres donnés à titre indicatif, doit être vérifié par le calcul.
class INA3221: def __init__(self, scl=22, sda=21, CHen="111"): # Définir les broches SCL et SDA pour le bus I2C pscl = Pin(scl) psda = Pin(sda) self.i2c = SoftI2C(scl=pscl, sda=psda, freq=400000) self.config(CHen[0],CHen[1],CHen[2])
def scan(self): # Scanner le bus I2C et afficher les adresses trouvées adresses_trouvees = self.i2c.scan() print("Adresses I2C trouvées :") for adresse in adresses_trouvees: print(f" - Adresse décimale : {adresse}") print(f" - Adresse hexadécimale : {hex(adresse)}")
def bin_to_int(self,strbin): sum = 0 puis = len(strbin)-1 for i,c in enumerate(strbin): #print(i,c) sum+= 2**(puis-i)*int(c) #a=hex(sum) #print(a) return sum
def voltmeter(self, channel=1): """Returns the channel's bus voltage in Volts""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" value_reg = self.i2c.readfrom_mem(INA3221_ADDR, BUS_VOLTAGE_CH[channel] , 2) bus_voltage = int.from_bytes(value_reg, 'big') >> 3 # Conversion en 13 bits #print(bus_voltage) # convert to volts - LSB = 8mV return bus_voltage * BUS_ADC_LSB
ina = INA3221(CHen="101") #ina.scan() #ina.read_config() while True: v1 = ina.voltmeter(3) print(v1) sleep(1) break
# Constants for manufacturer and device ID C_MANUFACTURER_ID = const(0x5449) # "TI" C_DIE_ID = const(0x3220)
# General constants C_BUS_ADC_LSB = 0.008 # VBus ADC LSB is 8mV C_SHUNT_ADC_LSB = 0.00004 # VShunt ADC LSB is 40µV
class INA3221: """Driver class for Texas Instruments INA3221 3 channel current sensor device"""
IS_FULL_API = True
@staticmethod def _to_signed(val): if val > 32767: return val - 65536 return val
@staticmethod def _to_unsigned(val): if val < 0: return val + 65536 return val
def write(self, reg, value): """Write value in device register""" seq = bytearray([reg, (value >> 8) & 0xFF, value & 0xFF]) print(reg,value,seq) self.i2c_device.write(seq)
def read(self, reg): """Return value from device register""" buf = bytearray(3) buf[0] = reg self.write_then_readinto(buf, buf, out_end=1, in_start=1) value = (buf[1] << 8) | (buf[2]) return value
def update(self, reg, mask, value): """Read-modify-write value in register""" regvalue = self.read(reg) regvalue &= ~mask value &= mask self.write(reg, regvalue | value)
def writeto_then_readfrom( self, address, buffer_out, buffer_in, *, out_start=0, out_end=None, in_start=0, in_end=None, stop=False ): """Write data from buffer_out to an address and then read data from an address and into buffer_in """ if out_end: self.i2c_device.writeto(address, buffer_out[out_start:out_end], stop) else: self.i2c_device.writeto(address, buffer_out[out_start:], stop)
if not in_end: in_end = len(buffer_in) read_buffer = memoryview(buffer_in)[in_start:in_end] self.i2c_device.readfrom_into(address, read_buffer, stop)
def write_then_readinto( self, out_buffer, in_buffer, *, out_start=0, out_end=None, in_start=0, in_end=None ): """ Write the bytes from ``out_buffer`` to the device, then immediately reads into ``in_buffer`` from the device. The number of bytes read will be the length of ``in_buffer``.
If ``out_start`` or ``out_end`` is provided, then the output buffer will be sliced as if ``out_buffer[out_start:out_end]``. This will not cause an allocation like ``buffer[out_start:out_end]`` will so it saves memory.
If ``in_start`` or ``in_end`` is provided, then the input buffer will be sliced as if ``in_buffer[in_start:in_end]``. This will not cause an allocation like ``in_buffer[in_start:in_end]`` will so it saves memory.
:param bytearray out_buffer: buffer containing the bytes to write :param bytearray in_buffer: buffer containing the bytes to read into :param int out_start: Index to start writing from :param int out_end: Index to read up to but not include; if None, use ``len(out_buffer)`` :param int in_start: Index to start writing at :param int in_end: Index to write up to but not include; if None, use ``len(in_buffer)`` """ if out_end is None: out_end = len(out_buffer) if in_end is None: in_end = len(in_buffer)
def is_channel_enabled(self, channel=1): """Returns if a given channel is enabled or not""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" bit = C_ENABLE_CH[channel] return self.read(C_REG_CONFIG) & bit != 0
def enable_channel(self, channel=1, enable=True): """Enables or disable a given channel""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" bit = C_ENABLE_CH[channel] value = 0 if enable: value = bit self.update(C_REG_CONFIG, bit, value)
def shunt_voltage(self, channel=1): """Returns the channel's shunt voltage in Volts""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" value = self._to_signed(self.read(C_REG_SHUNT_VOLTAGE_CH[channel])) / 8.0 # convert to volts - LSB = 40uV return value * C_SHUNT_ADC_LSB
def current(self, channel=1): """Return's the channel current in Amps""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" return self.shunt_voltage(channel) / self.shunt_resistor[channel-1]
def bus_voltage(self, channel=1): """Returns the channel's bus voltage in Volts""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" value = self._to_signed(self.read(C_REG_BUS_VOLTAGE_CH[channel])) / 8 # convert to volts - LSB = 8mV return value * C_BUS_ADC_LSB
def shunt_critical_alert_limit(self, channel=1): """Returns the channel's shunt voltage critical alert limit in Volts""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" value = self._to_signed(self.read(C_REG_CRITICAL_ALERT_LIMIT_CH[channel])) / 8 # convert to volts - LSB = 40uV return value * C_SHUNT_ADC_LSB
def set_shunt_critical_alert_limit(self, channel, voltage): """Sets the channel's shunt voltage critical alert limit in Volts""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" value = self._to_unsigned(round(voltage * C_SHUNT_ADC_LSB) * 8) self.write(C_REG_CRITICAL_ALERT_LIMIT_CH[channel], value)
def shunt_warning_alert_limit(self, channel=1): """Returns the channel's shunt voltage warning alert limit in Volts""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" value = self._to_signed(self.read(C_REG_WARNING_ALERT_LIMIT_CH[channel])) / 8 # convert to volts - LSB = 40uV return value * C_SHUNT_ADC_LSB
def set_shunt_warning_alert_limit(self, channel, voltage): """Sets the channel's shunt voltage warning alert limit in Volts""" assert 1 <= channel <= 3, "channel argument must be 1, 2, or 3" value = self._to_unsigned(round(voltage * C_SHUNT_ADC_LSB) * 8) self.write(C_REG_WARNING_ALERT_LIMIT_CH[channel], value)
@property def is_ready(self): """Returns the CVRF (ConVersion Ready Flag) from the mask/enable register """ regvalue = self.read(C_REG_MASK_ENABLE) print(regvalue) test = (regvalue & C_CONV_READY_FLAG) != 0x0 print(test) return test
while True: # Lecture de la tension de bus du canal 1 bus_voltage_raw = i2c.readfrom_mem(INA3221_ADDR, BUS_VOLTAGE_REG_CH1, 2) reg = int.from_bytes(bus_voltage_raw, 'big') print(reg) binary = int_to_binary(reg) print(binary) binary = binary[:-3] print(binary) volt = bin_to_int(binary) print(volt) print(volt*0.008)
## Module INA3221 (WCMCU 3221) : Moniteur de tension et de courant 3 canaux avec interface I2C
Le module INA3221 (WCMCU 3221) est un moniteur de tension et de courant polyvalent qui offre une interface I2C compatible SMBUS pour une communication facile avec les microcontrôleurs et autres systèmes embarqués. Il dispose de trois canaux indépendants pour mesurer simultanément la tension et le courant sur plusieurs charges ou alimentations.
**Fonctionnalités principales:**
* **Mesure précise de la tension et du courant :** Le INA3221 peut mesurer la tension sur les shunts de courant (In+ et In-) et la tension de bus (Vin-) pour chaque canal, permettant des calculs précis du courant et de la puissance consommés. * **Large plage de mesure :** Le module peut mesurer des tensions de bus allant de 0 V à 26 V et des courants jusqu'à 3 A (limités par la résistance de shunt). * **Interface I2C flexible :** L'interface I2C permet une communication simple et efficace avec les microcontrôleurs, offrant quatre adresses programmables (0x40, 0x41, 0x44 et 0x45) pour une configuration aisée. * **Alertes programmables :** Le INA3221 dispose de sorties d'alertes configurables (PV, CRI, WAR et TC) pour signaler les conditions hors plage et protéger vos systèmes contre les dommages. * **Consommation d'énergie optimisée :** Le module consomme un faible courant de 350 µA typiques, le rendant idéal pour les applications alimentées par batterie.
**Applications:**
* Surveillance de la consommation d'énergie dans les ordinateurs, les équipements de télécommunication, les chargeurs de batterie et les alimentations * Gestion de l'alimentation des systèmes embarqués et des circuits électroniques * Détection de pannes et protection des circuits * Test et mesure d'équipements électroniques
**Spécifications techniques:**
* Alimentation du circuit de contrôle : 2,7 V à 5,5 V * Alimentation de la charge : 0 V à 26 V * Type de sortie : Numérique * Interface de communication : I2C, compatible SMBUS * Adresses programmables : 4 (via des cavaliers) * Résistance de shunt : 0,1 Ω 1% 1 W (limite le courant maximum à moins de 3 A)
**Connexions:**
* CH1 : Sortie pour charge 1 * CH2 : Sortie pour charge 2 * CH3 : Sortie pour charge 3 * GND : Masse commune des alimentations * POW : Entrée d'alimentation pour la charge * VPU : Tension d'alimentation pull-up pour polariser les sorties * VS : Alimentation du circuit de contrôle (2,7 V à 5,5 V) * SCL : Horloge I2C * SDA : Données I2C * PV : Sortie d'alerte de tension valide (drain ouvert) * CRI : Sortie d'alerte critique (drain ouvert) * WAR : Sortie d'alerte d'avertissement (drain ouvert) * TC : Sortie d'alerte de séquence de conversion (drain ouvert)
Le module INA3221 (WCMCU 3221) offre une solution complète et économique pour la mesure précise de la tension et du courant dans une large gamme d'applications. Sa simplicité d'utilisation, sa flexibilité et sa fiabilité en font un choix idéal pour les concepteurs de systèmes embarqués et les amateurs.
En poursuivant votre navigation sur mon site,
vous acceptez l’utilisation des Cookies et autres traceurs
pour réaliser des statistiques de visites et enregistrer
sur votre machine vos activités pédagogiques.En savoir plus.