sbilal0007
Posts: 1
Joined: Wed Dec 12, 2018 2:24 am

Raspbery Pi Zero W getting Heated and Dead when used the internal pull-up register for both GPIO13 and GPIO20

Wed Dec 12, 2018 2:47 am

I'm new to the raspberry pi. I have raspberry pi Zero W and I'm using it as a counter. I have used the GPIO26 and GPIO19 for two LED's Via 330ohm register with the ground.

I also using the GPIO13 (GPIO.setup( 13, GPIO.IN, pull_up_down = GPIO.PUD_UP )) for push-button.

For the counter, I added the limit switch between the GPIO20(20, GPIO.IN, pull_up_down = GPIO.PUD_UP) and Ground.

When limit switch triggers the circuit get close between GPIO20 and GROUND and program counter increases.

I have used the internal pull-up register for both GPIO13 and GPIO20.

Everything was working fine before adding the Limit switch and GPIO20 as a pull-up. But when I added this logic for counter then it works well for
1-2 days, after that raspberry pi getting heated and getting dead.

This script runs when my Pi boots up every time.

I'm not getting what's going wrong with the above.

Code: Select all

#!/usr/bin/env python
import time
import math
import subprocess
import RPi.GPIO as GPIO
import sys
import sqlite3
from sqlite3 import Error
from os import system
import json
import urllib3
from  urllib3.exceptions import RequestError
from  urllib3.exceptions import ResponseError
from  urllib3.exceptions import TimeoutError
from  urllib3.exceptions import HTTPError
from  urllib3.exceptions import ConnectionError
from  urllib3.exceptions import ConnectTimeoutError
from  urllib3.exceptions import HTTPWarning
from  urllib3.exceptions import SecurityWarning
from  urllib3.exceptions import PoolError

#Actual Machine ID from main Database
#Mechanical Press 60 Ton
machineID = 1

#Machine Ideal time in Seconds
idealTime = 5

http = urllib3.PoolManager()

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)

#change these as desired - they're the pins connected from the
#SPI port on the ADC to the Cobbler
SPICLK  = 18
SPIMISO = 23
SPIMOSI = 24
SPICS   = 25

# set up the SPI interface pins
GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
GPIO.setup(SPICLK,  GPIO.OUT)
GPIO.setup(SPICS,   GPIO.OUT)

#Setting pin 13 for button input
GPIO.setup( 13, GPIO.IN, pull_up_down = GPIO.PUD_UP )

#Dieset Red LED
GPIO.setup( 26, GPIO.OUT)

#For GREEN LED Status
GPIO.setup( 19, GPIO.OUT )

#GPIO  input signal
GPIO.setup( 20, GPIO.IN, pull_up_down = GPIO.PUD_UP )
GPIO.remove_event_detect(20)

mcStatus = 0
machineStroke = 0

lastTime = 0
currentTime = 0
isIdeal = False
isMachineStateChange = False

global mcLastOnOff
global mcLastDieset
global mcLastIdeal
global mcLastStamp

# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
  if ((adcnum > 7) or (adcnum < 0)):
    return -1
  GPIO.output(cspin, True)

  GPIO.output(clockpin, False)  # start clock low
  GPIO.output(cspin, False)     # bring CS low

  commandout = adcnum
  commandout |= 0x18  # start bit + single-ended bit
  commandout <<= 3    # we only need to send 5 bits here

  for i in range(5):
    if (commandout & 0x80):
      GPIO.output(mosipin, True)
    else:
      GPIO.output(mosipin, False)

    commandout <<= 1
    GPIO.output(clockpin, True)
    GPIO.output(clockpin, False)

  adcout = 0
  # read in one empty bit, one null bit and 10 ADC bits
  for i in range(12):
    GPIO.output(clockpin, True)
    GPIO.output(clockpin, False)
    adcout <<= 1

    if (GPIO.input(misopin)):
      adcout |= 0x1

  GPIO.output(cspin, True)

  adcout >>= 1       # first bit is 'null' so drop it
  return adcout

