Python Forum
Help with getting a led to flash.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with getting a led to flash.
#1
I’m looking for a bit of help trying to get a led to blink on and off. I have tried adding a bit of code to different locations in the script but just can’t get it to work. I need the led to flash once the program starts. And continue fo ever. The link below is not my working but hopefully some will know how to do this. My led is on GPIO 27.
main.py
#!/usr/bin/python

#Imports
import pygame, random, math, time, pygame.mixer, os
import time
import sys

time.sleep(5)

gpioAvailable = True
try:
    import RPi.GPIO as GPIO
except:
    gpioAvailable = False
from audio import TrackerAudio
from pygame.locals import *
from resources import resources
from graphics import TrackerGraphics
from pyscope import pyscope
from startup import StartupGraphics
from calibration import Calibration
from calibrationGraphics import CalibrationGraphics

os.environ["SDL_FBDEV"] = "/dev/fb1"
os.environ['SDL_VIDEO_CENTERED'] = '1'

if gpioAvailable:
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP)

buttonTimerStart = 0
buttonTimerCurrent = 0
buttonHoldTime = 0
stateString="TRACK"
changeState=True
numberOfButtonPresses=0
buttonHoldTime=0

def my_callback(channel):

    global numberOfButtonPresses
    global buttonHoldTime
    global buttonTimerStart

    if GPIO.input(20):
        buttonHoldTime = time.time() - buttonTimerStart
        buttonTimerStart=0
    else:
        numberOfButtonPresses=numberOfButtonPresses+1
        buttonTimerStart=time.time()
    
if gpioAvailable:
    GPIO.add_event_detect(20, GPIO.BOTH, callback=my_callback, bouncetime=300)

#initialise pygame
pygame.init()

#initialise required game classes
scope=pyscope()
resources=resources() #get a resources object instance
ca=Calibration(scope, resources)
cg=CalibrationGraphics(scope, resources, ca)
sg=StartupGraphics(scope, resources) #get the startup graphics instance
tg=TrackerGraphics(scope, resources, ca) #get the tracker graphics instance
ta=TrackerAudio(resources) #get the tracker audio instance
pygame.mouse.set_visible(False) # Hide the mouse pointer

#initialise a clock instance so we can control the game loop
my_clock=pygame.time.Clock()

#enter the game loop
wave_size = 0
args=[]
done=False
currentState=True
startupTimerStart=time.time()
startupTimerCurrent=time.time()
qPress = False

os.system("fbcp &")

#show the startup gracphics
sg.draw()

while done==False:

    if numberOfButtonPresses>1:
        addContact = True
        numberOfButtonPresses=0
    else:
        addContact = False

    #process pygame events
    keys=pygame.key.get_pressed()        
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
            pass
        if event.type == pygame.KEYDOWN:
            if event.key==K_q:
                qPress = True
                buttonTimerStart=time.time()
                buttonTimerCurrent=time.time()
                buttonHoldTime=0
            if event.key==K_x:
                done=True
            if event.key==K_UP:
                addContact = True
        if event.type == pygame.KEYUP:
            if event.key==K_q:
                qPress=False

    if qPress:
        buttonHoldTime = time.time() - buttonTimerStart

    if buttonHoldTime>4:
        buttonHoldTime=0
        stateString="CALIBRATE"
        ca.initCalibration()
        calibrationStep = 0

    if stateString=="CALIBRATE":
        xy = ca.calibrate(calibrationStep)

        if calibrationStep==0:
            cg.initBackground()
            cg.update(xy, ca)
        if calibrationStep==500:
            stateString="TRACK"
        else:
            cg.update(xy, ca)
            calibrationStep=calibrationStep+1
        
    else:

        #process tracker graphics
        args = tg.update(wave_size, addContact, ca)
        if args!=999:
            #process audio
            ta.update(wave_size, args)

            #check the wave size, if it's 16 then reset otherwise increment
            if wave_size==15:
                wave_size=0
            else:
                wave_size+=1

    my_clock.tick(21)

scope.pySurface.fill((0,0,0))
scope.screen.blit(scope.pySurface,(0,0))
os.system("killall fbcp")
pygame.quit()
contacts.py
import random, math, sys, pygame

