Python Forum
Transistor C.E. amp Basic design concepts calculator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Transistor C.E. amp Basic design concepts calculator
#1
This is an earlier program I wrote when I first began learning python,
since then I have upgraded the coding style and features about 8 times,
this is probably upgrade #8, however it works good enough to be called
a finished program, any new features will be enhancement upgrades to it now.

Some features I'm currently thinking of,is writing some code to have the computer
choose standard resistor values, allow the user to choose there own design
parameters and have the computer calculate values within those parameters. etc...

So this program is just the foundation for added features, enjoy...


import os
class klass:
     '"docstring'"
    def_init_(self):
        self.attribute="var"
        if len(self.attribute) <2:
            pass




print('---------------------------')
print("")
print("")
about = """This is a program to calculate the transistor bias resistors
for a basic Common Emitter amp stage, with series feedback, using Bipolar transistors.
It is up to you to assume the ground reference as positive or negative,
depending on the makeup of the transistor, (NPN or PNP). These are just
ballpark values, using first order calculations using rule of thumb
methods to get the values. The resistor values are approximations, it is
up to you to decide what values to use in the final design."""
print (about)
doover=0
while doover==0:
    print("")
    print("");print("")
    values=[]
    amp_param=["VCC","RC","Av","Beta"]
    for ndx in range (4):
        print ("                Entering  ( e ) exits out anytime") 
        if exit==(1):
            break
        else:
            user=amp_param[ndx]
            error=0
        while error==0:
            try:
                user=input("Enter a value for "+(user)+" >>  ")
                if (user)=="e":
                    exit=1
                    break
                user=float(user)
                error=1
                values.append(user)
            except:
                print("")
                print("Enter a numeric value only")
                user=amp_param[ndx]
    
    if exit==(1):
        break
    VCC=(values[0])
    RC=(values[1])
    Av=(values[2])
    Beta=(values[3])
    print("")
    VC=(VCC/2)
    RE=(RC / Av)
    IC=(VCC / (2*RC))
    IB=(IC / Beta)
    IE=(IC+IB)
    VRE=(IE*RE)
    Vbe=0.7
    VB=(VRE+Vbe)
    Idv=(11*IB)
    RBS=((VCC-VB) / (Idv))
    RBG=(VB / (Idv - IB))
    RC=int(RC)
    RE=int(RE)  #convert the float value to a decimal value, with no decimal places.
    re=(.026/IC)
    RBG=int(RBG)
    RBS=int(RBS)
    IC=format(IC,'.6f')
    VRE=format(VRE,'.2f')#converts a decimal value to a float value with 2 decimal places after the whole number.
    VB=format(VB,'.2f') 
    print("")
    print("")
    if float (IC) < 0.001:
        micro=float(IC) * 1000000
        print ("The quiescent collector current is ~=, " + str(micro) + " microamps")
    elif float (IC) >.001 < 1:
        mill=float(IC) * 1000
        print ("The quiescent collector current is ~=, " + str(mill) + " milliamps")
    else:
        print("The quiescent collector current is ~=, " + str(IC) + "amps")    
    print("")
    print ('The collector resistor is, ' + str(RC) + ' ohms')
    print("")
    print ('The emitter resistor is, ' + str(RE) + ' ohms')
    print("")
    print ('The base to ground resistor is, ' + str(RBG) + ' ohms')
    print("")
    print ('The base to supply resistor is, ' + str(RBS) + ' ohms')
    print ("")
    print ('The quiescent collector voltage is ~=, ' + str(VC) + ' volts')
    print("")
    print ('The emitter voltage is ~=, ' + str(VRE) + ' volts')
    print("")
    print ('The base voltage is ~=, ' + str(VB) + ' volts')
    print("")
    print("------------------------------------------------")
    error=0
    while error==0:
        try:
            print("");print ("                Entering  ( m ) goes back to main menu")
            print("");print("") 
            VIN=input("enter a value of voltage input peak to peak  ")
            print("")
            if VIN=="m":
                #exit=1
                break  
            VIN=float(VIN)
            error=1
            VPK= float(VIN / 2)
            VB=float(VB)
            Eth=((VCC*RBG) / (RBG+RBS))
            Rth=((RBG*RBS) / (RBG+RBS))
            Zin=(Beta*(RE+re))
            delta_IB=(VPK/(Rth+Zin))
            delta_IBF=format(delta_IB,".6f")
            if float(delta_IBF)< 0.001:
                microh=float(delta_IBF) * 1000000
                print ("The Base current increase is ~=, " + str(microh) + " microamps")
                microplus=1
                millplus=0
            elif float (delta_IBF)>.001 < 1:
                millh=float(delta_IBF) * 1000
                print ("The Base current increase is ~=, " + str(millh) + " milliamps")
                millplus=1
                microplus=0
            else:
                print("The Base current increase is ~=, " + str(delta_IBF) + "amps")
                print("")

            #print ("Delta base current high value= ",(delta_IBF))
            delta_base=((Beta*delta_IB))
            pxICPKswing=((VCC/(2*RC))+(delta_base))
            pxICPKswing=format(pxICPKswing,".3f")
            if float(pxICPKswing)< 0.001:
                microh=float(pxICPKswing) * 1000000
                print ("The collector current increases to ~=, " + str(microh) + " microamps")
                microplus=1
                millplus=0
            elif float (pxICPKswing)>.001 < 1:
                millh=float(pxICPKswing) * 1000
                print ("The collector current increases to ~=, " + str(millh) + " milliamps")
                millplus=1
                microplus=0
            else:
                print("The collector current increases to ~=, " + str(pxICPKswing) + "amps")
                print("")
            delta_IB=(-VPK/(Rth+Zin))
            delta_IBF=format(delta_IB,".6f")
            if float(delta_IBF)< 0.001:
                microh=float(delta_IBF) * 1000000
                print ("The Base current decrease is ~=, " + str(microh) + " microamps")
                microplus=1
                millplus=0
            elif float (delta_IBF)>.001 < 1:
                millh=float(delta_IBF) * 1000
                print ("The Base current decrease is ~=, " + str(millh) + " milliamps")
                millplus=1
                microplus=0
            else:
                print("The Base current decrease is ~=, " + str(pxICPKswing) + "amps")
                print("")
 
            #print ("Delta base current low = ",(delta_IBF))
            delta_base=((Beta*delta_IB))
            nxICPKswing =((VCC/(2*RC))+(delta_base))
            nxICPKswing=format(nxICPKswing,".3f")
            if float(nxICPKswing) < 0.001:
                microl=float(nxICPKswing) * 1000000
                print ("The collector current decreases to ~=, " + str(microl) + " microamps")
                microminus=1
                millminus=0
            elif float (nxICPKswing) >.001 < 1:
                milll=float(nxICPKswing) * 1000
                print ("The collector current decreases to ~=, " + str(milll) + " milliamps")
                millminus=1
                microminus=0
            else:
                print("The collector current decreases to ~=, " + str(nxICPKswing) + "amps")    
            if microminus==1 and microplus==1:
                print("")
                print("")
                print ("collector current swings from, " + str(microl)+" to " + str(microh)+ " microamps")
            elif millplus==1 and millminus==1:
                print("")
                print("")
                print ("collector current swings from, " + str(milll)+" to " + str(millh)+ " milliamps")
            else:
                print("")
                print("")
                #print("The collector current is ~=, " + str(nxICPKswing) + " amps")
            print("")
            pxICPKswing=float(pxICPKswing)
            nxICPKswing=float(nxICPKswing)
            VCswinglo=(VCC -(pxICPKswing * RC))
            VCswinglo=format(VCswinglo,".3f")
            VCswinghi=(VCC - (nxICPKswing * RC))
            VCswinghi=format(VCswinghi,".3f")
            print("")
            print ("collector voltage swing low is, " + str(VCswinglo) + " volts")
            print("")
            print ("collector voltage swing high is, " + str(VCswinghi) + " volts")
            print("")
            print("")
            print ("The collector voltage swings from, " + str(VCswinglo) + " to " + str(VCswinghi) + " volts")
        except:
            print("")
            print("enter a number only")
            print("")
    if exit==(1):
        break
    print("")
    print("")
    print("")
    again=input ("Enter (1) to do another calculation or enter (0) to quit  ") 
    if again =="1":
        doover=0
    else:
        break
    
print("Done")
print("")
userdone=input("Hit the enter key to end the program")
Reply
#2
The main problem: This program is hard to read and hard to change.
Try to use functions. Split your program into logical parts.

One part, to get the data input from user and converting it to the right type. One function which collects all parameters. Many functions, which do the math.

Example with your code:

'''
This is a program to calculate the transistor bias resistors
for a basic Common Emitter amp stage, with series feedback, using Bipolar transistors.
It is up to you to assume the ground reference as positive or negative,
depending on the makeup of the transistor, (NPN or PNP). These are just
ballpark values, using first order calculations using rule of thumb
methods to get the values. The resistor values are approximations, it is
up to you to decide what values to use in the final design.
'''

import sys
import textwrap


def print_help():
    wrapper = textwrap.TextWrapper(width=50, initial_indent=' | ', subsequent_indent=' | ')
    for line in wrapper.wrap(__doc__.strip()):
        print(line)


class ExitApp(Exception):
    pass


def print_newlines(n):
    print('\n' * n, end='')


def get_input_as(question, type=float, prompt=' >> ' ,exit_text='e'):
    while True:
        value = input(question + prompt)
        if value.lower().strip() == exit_text:
            raise ExitApp()
        try:
            value = float(value)
        except ValueError:
            print(f"{value} is not a float")
            continue
        else:
            return value


def get_parameters():
    print_newlines(3)
    amp = dict.fromkeys(["VCC","RC","Av","Beta"])
    print ("Entering ( e ) exits out anytime")
    for param in amp:
        try:
            value = get_input_as(f'Please enter the parameter for {param}', float)
        except ExitApp:
            sys.exit(0)
        amp[param] = value
    return amp


def do_math1(VCC, RC, **args):
    '''
    This function takes only VCC and RC.
    Other keywords are not used. **args allows this.
    '''
    # some calculations
    return 'your result'


if __name__ == '__main__':
    print_help()
    parameters = get_parameters()
    print(parameters)

    do_math1(**parameters) # Av and Beta is not used in this function
    # but you do also this
    do_math1(parameters['VCC'], parameters['RC'])
    # or
    vcc = parameters['VCC']
    rc = parameters['RC']
    do_math1(vcc, rc)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Hi,
Thank you for taking the time to write out the example code, I will consider learning how
to compartmentalizing by defining functions, that for me will be a study in itself,
my defining and building functions will most likely start out very primitive, and confusing,
but I will try to take this next step in learning python programming.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020