def readCTSensor(ADC_CH):
  vRMS       = 70.0  # Assumed or measured old 116.0 
  offset     = 1.65   # Half the ADC max voltage
  numTurns   = 2000   # 1:2000 transformer turns
  rBurden    = 3300   # Burden resistor value
  numSamples = 50   # Number of samples before calculating RMS

  #  if DEBUG:
  #    print "\nCT Sensor number of turns:", numTurns
  #    print "Actual burden resistor:", rBurden, "ohm"
  #    print "Number of samples:", numSamples
  #    print "AC (RMS Voltage):", vRMS, "V"

  voltage       = 0.0
  iPrimary      = 0.0
  acc           = 0.0
  apparentPower = 0.0

  # Take a number of samples and calculate RMS current
  for i in range(0, numSamples):
    # Read ADC, convert to voltage, remove offset
    sample = readadc(ADC_CH, SPICLK, SPIMOSI, SPIMISO, SPICS)
    voltage = (sample * offset * 2) / 1024
    voltage = voltage - offset

    iPrimary = (voltage / rBurden) * numTurns

    acc += pow(iPrimary, 2)
    time.sleep(0.001)

  iRMS = math.sqrt(acc / numSamples)  # Calculate RMS from accumulated values
  apparentPower = vRMS * iRMS         # Calculate apparent power


  return iRMS, apparentPower

def create_connection(db_file):

    try:
        conn = sqlite3.connect(db_file,20000, isolation_level = None)
	#Set journal mode to WAL.
	conn.execute('pragma journal_mode=wal')
        return conn
    except Error as e:
	GPIO.cleanup()
        print("DB Err in MAIN",e)

    return None