class Contacts():
    # Contacts class acts as storage and processing for
    # individual contact class elements,
    
    def __init__(self):
        # each Contacts class stores an array contact classes
        self.ContactArray = ([])
        self.ClosestScreenDist = 999
        #Declare the tracker maximum scale in meters to scale all screen distance values to
        self.trackerScale = 30

    #define a method to add a contact
    def addContact(self, compassActive):
        if compassActive:
            seedAngle = random.randint(0, 359)
        else:
            seedAngle = 0
            
        #for i in range(0,50,1):
        self.ContactArray.append(Contact(seedAngle))

    #define a function to move all contacts towards the center
    def moveContacts(self):

        newContactArray = ([])

        #loop through the contact array and move each item closer to the center
        #if an item reaches the center do not add it back into the contacts array
        for i in range(0,len(self.ContactArray),1):
            self.ContactArray[i].moveCloser()
            if self.ContactArray[i].outOfScope!=True:
                if self.ContactArray[i].distanceFromCentre<self.ClosestScreenDist:
                    self.ClosestScreenDist = self.ContactArray[i].distanceFromCentre
                
                newContactArray.append(self.ContactArray[i])

        self.ContactArray = newContactArray
        if len(self.ContactArray)==0:
            self.ClosestScreenDist = 999

    #define a function to return the closest screen value converted into the tracker distance scale
    def getClosestContactDistance(self):

        if self.ClosestScreenDist==999:
            contactDist = 999
        else:
            scaleFactor = float(self.trackerScale) / float(182)
            contactDist = scaleFactor * self.ClosestScreenDist
            
        return int(contactDist)

    #define a function to rotate all contacts in relation to the current grid bearing
    def updateContactsInWorld(self, bearing):

        for i in range(0,len(self.ContactArray),1):
            self.ContactArray[i].updateContactInWorld(bearing)

class Contact():
    # Contact contains positional data for a contact blip

    def __init__(self, seedAngle):
       # contact stores x and y positional data
       startPos = self.generateRandomStartPosition(seedAngle)       
       self.x = startPos[0]
       self.y = startPos[1]
       self.centreX = 160
       self.centreY = 182
       self.worldX = startPos[0]
       self.worldY = startPos[1]
       self.distanceFromCentre = 999
       self.opacityIndex = 0
       self.outOfScope = False

    #Define a function that returns an x,y co ordinate for an image given a bearing and distance
    def generateRandomStartPosition(self, seedAngle):

        angle = seedAngle + random.randint(-45, 45)
       
        if angle < 0:
            angle = 360 + angle
        elif angle > 360:
            angle = angle - 360

        startDistance = 182 + random.randint(0, 10)
        xy = self.getNewXY(angle, startDistance)
        return xy

    #define a function to return x/y coordinates for a given distance and bearing from the hud center
    def getNewXY(self,angle,dist):

        #find the x coordinate which is 160 +or- dist * cos angle
        xmultiplier = math.sin(math.radians(angle))
        distSin = dist*xmultiplier
        x = 160+distSin

        #find the y coordinate which is 182 +or- dist * cos angle
        ymultiplier = math.cos(math.radians(angle))
        distCos = dist*ymultiplier
        y = 182-distCos
        
        return (x,y)

    #define function to move contact closer to the center hud position
    def moveCloser(self):

        #get the current x/y coords
        currentX = self.x
        currentY = self.y

        #find the angle that the contact is currently pointing towards
        currentAngle = self.getContactBearing(currentX, currentY)

        #get the current distance from the center to the contact
        currentDist = self.getContactDistanceFromHud(currentX, currentY)

        #reduce the distance by a random amount between 1 and 3
        newDist = currentDist - 6

        #set the distance member value
        self.distanceFromCentre = newDist

        #check that the contact is still in scope (i.e. gt 0)
        if newDist <= 0:
          self.outOfScope = True
          return

        #change the bearing randomly with a random increment between +- 3 degrees
        deltaAngle = random.randint(-5, 5)
        newAngle = currentAngle+deltaAngle
        
        if newAngle<0:
            newAngle = 360 + newAngle
        elif newAngle>360:
            newAngle = newAngle - 360

        #get a new set of x/y coords based upon the new bearing and distance
        newXYcoords = self.getNewXY(newAngle, newDist)

        #update the contact x/y position
        self.x = newXYcoords[0]
        self.y = newXYcoords[1]

    #define function to get bearing from the hud center to the contact x/y coordinates
    def getContactBearing(self, x, y):

        dx = x - 160
        dy = y - 182

        if dx==0:
            if dy>0:
                angleDeg = 180
            else:
                angleDeg = 0
            return angleDeg
        else:
            angleRad = math.atan(dy / dx)
            angleDeg = abs(math.degrees(angleRad))

        if dx >= 0:
          if dy <= 0:
             returnAngle = 90 - angleDeg
          else:
             returnAngle = 90 + angleDeg
        else:
          if dy < 0:
             returnAngle = 270 + angleDeg
          else:
             returnAngle = 270 - angleDeg

        return returnAngle

    #define function to get distance from the hud center to the contact x/y coordinates
    def getContactDistanceFromHud(self, x, y):

        dx = x - 160
        dy = y - 182
        
        dist = math.sqrt(math.pow(dx,2) + math.pow(dy,2))
        return dist

    #define a function to rotate each contact
    #about the centre point in relation to the world grid
    def updateContactInWorld(self, bearing):

        worldPoint = ([])
        worldPoint.append(self.x)
        worldPoint.append(self.y)

        centrePoint = ([])
        centrePoint.append(self.centreX)
        centrePoint.append(self.centreY)

        newPoint = self.rotatePoint(centrePoint, worldPoint, bearing)
        self.worldX = newPoint[0]
        self.worldY = newPoint[1]
        return newPoint

    def rotatePoint(self, centerPoint,point,angle): 
        """Rotates a point around another centerPoint. Angle is in degrees. Rotation is counter-clockwise""" 
        angle = math.radians(angle) 
        temp_point = point[0]-centerPoint[0] , point[1]-centerPoint[1] 
        temp_point = ( temp_point[0]*math.cos(angle)-temp_point[1]*math.sin(angle) , temp_point[0]*math.sin(angle)+temp_point[1]*math.cos(angle)) 
        temp_point = temp_point[0]+centerPoint[0] , temp_point[1]+centerPoint[1] 
        return temp_point

    def getOpacityIndex(self, wave_size, trackerScale):
        "set the opacity index of the current contact, this is used to render"
        "out each contact with respect to the tracker wave"
        multiplier = float(16) / float(trackerScale)
        waveIndex1 = (int(multiplier * self.getContactDistance(trackerScale))-1)

        diff = wave_size-waveIndex1

        #get the current Index based upon the distance of the wave in relation to the conact
        if diff<0:
            return 0
        elif diff<2:
            return 3
        elif diff<10:
            return 2
        elif diff<16:
            return 1
        else:
            return 1

    #define a function to return the closest screen value converted into the tracker distance scale
    def getContactDistance(self, trackerScale):

        scaleFactor = float(trackerScale) / float(182)
        contactDist = scaleFactor * self.distanceFromCentre
            
        return int(contactDist)
