import board import neopixel from analogio import AnalogIn from simpleio import map_range # from adafruit_circuitplayground.express import cpx pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=0, brightness=0.1) pixels.fill((0, 0, 0)) pixels.show() # cpx.pixels.brightness = 0.05 analogin = AnalogIn(board.LIGHT) max_analog_value = 0 while True: if analogin.value > max_analog_value: max_analog_value = analogin.value # light value remapped to pixel position peak = map_range(analogin.value, 500, max_analog_value, 0, 10) print(analogin.value) print(int(peak)) for i in range(0, 10, 1): if i <= peak: pixels[i] = (0, 25, 0) #25 is darker than 255 else: pixels[i] = (0, 0, 0) pixels.show()
# Read analog voltage on A1 print("A1: %0.2f" % getVoltage(analog1in), end="\t") # use A2 as capacitive touch to turn on internal LED print("A2 touch: %d" % touch.raw_value, end="\t") if touch.value: print("A2 touched!", end="\t") led.value = touch.value if not buttons[0].value: print("Button D2 pressed!", end="\t") # optional! uncomment below & save to have it sent a keypress #kbd.press(Keycode.A) #kbd.release_all() if not buttons[1].value: print("Button D3 pressed!", end="\t") play_file(audiofiles[0]) if not buttons[2].value: print("Button D4 pressed!", end="\t") play_file(audiofiles[1]) # sweep a servo from 0-180 degrees (map from 0-255) servo.angle = simpleio.map_range(i, 0, 255, 0, 180) i = (i + 1) % 256 # run from 0 to 255 #time.sleep(0.01) # make bigger to slow down print("")
if time.monotonic() - last_update_internet_time > weather_update_freq: update_internet_time() last_update_internet_time = time.monotonic() # CURRENT WEATHER if time.monotonic() - last_update_current_weather > weather_update_freq: update_current_weather() last_update_current_weather = time.monotonic() # FORECASTS if time.monotonic() - last_update_forecast > weather_update_freq: update_forecast() last_update_forecast = time.monotonic() # BRIGHTNESS board.DISPLAY.brightness = simpleio.map_range(light.value, 0, 40000, 0, 100) / 100 # CLEAR MEMORY print('X Clear memory... Mem free: {:,} allocated: {:,}'.format( gc.mem_free(), gc.mem_alloc()), end='') gc.collect() print(' | Mem free: {:,} allocated: {:,}'.format(gc.mem_free(), gc.mem_alloc()), end='') print(' | Progress: {:02.0f}'.format(progress), '%') # UPDATE DISPLAY display.show(group) time.sleep(update_freq)
# time.monotonic for blinka animation slither = 0 # blinka animation sprite index g = 1 # array for random beat division values rando_div = [240, 120, 60, 30, 15] # array of beat division values beat_division = [whole, half, quarter, eighth, sixteenth] # strings for beat division names beat_division_name = ["1", "1/2", "1/4", "1/8", "1/16", "Random"] while True: # mapping analog pot values to the different parameters # MIDI modulation 0-127 mod_val1 = round(simpleio.map_range(val(mod_pot), 0, 65535, 0, 127)) # BPM range 60-220 bpm_val1 = simpleio.map_range(val(bpm_slider), 0, 65535, 60, 220) # 6 options for beat division beat_val1 = round(simpleio.map_range(val(beat_pot), 0, 65535, 0, 5)) # 12 options for key selection key_val1 = round(simpleio.map_range(val(key_pot), 0, 65535, 0, 11)) # 6 options for mode selection mode_val1 = round(simpleio.map_range(val(mode_pot), 0, 65535, 0, 5)) # sending MIDI modulation if abs(mod_val1 - mod_val2) > 2: # updates previous value to hold current value mod_val2 = mod_val1 # MIDI data has to be sent as an integer # this converts the pot data into an int
except ValueError: # these happen, no biggie - retry continue # print("Time for data aquisition: %0.2f s" % (time.monotonic()-stamp)) mini = frame[0] # Define a min temperature of current image maxi = frame[0] # Define a max temperature of current image for h in range(24): for w in range(32): t = frame[h * 32 + w] if t > maxi: maxi = t if t < mini: mini = t image_bitmap[w, (23 - h)] = int( map_range(t, min_t, max_t, 0, last_color)) min_label.text = "%0.2f" % (min_t) max_string = "%0.2f" % (max_t) max_label.x = 120 - (5 * len(max_string) ) # Tricky calculation to left align max_label.text = max_string min_t = mini # Automatically change the color scale max_t = maxi # print((mini, maxi)) # Use this line to display min and max graph in Mu # print("Total time for aquisition and display %0.2f s" % (time.monotonic()-stamp))
)) time.sleep(0.2) else: print("Waiting for connection") while not ble.connected: pass print("Connected") while ble.connected: # Feather Sense accelerometer readings to CC accel_data = sense_accel.acceleration # get accelerometer reading accel_x = accel_data[0] accel_y = accel_data[1] # accel_z = accel_data[2] # Remap analog readings to cc range cc_x = int(simpleio.map_range(accel_x, 0, 9, 127, 0)) cc_y = int(simpleio.map_range(accel_y, 1, -9, 0, 127)) cc_thumb = get_flex_cc(analog_in_thumb, 49000, 35000, 127, 0) cc_index = get_flex_cc(analog_in_index, 50000, 35000, 0, 127) cc_middle = get_flex_cc(analog_in_middle, 55000, 40000, 0, 127) cc_ring = get_flex_cc(analog_in_ring, 55000, 42000, 0, 127) ''' print( "CC_X:{} CC_Y:{} CC_Thumb:{} CC_Index:{} CC_Middle:{} CC_Ring:{}".format( cc_x, cc_y, cc_thumb, cc_index, cc_middle, cc_ring ) )''' # send all the midi messages in a list midi.send([
def adc_to_wind_speed(val): """Returns anemometer wind speed, in m/s. :param int val: ADC value """ voltage_val = val / 65535 * 3.3 return map_range(voltage_val, 0.4, 2, 0, 32.4)
import simpleio print("Aloha") cpx.pixels.auto_write = False cpx.pixels.brightness = 0.05 while True: if cpx.switch: print("Slide switch set to off!") cpx.pixels.fill((0, 0, 0)) continue else: x, y, z = cpx.acceleration x_value = abs(int(simpleio.map_range(x, -10, 10, 0, 10))) y_value = abs(int(simpleio.map_range(y, -10, 10, 0, 10))) z_value = abs(int(simpleio.map_range(z, -10, 10, 0, 10))) print((x_value, y_value, z_value)) if x_value >= 8: cpx.pixels[2] = (0, 150, 150) else: cpx.pixels[2] = (0, 0, 0) if x_value >= 7 and y_value >= 3: cpx.pixels[3] = (0, 150, 150) else: cpx.pixels[3] = (0, 0, 0)
if touch_raw_value > 800: print("chase") color_chase(PURPLE, 0.1) else: pixels.fill((0, 0, 0)) pixels.show() # potentiomter + servo # uncomment this line to see the values of the pot # print((ss.analog_read(pot),)) # time.sleep(0.25) # maps the range of the pot to the range of the servo angle = map_range(ss.analog_read(pot), 0, 1023, 180, 0) # sets the servo equal to the relative position on the pot crickit.servo_1.angle = angle # Light sensor + DC motor # uncomment to see values of light # print(light_in.value) # time.sleep(0.5) # reads the on-board light sensor and graphs the brighness with NeoPixels # light value remaped to motor speed peak = map_range(light_in.value, 3000, 62000, 0, 1) # DC motor
# to keep the connection active #try: #io.loop() #except (ValueError, RuntimeError) as e: #print("Failed to get data, retrying...\n", e) #wifi.reset() #continue now = time.monotonic() print("reading soil sensor...") # Read capactive moisture = ss.moisture_read() label_level.text = str(moisture) # Convert into percentage for filling the screen moisture_percentage = map_range(float(moisture), SOIL_LEVEL_MIN, SOIL_LEVEL_MAX, 0.0, 1.0) # Read temperature temp = ss.get_temp() temp = display_temperature(temp) # fill display print("filling disp..") fill_water(moisture_percentage) print("disp filled..") print("temp: " + str(temp) + " moisture: " + str(moisture)) # Play water level alarms if moisture <= SOIL_LEVEL_MIN and alarm_sounded_min == False: print("Playing low water level warning...")
if sin_bright == 0 and sin_slope > 0: cpx.pixels[sin_pix] = (0, 0, 0) sin_pix = (sin_pix + 1) % 10 elif sin_bright >= 0: cpx.pixels[sin_pix] = (sin_bright, 0, 0) else: cpx.pixels[sin_pix] = (0, abs(sin_bright), 0) start = now if button_iter == 5: if time.monotonic() % 30 == 0: max_light_reading = 0 if now - start > 0.1: brightness = cpx.light if brightness > max_light_reading: max_light_reading = brightness peak = map_range(brightness, 0, max_light_reading, 0, 10) for i in range(0, 10, 1): if i <= peak: cpx.pixels[i] = (0, 15, 0) #25 is darker than 255 else: cpx.pixels[i] = (1, 0, 0) start = now if button_iter == 6: if now - start > 0.1: x, y, z = cpx.acceleration if x <= (-1 * accel_threshold): cpx.pixels[7] = (0, accel_brightness, 0) else: cpx.pixels[7] = (0, 0, 0) if x >= accel_threshold: cpx.pixels[2] = (0, accel_brightness, 0)
# PROJ01 - Theremin # (CircuitPython) # this circuit was designed for use with the Metro Express Explorers Guide on Learn.Adafruit.com # by Asher Lieber for Adafruit Industries. import board import analogio import pulseio from simpleio import map_range piezo = pulseio.PWMOut(board.D9) photo = analogio.AnalogIn(board.A0) while True: # map photo sensor value to hearable sound on piezo val = int(map_range(photo.value, 0, 65520, 1000, 64000)) piezo.duty_cycle = val
int(l * r) for l, r in zip(neopixel_utils.RED, (brightness, brightness, brightness))) if file_write_status == 'out_of_space': file_write_status_color = tuple( int(l * r) for l, r in zip(neopixel_utils.YELLOW, (brightness, brightness, brightness))) elif file_write_status == 'rw': file_write_status_color = tuple( int(l * r) for l, r in zip(neopixel_utils.GREEN, (brightness, brightness, brightness))) # Calculate color to display for temperatures cpu_temp_color_red = int(simpleio.map_range( cpu_temp, 20, 40, 0, 255)) # Scale the value of temp from (20, 40) to (0, 255) cpu_temp_color_blue = 255 - cpu_temp_color_red therm_temp_color_red = int(simpleio.map_range( therm_temp, 15, 40, 0, 255)) # Scale the value of temp from (15, 40) to (0, 255) therm_temp_color_blue = 255 - therm_temp_color_red # adjust color brightness based on ambient brightness cpu_temp_color_red = int(cpu_temp_color_red * brightness) cpu_temp_color_blue = int(cpu_temp_color_blue * brightness) therm_temp_color_red = int(therm_temp_color_red * brightness) therm_temp_color_blue = int(therm_temp_color_blue * brightness) if touch_A1.value: print("A1 touched!") if touch_A2.value:
try: mlx.getFrame(frame) except ValueError: # these happen, no biggie - retry continue # print("Time for data aquisition: %0.2f s" % (time.monotonic()-stamp)) mini = frame[0] # Define a min temperature of current image maxi = frame[0] # Define a max temperature of current image for h in range(24): for w in range(32): t = frame[h * 32 + w] if t > maxi: maxi = t if t < mini: mini = t image_bitmap[w, (23 - h)] = int(map_range(t, min_t, max_t, 0, last_color)) min_label.text = "%0.2f" % (min_t) max_string = "%0.2f" % (max_t) max_label.x = 120 - (5 * len(max_string)) # Tricky calculation to left align max_label.text = max_string min_t = mini # Automatically change the color scale max_t = maxi # print((mini, maxi)) # Use this line to display min and max graph in Mu # print("Total time for aquisition and display %0.2f s" % (time.monotonic()-stamp))
clue_display.patch_label.text = "Connected!" time.sleep(1.0) clue_display.show_screen(0) while BLE.connected: if clue.button_a: if not debouncer.hot(BUTTONS["MODE"]): clue_display.next_screen() ACCEL_DATA = clue.acceleration PROX_DATA = clue.proximity ACCEL_X = ACCEL_DATA[0] if clue_display.current_screen == 0: midi_data = [] # Remap analog readings to cc range cc_x = int(simpleio.map_range(ACCEL_X, -9, 9, 0, 127)) cc_x = remap(cc_x, START_RANGE, 127, 0, 127) midi_data.append( ControlChange(clue_display.starting_patch + 4, cc_x)) # It's easier to map it inverted for a shoe mount... # CC_Y = int(simpleio.map_range(ACCEL_Y, -9, 9, 0, 127)) if clue.white_leds and debouncer.hot(BUTTONS["PROXY"], check=True): clue.white_leds = False CC_PROX = int(simpleio.map_range(clue.proximity, 0, 255, 0, 127)) CC_PROX_SWITCH = 127 if CC_PROX > 4 else 0 if CC_PROX_SWITCH != 0 and not debouncer.hot(BUTTONS["PROXY"]): clue.white_leds = True midi_data.append( ControlChange(clue_display.starting_patch + 3, CC_PROX_SWITCH)) if clue.touch_0:
# run state for main program after selecting whether or not to connect to wifi if run: # print eCO2 and TVOC data to REPL print("eCO2 = %d ppm \t TVOC = %d ppb" % (sgp30.eCO2, sgp30.TVOC)) # 2 second delay time.sleep(2) # fumes variable for reading from SGP30 # comment out either TVOC or eCO2 depending on data preference fumes = sgp30.TVOC # fumes = sgp30.eCO2 # mapping fumes data to fan RPM # value for TVOC mapped_val = simpleio.map_range(fumes, 10, 1000, 10, 100) # value for eCO2 # mapped_val = simpleio.map_range(fumes, 400, 2500, 10, 100) # adding fume text # PPB is for TVOC, PPM is for eCO2 funhouse.set_text("%d PPB" % fumes, fume_text) # funhouse.set_text("%d PPM" % fumes, fume_text) # adding fan's RPM text funhouse.set_text("%d%s" % (mapped_val, "%"), fan_text) # printing fan's data to the REPL print("fan = ", mapped_val) # setting fan's RPM emc.manual_fan_speed = int(mapped_val)
import time from adafruit_circuitplayground.express import cpx import touchio import simpleio import board cpx.pixels.brightness = 0.2 touch = touchio.TouchIn(board.A1) DRY_VALUE = 1500 # calibrate this by hand! WET_VALUE = 2100 # calibrate this by hand! while True: value_A1 = touch.raw_value print((value_A1, )) # fill the pixels from red to green based on soil moisture percent_wet = int( simpleio.map_range(value_A1, DRY_VALUE, WET_VALUE, 0, 100)) cpx.pixels.fill((100 - percent_wet, percent_wet, 0)) time.sleep(0.5)
import time import digitalio import adafruit_bus_device import adafruit_hcsr04 import simpleio sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D11, echo_pin=board.D12) dot = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=.1) r = 0 g = 0 b = 0 while True: try: print((sonar.distance, )) if sonar.distance < 20: r = simpleio.map_range(sonar.distance, 0, 20, 255, 0) b = simpleio.map_range(sonar.distance, 5, 20, 0, 255) g = simpleio.map_range(sonar.distance, 20, 35, 0, 255) else: r = simpleio.map_range(sonar.distance, 0, 20, 255, 0) b = simpleio.map_range(sonar.distance, 35, 20, 255, 0) g = simpleio.map_range(sonar.distance, 20, 35, 0, 255) dot.fill((int(r), int(b), int(g))) except RuntimeError: print("Retrying!") time.sleep(0.1)
import time #pylint: disable-msg=import-error import board #pylint: disable-msg=import-error from analogio import AnalogIn #pylint: disable-msg=import-error import busio #pylint: disable-msg=import-error import simpleio #pylint: disable-msg=import-error potentiometer = AnalogIn(board.A0) uart = busio.UART(board.TX, board.RX, baudrate=9600) def get_voltage(pin): return(pin.value * 3.3) / 6553 while True: #print (get_voltage(potentiometer)) myPotValue = simpleio.map_range(potentiometer.value, 0, 65000, 0, 180) print((myPotValue)) uart.write(bytes([int(myPotValue)])) time.sleep(.1)
# CircuitPlaygroundExpress_LightSensor # reads the on-board light sensor and graphs the brightness with NeoPixels import time import board import neopixel from analogio import AnalogIn from simpleio import map_range pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=0, brightness=.05) pixels.fill((0, 0, 0)) pixels.show() analogin = AnalogIn(board.LIGHT) while True: # light value remapped to pixel position peak = map_range(analogin.value, 2000, 62000, 0, 9) print(analogin.value) print(int(peak)) for i in range(0, 9, 1): if i <= peak: pixels[i] = (0, 255, 0) else: pixels[i] = (0, 0, 0) pixels.show() time.sleep(0.01)
def heard_signal(threshold): return (simpleio.map_range(mic.get_mic_magnitude(), 15, 1000, 0, 1) > threshold)
def get_flex_cc(sensor, low_in, high_in, min_out, max_out): flex_raw = sensor.value flex_cc = simpleio.map_range(flex_raw, low_in, high_in, min_out, max_out) flex_cc = int(flex_cc) return flex_cc
# update led display if "led" or "big_led" in clock_display: led_disp.colon = not led_disp.colon # Check to see if time was set new_xst_datetime, clock_sound, update_flag = led_disp.set_datetime( ds3231.datetime) if update_flag: # If so, update RTC Std Time with new datetime ds3231.datetime = new_xst_datetime print("RTC time was set") led_disp.dst = is_dst led_disp.show(current) # refresh LED display # Refresh FeatherM4 NeoPixel to show "second hand" r = int(map_range(current.tm_sec, 0, 45, 255, 100)) g = int(map_range(current.tm_sec, 15, 59, 100, 255)) b = int(map_range(current.tm_sec, 55, 59, 100, 255)) pixel[0] = (r, g, b) pixel.write() if "pybadge" in clock_display: pybadge_disp.colon = not pybadge_disp.colon # auto-refresh # Check to see if time was set new_xst_datetime, clock_sound, update_flag = pybadge_disp.set_datetime( ds3231.datetime) if update_flag: # If so, update RTC Std Time with new datetime ds3231.datetime = new_xst_datetime print("RTC time was set")
def set_pixels(): pixels[0] = PURPLE pixels[1] = BLUE pixels[2] = BLUE pixels[3] = CYAN pixels[4] = LIGHT_BLUE pixels[5] = YELLOW pixels[6] = ORANGE pixels[7] = RED pixels[8] = RED pixels[9] = RED while True: temp_c = temperature temp_f = temperature * 9 / 5 + 32 print("Temperature is: %f C and %f F" % (temp_c, temp_f)) set_pixels() # light value remapped to pixel position peak = simpleio.map_range(temp_f, 0, 100, 0, 9) for i in range(0, 10, 1): if i >= peak: pixels[i] = (0, 0, 0) pixels.show()
pixels[8] = (0, 255, 0) pixels[9] = (255, 255, 0) print("Not hot enough, right moisture level") # ALL GREEN = COMPOST AT OPTIMUM TEMPERATURE & MOISTURE elif compostTemp > tempThreshhold: pixels.fill((0, 255, 0)) # green print("Compost Ready") # LIGHTING CONFIGURATION # print value of light sensor print((light.value, )) # map light snesor range to neopixel brightness range peak = map_range(light.value, 2000, 62000, 0.01, 0.3) # print neopixel brightness levels print(peak) # show neopixels pixels.show() # update neopixel brightness based on level of exposed light pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=peak) # pause for three seconds time.sleep(3) # END PROGRAM
# SPDX-FileCopyrightText: 2021 Brent Rubell for Adafruit Industries # # SPDX-License-Identifier: MIT """ 'photo_sensor.py'. ================================================= uses LIGHT to control a LED """ import analogio import board import pwmio from simpleio import map_range LED = pwmio.PWMOut(board.D9) LIGHT = analogio.AnalogIn(board.A0) while True: LIGHT_VAL = map_range(LIGHT.value, 20000, 32766, 0, 32766) LED.duty_cycle = int(LIGHT_VAL)
print("CPU.freqency: ", microcontroller.cpu.frequency) print("CPU.temperature: ", microcontroller.cpu.temperature) # print("Battery voltage: ", AnalogIn(board.Ax) ) # not used # Slowly center (zero) the meter's output before reading the input voltage. # This should take about one second to move the needle to the center. meter_out_volt = inertia_move(-10, 0, 0.200, 0.050) time.sleep(0.500) # hold at center scale for 0.500 seconds # ### Main Loop ### while True: # Read the CV input and map to a +/-10V value. # Because of the input op-amp's signal inversion and fixed gain, a 0V # input to the Trinket's analog pin correlates to a CV input value of +10V; # a 3.3V input maps to a value of -10V. DO NOT adjust these values. cv_input_volt = map_range(cv_pin.value, 0, 65535, +10, -10) # Show the input voltage polarity on the DotStar indicator. if cv_input_volt > +1.0: # 1V noise threshold dot[0] = (0, 255, 0) # grn = positive neg_led.value = False zero_led.value = False pos_led.value = True elif cv_input_volt < -1.0: # 1V noise threshold dot[0] = (255, 0, 0) # red = negative neg_led.value = True zero_led.value = False pos_led.value = False else: dot[0] = (0, 0, 255) # blu = zero neg_led.value = False
# CircuitPlaygroundExpress_LightSensor # reads the on-board light sensor and graphs the brighness with NeoPixels from adafruit_circuitplayground.express import cpx from simpleio import map_range import time cpx.pixels.brightness = 0.05 while True: #light value remaped to pixel position peak = map_range(cpx.light, 10, 325, 0, 9) print(cpx.light) print(int(peak)) for i in range(0, 9, 1): if i <= peak: cpx.pixels[i] = (0, 255, 0) else: cpx.pixels[i] = (0, 0, 0) time.sleep(0.01)
""" 'map_range_demo.py'. ================================================= maps a number from one range to another """ import time import simpleio while True: sensor_value = 150 # Map the sensor's range from 0<=sensor_value<=255 to 0<=sensor_value<=1023 print("original sensor value: ", sensor_value) mapped_value = simpleio.map_range(sensor_value, 0, 255, 0, 1023) print("mapped sensor value: ", mapped_value) time.sleep(2) # Map the new sensor value back to the old range sensor_value = simpleio.map_range(mapped_value, 0, 1023, 0, 255) print("original value returned: ", sensor_value) time.sleep(2)
""" 'map_range_demo.py'. ================================================= maps a number from one range to another """ import time import simpleio while True: sensor_value = 150 # Map the sensor's range from 0<=sensor_value<=255 to 0<=sensor_value<=1023 print('original sensor value: ', sensor_value) mapped_value = simpleio.map_range(sensor_value, 0, 255, 0, 1023) print('mapped sensor value: ', mapped_value) time.sleep(2) # Map the new sensor value back to the old range sensor_value = simpleio.map_range(mapped_value, 0, 1023, 0, 255) print('original value returned: ', sensor_value) time.sleep(2)
import digitalio import adafruit_character_lcd as LCD import board import analogio from simpleio import map_range # LCD setup lcd_columns = 16 lcd_rows = 2 lcd_rs = digitalio.DigitalInOut(board.D7) lcd_en = digitalio.DigitalInOut(board.D8) lcd_d7 = digitalio.DigitalInOut(board.D12) lcd_d6 = digitalio.DigitalInOut(board.D11) lcd_d5 = digitalio.DigitalInOut(board.D10) lcd_d4 = digitalio.DigitalInOut(board.D9) lcd_backlight = digitalio.DigitalInOut(board.D13) lcd = LCD.cirpyth_char_lcd(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight) therm = analogio.AnalogIn(board.A0) # loop forever while True: # get temperature from sensor tmp = ((( (map_range(therm.value, 0, 65535, 0, 3.3)) - .5) * 100) * 1.8) + 32 lcd.clear() # lcd.message('temp: ' + str(therm.value * .004882814)[:5] + ' * f') lcd.message('temp: ' + str(tmp)[:5] + ' * f') time.sleep(.6)