def main():

 #GPIO Callback for breaking the Ideal Status
 def stroke_callback(channel):
    global lastTime
    if(isIdeal == True):
      lastTime = time.time()

 global mcStatus
 global machineStroke
 dieSetNotified = 0
 isTimeUpdated = False
 global lastTime
 global currentTime
 global isIdeal
 global isMachineStateChange
 isStroke = False

 GPIO.add_event_detect(20, GPIO.BOTH, callback = stroke_callback, bouncetime = 1000)

 database_path = "/home/pi/Desktop/main_production/machine_database.db"

 #create a database connection
 conn = create_connection(database_path)
 cur = conn.cursor()

 sqlQuery = '''INSERT INTO machine_log (MachineId, MachineStatus, MachineStroke, Amp, DieSet, TimeStamp) VALUES(?,?,?,?,?,?)'''
 sqlQueryState = '''UPDATE machine_state SET OnOFF = ?, Dieset = ?, Ideal = ?, TimeStamp = ? WHERE ID = ?'''

 #Get Machine last status from database
 cur.execute("SELECT * FROM machine_state")
 rows = cur.fetchall()

 for row in rows:
   mcLastOnOff = row[1]
   mcLastDieset = row[2]
   mcLastIdeal = row[3]
   mcLastStamp = row[4]

 print('Last OnOff ', mcLastOnOff)
 print('Last Dieset ', mcLastDieset)
 print('Last Ideal ', mcLastIdeal)
 print('Last TimeStamp ', mcLastStamp)

 if(mcLastOnOff == 1 and mcLastDieset == 0 and mcLastIdeal == 1):
   try:
     #Ending machine Idle Status
     machineLogs = (machineID, 7, machineStroke, 0.0, mcLastDieset, mcLastStamp + 2.0)
     cur.execute(sqlQuery, machineLogs)

     #Setting machine to OFF
     machineLogs = (machineID, 2, machineStroke, 0.0, mcLastDieset, mcLastStamp + 3.0)
     cur.execute(sqlQuery, machineLogs)

     #Updating the current machine state
     machineStateLogs = (0, 0, 0, mcLastStamp + 3.0, 1)
     cur.execute(sqlQueryState, machineStateLogs)
     conn.commit()
   #Catch the exception
   except Exception as e:
     #Roll back any change if something goes wrong
     print("Database Exception In MAIN First elif",e)
     print(time.time())
     conn.rollback()

 elif(mcLastOnOff == 1 and mcLastDieset == 0 and mcLastIdeal == 0):
   try:
     #Setting machine to OFF
     machineLogs = (machineID, 2, machineStroke, 0.0, mcLastDieset, mcLastStamp + 1.0)
     cur.execute(sqlQuery, machineLogs)

     #Updating the current machine state
     machineStateLogs = (0, 0, 0, mcLastStamp + 1.0, 1)
     cur.execute(sqlQueryState, machineStateLogs)
     conn.commit()
   #Catch the exception
   except Exception as e:
     #Roll back any change if something goes wrong
     print("Database Exception In MAIN Second elif",e)
     print(time.time())
     conn.rollback()

 elif(mcLastOnOff == 1 and mcLastDieset == 1 and mcLastIdeal == 0):
   try:
     #Setting machine to OFF
     machineLogs = (machineID, 2, machineStroke, 0.0, mcLastDieset, mcLastStamp + 1.0)
     cur.execute(sqlQuery, machineLogs)

     #Updating the current machine state
     machineStateLogs = (0, 1, 0, mcLastStamp + 1.0, 1)
     cur.execute(sqlQueryState, machineStateLogs)
     conn.commit()
   #Catch the exception
   except Exception as e:
     #Roll back any change if something goes wrong
     print("Database Exception In MAIN Third elif",e)
     print(time.time())
     conn.rollback()

 #Synchronizing device time to server time for correct Timestamp
 while isTimeUpdated == False:

  print("Current Time : ", time.asctime(time.localtime(time.time())))

  try:
    response = http.request('POST','http://shreeapi.fosterbin.com/match_time.php', fields={'data': int(time.time())})
    newStatus = response.status
    print response.data
    timeStatus = json.loads(response.data.decode('utf-8'))['matchStatus']
    time.sleep(2)
  except (ValueError, ResponseError, TimeoutError, HTTPError, ConnectionError, ConnectTimeoutError, HTTPWarning, PoolError) as e:
    print('Conn fail!',e)
    newStatus = 0
    time.sleep(5)

  if(newStatus == 200):
    if(timeStatus == 1):
     isTimeUpdated = True
     #Lightning Up Green LED
     GPIO.output(19,True)
     if(mcLastDieset == 1):
       #Lightning Up Dieset LED
       GPIO.output(26,True)
     elif(mcLastDieset == 0):
       #Lightning Off Dieset LED
       GPIO.output(26,False)
    else:
     print("Time not Updated !!")
  else:
   print("No net !!")

 try:

  while True:

    #Getting Dieset status
    isDieSetRunning = GPIO.input(13)

    #Non-invasive current sensor connected to ADC #0
    iRMS, apparentPower = readCTSensor(0)
    #print(apparentPower)

    #Machine Start >> 1
    #Machine Stop >> 2
    #Machine DieSet Start >> 3
    #Machine DieSet Stop >> 4
    #Machine Data >> 5
    #Machine Ideal Start >> 6
    #Machine Ideal Stop >> 7

    #Getting Stroke Status
    isValidStroke = GPIO.input(20)

    #Machine On
    if( apparentPower >= 3  and mcStatus == 0 ): #and isDieSetRunning == False ):
      isMachineStateChange = True
      #Changing machine status to ON
      mcStatus = 1
      #When Machine ON then it should not be idle
      lastTime = time.time()
      #print(lastTime)

      try:
	 machineLogs = (machineID, 1, machineStroke, apparentPower, isDieSetRunning, time.time())
      	 cur.execute(sqlQuery, machineLogs)
      	 conn.commit()
      except Exception as e:
         #Roll back any change if something goes wrong
         print("Database Exception In MAIN Second elif",e)
         conn.rollback()

      print ("M On : ", machineStroke)

    #Machine Valid stroke
    elif( isValidStroke == False and isStroke == False and mcStatus == 1 and isDieSetRunning == False ):
      machineStroke += 1
      isStroke = True

      try:
        machineLogs = (machineID, 5, machineStroke, apparentPower, isDieSetRunning, time.time())
        cur.execute(sqlQuery, machineLogs)

        machineStateLogs = (mcStatus, isDieSetRunning, isIdeal, time.time(), 1)
        cur.execute(sqlQueryState, machineStateLogs)
        conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN : VS",e)
        print(time.time())
        conn.rollback()

      #When Machine producing production  then it's by default not idle
      lastTime = time.time()
      #print(lastTime)
      print ("VS :  ", machineStroke)

    elif(isValidStroke == True and isStroke == True):
      isStroke = False

    #Machine Off
    elif( apparentPower <= 1 and mcStatus == 1 ): #and isDieSetRunning == False ):
      isMachineStateChange = True
      #Changing machine status to OFF
      mcStatus = 0

      try:
        machineLogs = (machineID, 2, machineStroke, apparentPower, isDieSetRunning, time.time())
        cur.execute(sqlQuery, machineLogs)
        conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN : M Off",e)
        print(time.time())
        conn.rollback()

      print ("M Off : ", machineStroke)

    if(isDieSetRunning == True and mcLastDieset == 0):
      isMachineStateChange = True
      mcLastDieset = 1
      machineStroke = 0

      try:
         machineLogs = (machineID, 3, machineStroke, apparentPower, isDieSetRunning, time.time())
         cur.execute(sqlQuery, machineLogs)
         conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN Second : DS Start",e)
        print(time.time())
        conn.rollback()

      GPIO.output(26,GPIO.HIGH)

      print('DS : ', isDieSetRunning)

    elif(isDieSetRunning == False and mcLastDieset == 1):
      isMachineStateChange = True
      mcLastDieset = 0

      try:
        machineLogs = (machineID, 4, machineStroke, apparentPower, isDieSetRunning, time.time())
        cur.execute(sqlQuery, machineLogs)
        conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN Second : DS Stop",e)
        print(time.time())
        conn.rollback()

      GPIO.output(26,GPIO.LOW)

      #When Diset off then machine should not be idle
      lastTime = time.time()

      print('DS : ', isDieSetRunning)

    #Get the Idle time
    currentTime = time.time() - lastTime
    
    #print(currentTime)
    #print(isIdeal)
    #print(mcStatus)
    #print(isDieSetRunning)

    if(currentTime > idealTime and isIdeal == False and mcStatus == 1 and isDieSetRunning == False):
      isMachineStateChange = True
      isIdeal = True

      try:
        #Changing machine status to Idle
        machineLogs = (machineID, 6, machineStroke, apparentPower, isDieSetRunning, lastTime + 0.1)
        cur.execute(sqlQuery, machineLogs)
        conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN Second : Ideal Start",e)
        print(time.time())
        conn.rollback()

      print("M Ideal")

    elif(currentTime < idealTime and isIdeal == True and mcStatus == 1 and isDieSetRunning == False ):
      isMachineStateChange = True
      isIdeal = False

      try:
        #Changing machine status to Not Idle
	machineLogs = (machineID, 7, machineStroke, apparentPower, isDieSetRunning, time.time() + 0.1)
        cur.execute(sqlQuery, machineLogs)
        conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN Second : Ideal Stop",e)
        print(time.time())
        conn.rollback()

      print("M not Ideal")

    elif(isIdeal == True and (isDieSetRunning == True or mcStatus == 0)):
      isMachineStateChange = True
      isIdeal = False

      try:
        #Changing machine status to Idle
        machineLogs = (machineID, 7, machineStroke, apparentPower, isDieSetRunning, time.time() + 0.1)
        cur.execute(sqlQuery, machineLogs)
        conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN Second : Ideal Stop",e)
        print(time.time())
        conn.rollback()

      print("M not Ideal")

    if(isMachineStateChange == True):
      isMachineStateChange = False
      print("M Status changed !!")
      print("OnOff : ",mcStatus)
      print("Dieset : ",isDieSetRunning)
      print("Ideal : ",isIdeal)

      try:
         machineStateLogs = (mcStatus, isDieSetRunning, isIdeal, time.time(), 1)
         cur.execute(sqlQueryState, machineStateLogs)
         conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN Second : M Status Change",e)
        print(time.time())
        conn.rollback()

      system('python /home/pi/Desktop/main_production/post_with_urllib.py')
      #system('python /home/pi/Desktop/main_project/post_with_requests.py')

    if(isIdeal == True or isDieSetRunning == True):

      print("Ideal : ",time.time())

      try:
         machineStateLogs = (mcStatus, isDieSetRunning, isIdeal, time.time(), 1)
         cur.execute(sqlQueryState, machineStateLogs)
         conn.commit()
      except Exception as e:
        #Roll back any change if something goes wrong
        print("Database Exception In MAIN Second : M Status Change",e)
        print(time.time())
        conn.rollback()

      time.sleep(5)

 except KeyboardInterrupt:
   GPIO.cleanup()
   print ("Interrupt at Main program")

if __name__ == '__main__':
    main()

rhubarbdog
Posts: 64
Joined: Mon Dec 11, 2017 9:58 pm

Re: Raspbery Pi Zero W getting Heated and Dead when used the internal pull-up register for both GPIO13 and GPIO20

Wed Dec 12, 2018 5:01 am

Check your circuit.
It sounds like you have a short.
Try moving logic and circuit from pin20 to another pin. But thats probably just going to damage more of your pi

Return to “Troubleshooting”