pyscope.py
import os, pygame

#Define display class
class pyscope :
    
    screen = None
    pySurface = None
    
    def __init__(self):
        
        "Initializes a new pygame screen using the framebuffer"
        # Based on "Python GUI in Linux frame buffer"
        # http://www.karoltomala.com/blog/?p=679
        disp_no = os.getenv("DISPLAY")
        
        # Check which frame buffer drivers are available
        # Start with fbcon since directfb hangs with composite output
        drivers = ['fbcon', 'directfb', 'svgalib']
        found = False
        for driver in drivers:
            # Make sure that SDL_VIDEODRIVER is set
            if not os.getenv('SDL_VIDEODRIVER'):
                os.putenv('SDL_VIDEODRIVER', driver)
            try:
                pygame.display.init()
            except pygame.error:
                print(('Driver: {0} failed.'.format(driver)))
                continue
            found = True
            break
    
        if not found:
            raise Exception('No suitable video driver found!')
        size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
        flags = pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.FULLSCREEN
        self.screen = pygame.display.set_mode(size, flags)
        surface = pygame.Surface((320,240))
        self.pySurface = surface.convert()
        
        # Initialise font support
        pygame.font.init()
 
    def __del__(self):
        "Destructor to make sure pygame shuts down, etc."
And this is the script to blink the led.
from gpiozero import LED
from time import sleep

led = LED(17)

while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)
Reply
#2
I am not going to look at your project on github and search your code for where the LED is set. Post the relevant code.
Reply
#3
The project you posted doesn't even look like it has anything to do with a blinking LED.......

What exactly are you trying to do?
Reply
#4
(Aug-06-2020, 04:09 AM)t4keheart Wrote: The project you posted doesn't even look like it has anything to do with a blinking LED.......

What exactly are you trying to do?

I want to add a led to the project. But don’t have a clue where to add any new code. I have connected a led and resistor to gpio 27. The project has a few scripts like main.py. Contacts.py. Pygame.py.
Reply
#5
Show us at least the code that makes the led blink,
that should be only a few lines, probably in a while loop.

Then ask yourself, if my program is doing that, anything else
would need to be simultaneous. That may have hardware consequences.

A month or 2 ago, there was a question about multiple simultaneous blinking
lights: introducing a small transistor chip was the solution.

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#6
i have now added some script from the project. the main.py. loads all the other scripts i think.
Reply
#7
(Aug-06-2020, 07:45 AM)corsasri Wrote: i have now added some script from the project. the main.py. loads all the other scripts i think.

OK, but what is your code to make the led flash?

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#8
(Aug-06-2020, 09:27 AM)DPaul Wrote:
(Aug-06-2020, 07:45 AM)corsasri Wrote: i have now added some script from the project. the main.py. loads all the other scripts i think.

OK, but what is your code to make the led flash?

Paul

from gpiozero import LED
from time import sleep

led = LED(27)

while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)
Reply
#9
OK, that is a possibility, but nothing else can happen without disturbing the blinking pattern,
unless you consider parallel or simultaneous processing.

Depending on your setup you may have to decide on a software or a hardware solution.

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#10
(Aug-06-2020, 03:06 PM)DPaul Wrote: OK, that is a possibility, but nothing else can happen without disturbing the blinking pattern,
unless you consider parallel or simultaneous processing.

Depending on your setup you may have to decide on a software or a hardware solution.

Paul

So how do I distribute the blinking. Or do the processing?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Flash is not working in flask sahilsiddharth 3 9,900 Jul-01-2017, 08:13 PM
Last Post: sahilsiddharth

Forum Jump:

User Panel Messages

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