class Thermistor: """ NTC 模块。也适用于其他的热敏电阻。 :param pin: 掌控板引脚号,如使用P0,pin=0. :param series_resistor: 与热敏电阻连接的串联电阻器的值。默认是10K电阻。 :param nominal_resistance: 在标称温度下热敏电阻的阻值。 :param nominal_temperature: 在标称电阻值下热敏电阻的温度值(以摄氏度为单位)。默认使用25.0摄氏度。 :param b_coefficient: 热敏电阻的温度系数。 :param high_side: 表示热敏电阻是连接在电阻分压器的高侧还是低侧。默认high_side为True。 """ def __init__( self, pin, series_resistor=10000.0, nominal_resistance=10000.0, nominal_temperature=25.0, b_coefficient=3935.0, high_side=True ): self.adc = ADC(Pin(eval("Pin.P{}".format(pin)))) self.adc.atten(ADC.ATTN_11DB) self.series_resistor = series_resistor self.nominal_resistance = nominal_resistance self.nominal_temperature = nominal_temperature self.b_coefficient = b_coefficient self.high_side = high_side def getTemper(self): """ 获取温度,读取异常则返回None :return: 温度,单位摄氏度 """ try: if self.high_side: # Thermistor connected from analog input to high logic level. reading = self.adc.read_u16() / 64 reading = (1023 * self.series_resistor) / reading reading -= self.series_resistor else: # Thermistor connected from analog input to ground. reading = self.series_resistor / (65535.0 / self.adc.read_u16() - 1.0) steinhart = reading / self.nominal_resistance # (R/Ro) steinhart = math.log(steinhart) # ln(R/Ro) steinhart /= self.b_coefficient # 1/B * ln(R/Ro) steinhart += 1.0 / (self.nominal_temperature + 273.15) # + (1/To) steinhart = 1.0 / steinhart # Invert steinhart -= 273.15 # convert to C return steinhart except: return None
class Battery(object): def __init__(self, battery, charging, power=None): self._battery = ADC(battery) self._charging = charging self._power = power def charging(self): return self._charging.value() def power(self): if self._power: return self._power.value() return self._charging.value() def voltage_mv(self): # Assumes a 50/50 voltage divider and a 3.3v power supply raw = self._battery.read_u16() return (2 * 3300 * raw) // 65535 def level(self): # This is a trivial battery level estimation approach. It is assumes # the discharge from 4v to 3.5v is roughly linear and 4v is 100% and # that 3.5v is 5%. Below 3.5v the voltage will start to drop pretty # sharply to we will drop from 5% to 0% pretty fast... but we'll # live with that for now. mv = self.voltage_mv() level = ((19 * mv) // 100) - 660 if level > 100: return 100 if level < 0: return 0 return level
class Knob(object): def __init__(self, gpio): self.gpio = gpio self.adc = ADC(Pin(gpio)) def value(self): return 100*self.adc.read_u16()/65535
def _read_adc(): # exit if adc resolution was not set if not sharp1080.INIT: return 0 from machine import ADC, Pin conversion_factor = 3.3 / ((2**sharp1080.ADC_RES) - 1) # raspberry pico if sharp1080.INIT == sharp1080.PICO: adc = ADC(Pin(sharp1080.ADC_PIN)) raw = adc.read_u16() # esp8266 if sharp1080.INIT == sharp1080.ESP8266: adc = ADC(0) raw = adc.read() # esp32 if sharp1080.INIT == sharp1080.ESP32: adc = ADC(Pin(sharp1080.ADC_PIN)) adc.atten(ADC.ATTN_11DB) adc.width(ADC.WIDTH_12BIT) raw = adc.read() volt = raw * conversion_factor if sharp1080.DEBUG: print("adc_read: " + str(volt) + "V") return volt
def get_light(pin=26): temp2_sensor = ADC(pin) light = ADC(pin) conv_factor = 3.3 / 65535 lux = light.read_u16() * conv_factor / 2.3 * 100 return int(lux)
def get_temperature(pin=27): temp_sensor = ADC(pin) conv_factor = 3.3 / 65535 r0 = 100000.0 B = 4275.0 temp = float(temp_sensor.read_u16() * conv_factor) vol = temp print(temp_sensor.read_u16()) print(temp) r = 1023 / temp - 1 r = r0 * r temp = 1 / (math.log(r / r0) / B + (1 / 298.15)) - 273.15 a = 0.029411764705882353 b = -23.529411764705884 temp2 = a * temp_sensor.read_u16() * conv_factor * 1000 + b return (temp2, int(vol * 1000))
def getTemperature(): # Get Temperature temp_sensor = ADC(4) temperature = temp_sensor.read_u16() to_volts = 3.3 / 65535 temperature = temperature * to_volts celcius_degrees = 27 - (temperature - 0.706) / 0.001721 return celcius_degrees
def volt(adc): if isinstance(adc, ADC): pass else: adc = ADC(int(adc)) # Vref = 3.3v on rpi pico # 3.3 / 65535 = 5.035477e-05 return adc.read_u16() * 5.035477e-05
def log_voltages(file_name): adc = ADC(26) with open(file_name, 'w') as csv: while True: voltage = 3.3 * adc.read_u16() / 65535.0 text = '%5.3f' % voltage print(text) csv.write(text) csv.write('\n') time.sleep(60)
class AnalogIn_Driver(object): """Mock driver for build-in ADC.""" def __init__(self, pin): """ Requires an ADC enabled pin. """ self._pin = ADC(pin) self._data = array.array("I", [0]) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def readADC(self, chan): """ Returns error code and A/D value of channel `chan` as tuple; here only `chan` == 0 is allowed """ assert chan == 0, "readADC error: `chan` must be 0" return self._pin.read_u16() def update(self): """ Updates the A/D data for the channel; implemented for compatibility reasons. """ self._data[0] = self._pin.read_u16() @property def data(self): """ Array with A/D data """ return self._data @property def channelCount(self): return CHAN_COUNT @property def maxValue(self): return MAX_VALUE @property def channelMask(self): return 0x01 @channelMask.setter def channelMask(self, value): pass
class Analog: def __init__(self, pin, amplifier_gain=1, resistor=0): self.gain = amplifier_gain self.resistor = resistor self.pin = ADC(pin) def read_voltage(self): return self.pin.read_u16() * 3.3 / 65535 / self.gain def read_current(self): if self.resistor > 0: return self.read_voltage() / self.resistor else: return self.read_voltage()
class AnalogIn(object): """Basic analog input.""" def __init__(self, pin): self._pin = ADC(pin) def deinit(self): self._pin = None @property def value(self): return self._pin.read_u16() @property def max_adc(self): return MAX_VALUE
class AnalogueReader: """A base class for common analogue read methods. This class in inherited by classes like Knob and AnalogueInput and does not need to be used by user scripts. """ def __init__(self, pin, samples=DEFAULT_SAMPLES): self.pin = ADC(Pin(pin)) self.set_samples(samples) def _sample_adc(self, samples=None): # Over-samples the ADC and returns the average. values = [] for _ in range(samples or self._samples): values.append(self.pin.read_u16()) return round(sum(values) / len(values)) def set_samples(self, samples): """Override the default number of sample reads with the given value.""" if not isinstance(samples, int): raise ValueError( f"set_samples expects an int value, got: {samples}") self._samples = samples def percent(self, samples=None): """Return the percentage of the component's current relative range.""" return self._sample_adc(samples) / MAX_UINT16 def range(self, steps=100, samples=None): """Return a value (upper bound excluded) chosen by the current voltage value.""" if not isinstance(steps, int): raise ValueError(f"range expects an int value, got: {steps}") percent = self.percent(samples) if int(percent) == 1: return steps -1 return int(percent * steps) def choice(self, values, samples=None): """Return a value from a list chosen by the current voltage value.""" if not isinstance(values, list): raise ValueError(f"choice expects a list, got: {values}") percent = self.percent(samples) if percent == 1.0: return values[-1] return values[int(percent * len(values))]
def main(): freq = 0 i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000) adc = ADC(0) lcd = I2cLcd(i2c, 0x27, 2, 16) lcd.putstr("starting\nproject") time.sleep(2) lcd.clear() s = socket.socket() ai = socket.getaddrinfo("0.0.0.0", 80) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(addr) s.listen(5) lcd.putstr("Listening:80\n") ''' while True: res = s.accept() client_sock = res[0] client_addr = res[1] print("Client address:", client_addr) lcd.putstr("%s" % client_addr[0]) print("Client socket:", client_sock) client_stream = client_sock while True: data = input() print("to send data", data) client_stream.write(data) client_stream.close() ''' while True: conn, addr = s.accept() print('Connected by', addr) while True: lcd.clear() freq = int(input()) val = adc.read_u16() lcd.putstr("%s\n%s" % (val, freq)) print('data', val) try: conn.sendall(("%s,%s\r\n" % (val, freq)).encode()) except Exception as e: print('exception', e) break time.sleep_ms(20)
class Thermometer: def __init__(self, pin_id, R0, B, precision = 10): self.pin = ADC(Pin(pin_id)) self.R0 = R0 self.B = B self.precision = precision def analog_to_temp(self, val): R = (2**self.precision / val - 1.0 ) # print("R", R) # print("val", val) R = R*R0 # print("R", R) # print ("2**self.precision", 2**self.precision) temperature = 1.0/(math.log(R/R0)/B+1/298.15)-273.15 # Convert to temperature via datasheet return temperature def get_temperature(self): val = self.pin.read_u16() temp = self.analog_to_temp(val) return temp
class Pico(object): def __init__(self): self.led_pini = Pin(25, Pin.OUT) self.zamanlayici = Timer() def sicaklik_sensoru_ayarla(self): self.sicaklik_sensoru = ADC(4) def zamanlayiciyi_ayarla(self, frekans, mod, cb): self.zamanlayici.init(freq=frekans, mode=mod, callback=cb) def zamanlayiciyi_durdur(self): self.zamanlayici.deinit() def led_yaksöndür(self, zamanlayici): self.led_pini.toggle() def celcius_oku(self): #Referans: #https://github.com/raspberrypi/pico-micropython-examples/blob/master/adc/temperature.py ham_deger = self.sicaklik_sensoru.read_u16() * 3.3 / (65535) return 27 - (ham_deger - 0.706) / 0.001721
def getSoilMoisture(name, adc): # Get data from the moisture sensor soil_sensor = ADC(adc) moisture = soil_sensor.read_u16() display = "" #min = 14200 #max = 17000 min = 14000 max = 17000 # Calculate the moisture percentage percent_init = ((moisture - min) * 100) / (max - min) percent = 100 - abs(percent_init) # Convert the numerical value into a readable value if moisture < min: display = "{}:Wet".format(name) elif moisture >= min and moisture < max: display = "{}:Dmp".format(name) elif moisture >= max: display = "{}:Dry".format(name) return [display, percent]
from machine import ADC import time sensor_temp = ADC(4) conversion_factor = 3.3 / (65535) while True: reading = sensor_temp.read_u16() * conversion_factor temperature = 27 - (reading - 0.706)/0.001721 print(temperature) time.sleep(1)
display.init(buf) display.set_backlight( 0.8 ) # comment out this line if you have a Pico Explorer as it doesn't have a controllable backlight vsys = ADC(29) # reads the system input voltage charging = Pin( 24, Pin.IN) # reading GP24 tells us whether or not USB power is connected conversion_factor = 3 * 3.3 / 65535 full_battery = 4.2 # these are our reference voltages for a full/empty battery, in volts empty_battery = 2.8 # the values could vary by battery size/manufacturer so you might need to adjust them while True: # convert the raw ADC read into a voltage, and then a percentage voltage = vsys.read_u16() * conversion_factor percentage = 100 * ((voltage - empty_battery) / (full_battery - empty_battery)) if percentage > 100: percentage = 100.00 # draw the battery outline display.set_pen(0, 0, 0) display.clear() display.set_pen(190, 190, 190) display.rectangle(0, 0, 220, 135) display.rectangle(220, 40, 20, 55) display.set_pen(0, 0, 0) display.rectangle(3, 3, 214, 129) # draw a green box for the battery level
# Load the raspberry pi logo into the framebuffer (the image is 32x32) fb = framebuf.FrameBuffer(buffer, 32, 32, framebuf.MONO_HLSB) # Clear the oled display in case it has junk on it. oled.fill(0) # Blit the image from the framebuffer to the oled display oled.blit(fb, 96, 0) # Add some text oled.text("Raspberry Pi", 5, 5) oled.text("Pico", 5, 15) # Finally update the oled display so the image & text is displayed oled.show() while True: sleep(5) temp_sensor = ADC(TEMP_ADC) temperature = temp_sensor.read_u16() to_volts = 3.3 / 65535 temperature = temperature * to_volts celsius_degrees = 27 - (temperature - 0.706) / 0.001721 fahrenheit_degrees = celsius_degrees * 9 / 5 + 32 print(fahrenheit_degrees) oled.fill(0) # Blit the image from the framebuffer to the oled display oled.blit(fb, 96, 0) oled.text(str(fahrenheit_degrees), 5, 5)
# Start conditions & positions ball = Ball(32, 16, 3, 3, 1, -1, SCREEN_WIDTH, SCREEN_HEIGHT) # vx = 2; vx = -2 player = Player(30, SCREEN_HEIGHT - 3, 15, 2, 0, 0) # Required to calculate dt for first time tick = time.ticks_ms() # Execute loop as long as game isnt lost while not ball.get_game_over(): ntick = time.ticks_ms() ball.update( time.ticks_diff(ntick, tick) // 100, player ) # the floor division // rounds the result down to the nearest whole number tick = ntick player.x = adc.read_u16() * (SCREEN_WIDTH - 15) / 1023 fbuf.fill(0) # Fill entire framebuf with specific color (0 == black) ball.draw(fbuf) # Inserts current ball position into frame player.draw(fbuf) # Inserts current player platform position into frame disp.block(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, dispArr) # Sends current frame to display time.sleep_ms(50) # Waits for next iteration # Game is lost... fbuf.fill(0) fbuf.text('GAME', 15, 8) fbuf.text('OVER', 15, 18) disp.block(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, dispArr) print('Score: ', ball.get_score()) # Score is sent through UART / USB
from machine import Pin, ADC, PWM from utime import sleep_ms adc = ADC(26) pwm = PWM(Pin(20)) pwm.freq(1000) while (True): pwm.duty_u16(adc.read_u16()) sleep_ms(100)
led = Pin(25, Pin.OUT) # external LED on Pi Pico t = Timer() temp = ADC(4) # use channel 4 for measuring temperature conversion_factor = 3.3 / (65536) def blink(Timer): led(1) time.sleep_ms(20) # LED on for 20 milliseconds led(0) t.init(period=1000, mode=Timer.PERIODIC, callback = blink) print('\nThis program will show some information about the StackyPi board') print('and the usage of some on-board ressources of Raspberry Pi Pico Board\n') print('The external led blinks ones per second\n') print('This is a {}'.format(uos.uname().machine)) print('Installed firmware version is {}\n'.format(uos.uname().version)) print('Platform is {}'.format(sys.platform)) print('Micropython version is {}'.format(sys.version)) print('CPU frequency is {:3.0f} MHz'.format(machine.freq()/1e6)) # read value, 0-65535 across voltage range 0.0v - 3.3v reading = temp.read_u16() * conversion_factor # The temperature sensor measures the Vbe voltage of a biased bipolar diode, connected to the fifth ADC channel # Typically, Vbe = 0.706V at 27 degrees C, with a slope of -1.721mV (0.001721) per degree. intTemp = 27 - (reading - 0.706)/0.001721 print('On-Chip temperature is {:3.1f} °C'.format(intTemp))
# AIO_Test.py # 類比輸出入信號GPIO測試程式 # OmniXRI Jack, May 2021 from machine import Pin, ADC, PWM # 從machine導入Pin, ADC, PWM硬體參數設定類別 import utime # 導入時間相關函式庫 pwm = PWM(Pin(18)) # 設定LED1為PWM輸出腳 pwm.freq(1000) # 設定PWM頻率為1000 Hz adc = ADC(2) # 設定連接到ADC2(GP28),亦可寫成ADC(28) factor = 3.3 / (65535) # 電壓轉換因子 while True: # 若真則循環 reading = adc.read_u16() # 讀取類比輸入值16bit無號整數 pwm.duty_u16(reading) # 將輸入值轉至PWM工作周期值 vlot = reading * factor # 將輸入值轉成電壓值 print(vlot) # 將輸入電壓值列印至Shell區 utime.sleep(0.1) # 延時0.1秒
from machine import Pin, ADC from time import sleep adc = ADC(Pin(26)) while True: duty = adc.read_u16() print(duty) sleep(1)
x = int((WIDTH - 4) / 2) y = int((HEIGHT - 4) / 2) oled.text('Pico Pong 2021', 10, 21) oled.text('by Jerzy Jasonek', 0, 41) oled.show() check_level(level) sleep(2) ################################### Game loop ################################# while not game_over: check_level(level) if not start: player2Y = (Pot2.read_u16()) if player2Y < 1000: one_player_game = True led_one_player_game.value(1) else: one_player_game = False led_one_player_game.value(0) else: #update player position if not one_player_game: player1Y = (Pot.read_u16() * conversion_factor) player1Y = convert(player1Y, 0, 3.3, 0, 44) else: player1Y = y - 10
from machine import Pin, I2C, ADC from ssd1306 import SSD1306_I2C import time i2c = I2C(0, sda=Pin(4), scl=Pin(5)) oled = SSD1306_I2C(128, 32, i2c) pushButton = Pin(17, Pin.IN, Pin.PULL_UP) analog = ADC(28) oled.fill(0) oled.rect(0, 0, 127, 31, 1) oled.text("Pico", 5, 22, 1) oled.show() while True: if pushButton.value() == 0: oled.fill(1) oled.show() time.sleep(1) reading = analog.read_u16() # 0 to 65535 w = int(reading / 512) n = int(reading / 6553.5) oled.fill(0) oled.fill_rect(0, 0, w, 31, 1) oled.text(str(n), 0, 10, 0) oled.show()
def raw(adc): if isinstance(adc, ADC): pass else: adc = ADC(int(adc)) return adc.read_u16()
#https://projects.raspberrypi.org/en/projects/getting-started-with-the-pico/8 from machine import ADC, Pin import utime adc = ADC(Pin(27)) #Pin27 = ADC1 while True: print(adc.read_u16()) utime.sleep(0.5)
[0, 0, 0, 0, 0, 0, 0, .15], #Fa [0, 0, 0, 0, 0, .1, 0, .25], #Sol [0, 0, 0, 0, 0, 0, .4, 0], #La [0, 0, 0, 0, 0, .2, 0, 0], #Si [0, 0, 0, .05, 0, 0, 0, 0] #Ut ] elif 18 == version: keyboard_crosstalk = [ #when I put my finger on key n. <line>, this is the % of parasitic response I can read on each of the keys. #To calibrate, uncomment the print() line in keyboard_AT42T1110.py, in keyboard.read_analog_keys() [0, .2, .05, .1, .05, 0, 0, 0], #Do [0.05, 0, .5, 0, .1, 0, 0, 0], #Re [0] * 8, #Mi [0, 0, 0, 0, 0, 0, 0, .1], #Fa [0, 0, 0, 0, 0, .1, 0, .1], #Sol [0, 0, 0, 0, 0, 0, .5, 0], #La [0, 0, 0, 0, 0, .2, 0, 0], #Si [0, 0, 0, 0, 0, .3, .3, 0] #Ut ] else: keyboard_crosstalk = None midi_rst = Pin("C10", Pin.OUT, value=0) vbat_ADC = ADC(Pin("B1")) vusb_ADC = ADC(Pin("B0")) vbat = lambda: vbat_ADC.read_u16() / 65536 * 3.3 * 2 vusb = lambda: vusb_ADC.read_u16() / 65536 * 3.3 * 2 main_startup_pin = keyboard_instr_pin #End