igendel

Micro:bit candle counter

Nov 18th, 2025 (edited)
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | Source Code | 0 0
  1. # BBC Micro:bit IR-based candle detector and counter
  2. # by Ido Gendel, 2025
  3. # Hardware setup:
  4. # 3V -> L-53P3C 940nm NPN Phototransistor -> Pin 1 and 1K resistor -> GND
  5.  
  6. from microbit import *
  7.  
  8. # 3x5 digits patterns, 0 to 9 and then "E"
  9. digits = ["888808808808888",
  10.           "080880080080888",
  11.           "888008888800888",
  12.           "888008888008888",
  13.           "808808888008008",
  14.           "888800888008888",
  15.           "888800888808888",
  16.           "888008008008008",
  17.           "888808888808888",
  18.           "888808888008888",
  19.           "888800888800888"]
  20.  
  21. count = 0 # How many candles were detected
  22. currState = 0 # Are we seeing a candle now? (0/1)
  23. threshold = 3 # Range 1-5 inclusive, each step means 170 in raw values
  24.  
  25. def refresh(rawValue):
  26.    
  27.     image = [["0","0","0","0","0"],
  28.              ["0","0","0","0","0"],
  29.              ["0","0","0","0","0"],
  30.              ["0","0","0","0","0"],
  31.              ["0","0","0","0","0"]]
  32.    
  33.     # Draw current reading and threshold
  34.     image[5 - threshold][1] = "3"
  35.     value = int((rawValue / 1024) * 46)
  36.     for n in range(5):
  37.         temp = min(value, 9)
  38.         image[4 - n][0] = str(temp)
  39.         value = value - temp
  40.  
  41.     # Draw counter digit
  42.     for i in range(15):
  43.        image[i // 3][2 + (i % 3)] = digits[count][i]
  44.    
  45.     # Display completed image
  46.     s = ""
  47.     for line in image:
  48.         s = s + "".join(line) + ":"
  49.     display.show(Image(s[:-1]))
  50.        
  51.    
  52.  
  53. display.clear()
  54. while True:
  55.     rawValue = pin1.read_analog()
  56.     if currState == 0:
  57.         if (rawValue >= threshold * 170 + 85) and (count < 10):
  58.             currState = 1
  59.             count = count + 1
  60.     else:
  61.         if rawValue < threshold * 170 - 85:
  62.             currState = 0
  63.    
  64.     refresh(rawValue)
  65.    
  66.     if button_a.was_pressed():
  67.         threshold = threshold + 1
  68.         if threshold > 5:
  69.             threshold = 1
  70.            
  71.     if button_b.was_pressed():
  72.         count = 0
  73.         display.clear()
  74.         sleep(200)
  75.    
  76.  
Advertisement