Fino ad ora abbiamo utilizzato circuiti in condizioni
stazionarie, ovvero le cui grandezze fondamentali
(correnti, d.d.p., carica dei condensatori ) non
variano nel tempo. Un circuito RC è un esempio
di circuiti non stazionario.
Il circuito RC contiene, oltre a una batteria o
generatore di tensione, una o più resistenze e
uno o più condensatori.
Consideriamo il condensatore inizialmente scarico.
Attraverso l'interruttore S possiamo mettere in contatto
il condensatore con la batteria.
A carica completata, il bilancio energetico impone che
l'energia erogata dalla batteria durante la carica $\Delta U_B$
sia uguale all'energia immagazzinata dal condensatore $\Delta U_C$
più quella $\Delta U_R$ dissipata sul resistore $R$
Verifichiamo questo assunto:
Partiamo dal condensatore carico, con carica iniziale $ q_0 = Cfem $
Chiudiamo il circuito in modo che il condensatore scarichi la sua energia sul resistore $R$; ipotizziamo il verso della corrente in figura; la $2°$ legge di Kichoff dá:
int tau;
int R;
int experiment_counter;
void setup() {
// put your setup code here, to run once:
tau = 1; // tau = 1 second
R = 1e6; // R = 1e6 ohm
experiment_counter = 0;
int bps = 9600; // velocità, espressa in bps (boud rate per secondo).
Serial.begin(bps);
pinMode(2,OUTPUT); // set pin mode of second pin to OUTPUT
//make sure there is no tension in the capacitor at the beginning of experiment
digitalWrite(2, LOW); // turn OFF battery
delay(6*1000); // wait 6 seconds
}
void charge(){
digitalWrite(2, HIGH); //// turn ON battery
Serial.print("Experiment n. ");
Serial.print(experiment_counter);
Serial.print("\n");
unsigned long startChargingTime = millis();
unsigned long chargeTime = startChargingTime;
int seconds = 6;
while(chargeTime < startChargingTime+seconds*1000){
int sensorValue = analogRead(A0); //read tension
float voltage = sensorValue * (5.0 / 1023.0); // Convert the analog reading (which goes from 0 – 1023) to a voltage (0 – 5V)
chargeTime = millis(); //get current time
Serial.print(chargeTime-startChargingTime); // print charging time
Serial.print(" ");
Serial.print(voltage); //print voltage
Serial.print("\n");
delay(100); //wait 100ms
}
}
void discharge(){
digitalWrite(2, LOW); // turn OFF battery
int seconds = 6;
Serial.println("Discharging...");
unsigned long startDischargingTime = millis();
unsigned long dischargeTime = startDischargingTime;
while(dischargeTime < startDischargingTime+seconds*1000){
int sensorValue = analogRead(A0); //read tension
float voltage = sensorValue * (5.0 / 1023.0); // Convert the analog reading (which goes from 0 – 1023) to a voltage (0 – 5V)
dischargeTime = millis();
Serial.print(dischargeTime-startDischargingTime); // print charging time
Serial.print(" ");
Serial.print(voltage); //print voltage
Serial.print("\n");
delay(100); //wait 100ms
}
}
void stop(){
Serial.println("Stopping sketch");
while(1);
}
void loop() {
// put your main code here, to run repeatedly:
charge();
discharge();
experiment_counter++;
if(experiment_counter==50){
stop();
}
}
#include < iostream >
#include < fstream >
#include < string >
#define N_DATA 61 // data gathered during charging/discharging
#define N_EXPERIMENTS 50 // numbers of time the experiment wasrepeted
struct CapacitorData // structure containing data to be plotted
{
Double_t avg_voltages[N_DATA]; // Y axis
Double_t avg_times[N_DATA]; // X axis
int experiment_counter = 0;
};
void readData(std::ifstream &f,CapacitorData &c){
Double_t time, voltage;
std::string line;
for(int i=0;i< N_DATA; i++){
std::getline(f, line);
std::istringstream iss(line);
iss >> time >> voltage;
c.avg_times[i] = ((c.avg_times[i]*c.experiment_counter) + time/1000)/(c.experiment_counter+1);
c.avg_voltages[i] = ((c.avg_voltages[i]*c.experiment_counter)+ voltage)/(c.experiment_counter+1);
}
c.experiment_counter++;
}
void readFile(string fileName, CapacitorData &c, CapacitorData &d){
std::ifstream dataFile;
string line;
dataFile.open(fileName);
if(!dataFile){
std::cerr<< "Unable to open file: "<< fileName << std::endl;
exit(1);
}
for(int i=0;i < 2; i++){
std::getline(dataFile, line); // read "Experiment n. #"
readData(dataFile, c);
std::getline(dataFile, line); // read "Discharging..."
readData(dataFile, d);
}
}
void analysis() {
CapacitorData charging;
CapacitorData discharging;
readFile("capacitor_data.txt", charging, discharging); // read data and fill charging/discharging structures
TCanvas *c = new TCanvas("c", "Capacitor D.D.P. over time", 200, 200, 950,700); // create canvas
TGraph *graphFromData = new TGraph(N_DATA,charging.avg_times,charging.avg_voltages);
graphFromData->Draw(); // draw graph of charging
TF1 *expectedGraph = new TF1("expectedGraph","5*(1-e^(-x/1))",0,6);
expectedGraph->Draw("same"); //draw expected graph
TLegend *legend = new TLegend(.1,.7,.3,.9); //adding legend
legend->AddEntry(graphFromData,"d.d.p over time","l");
legend->AddEntry(expectedGraph,"Expected result","l");
legend->Draw();
graphFromData->GetYaxis()->SetTitle("D.D.P. [V]"); // set axis name
graphFromData->GetXaxis()->SetTitle("Time [s]"); // set axis name}
}
Possiamo scrivere lo stesso codice utilizzando un altro linguaggio di programmazione: Python. Ci serviremo di uno dei moduli più famosi di python per disegnare grafici, matplotlib. Vediamo il codice:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
import math
#usefull data
N_DATA = 61
N_EXPERIMENTS = 50
def readData(f,d):
# function that read data and calculate the mean value at same time
for data in range(N_DATA):
lineData = [ float(_) for _ in f.readline().split() ]
d['avg_time'][data] = ((d['avg_time'][data]*d['counter'])+lineData[0]/1000) / (d['counter']+1)
d['avg_voltages'][data] = ((d['avg_voltages'][data]*d['counter'])+lineData[1]) / (d['counter']+1)
d['counter']+=1
def readFile(filename,cd,dd):
with open(filename,'r') as file:
for experiment in range(N_EXPERIMENTS):
file.readline() # read "Experiment n.#"
readData(file, cd) # read charging data
file.readline() # read "discharging..."
readData(file, dd) # read discharging data
def ddp(t):
#mathematical function
fem = 5
C = 1e-6
R = 1e6
return fem*(1-pow(math.e,-t/(C*R)))
def plot(data):
fig = plt.figure()
t = np.linspace(0.,6.,61)
plt.plot(t,ddp(t), label="Expected result", color="orange")
plt.ylabel('D.D.P [V]')
plt.xlabel('Time [s]')
fig.suptitle('D.D.P. condensatore su tempo')
plt.scatter(data['avg_time'], data['avg_voltages'], label='Dati raccolti', marker = '.')
plt.legend(loc = 'upper left')
plt.show()
def main():
#definition of data structure
chargingData = {'avg_voltages': [0]*N_DATA, 'avg_time': [0]*N_DATA, 'counter': 0 }
dischargingData = {'avg_voltages': [0]*N_DATA, 'avg_time': [0]*N_DATA, 'counter': 0 }
readFile("capacitor_data.txt",chargingData, dischargingData) #read data
plot(chargingData) #plot things
# main function implementation
if __name__ == '__main__':
main()
Consideriamo un circuito RC costituito da un condensatore $ C = 5 \mu F $, ed una resistenza di $ R = 10 \Omega $; Il circuito viene vonnesso ad una batteria di $ fem $ uguale a $ 12 V $. Calcolare: