I have connected 4 DC motors (each two with L298 H-Bridge IC), now it's time to get them worked using a Python script running on Raspberry Pi B+. I'll include my code, and I'm totally new that means it's perfect-structured.
My aim is: How can we use Python Dictionaries to illuminate the bunch of code which has a lot of redundancy.
I mean, if anyone can tell how to start, and how to use packing/unpacking arguments to deal with each GPIO indecently.
NOTE: I have a seperate file that stores GPIO numbers in a dictionary to provide accessing its contents from any class.
import RPi.GPIO as G from time import sleep import config
class moving(object): """docstring for moving""" def __init__(self, duty): super(moving, self).__init__() self.duty = duty G.setmode(G.BOARD) G.setwarnings(False) M1F = config.BOARD['DC1_F'] M1B = config.BOARD['DC1_B'] M2F = config.BOARD['DC2_F'] M2B = config.BOARD['DC2_B'] M3F = config.BOARD['DC3_F'] M3B = config.BOARD['DC3_B'] M4F = config.BOARD['DC4_F'] M4B = config.BOARD['DC4_B'] # M1F: Enable pin of Motor one Forward G.setup(M1F,G.OUT) G.setup(M1B,G.OUT) G.setup(M2F,G.OUT) G.setup(M2B,G.OUT) G.setup(M3F,G.OUT) G.setup(M3B,G.OUT) G.setup(M4F,G.OUT) G.setup(M4B,G.OUT) frequency = config.DC_FREQ # Frequency is a constant value P1F = G.PWM(M1F,frequency) P1B = G.PWM(M1B,frequency) P2F = G.PWM(M2F,frequency) P2B = G.PWM(M2B,frequency) P3F = G.PWM(M3F,frequency) P3B = G.PWM(M3B,frequency) P4F = G.PWM(M4F,frequency) P4B = G.PWM(M4B,frequency) P1F.start(duty) P1B.start(duty) P2F.start(duty) P2B.start(duty) P3F.start(duty) P3B.start(duty) P4F.start(duty) P4B.start(duty) # when an object is created, # duty cylce will be inititlised G.cleanup() def change_speed(self,new_duty): self.duty = new_duty pass def move(self,direction): if directoin == 'F': G.output(M1F,1) G.output(M2F,1) G.output(M3F,1) G.output(M4F,1) pass # and So on for other directions pass
Although it may be acceptable that way, I don't feel comfort with that bad way of coding, especially when I decide to expand it with other developments.
Thanks a lot for every help