def main(self): """Gets data from internal sensors.""" utils.log_file("{} => checking up system status...".format(self.name), constants.LOG_LEVEL) core_temp = 0 core_vbat = 0 core_vref = 0 vref = 0 battery_level = 0 current_level = 0 ambient_temperature = 0 self.data = [] channels = [] for key in self.config["Adc"]["Channels"].keys(): channels.append(self.config["Adc"]["Channels"][key]["Ch"]) adcall = pyb.ADCAll(int(self.config["Adc"]["Bit"]), self.adcall_mask(channels)) for i in range( int(self.config["Samples"]) * int(self.config["Sample_Rate"])): core_temp += adcall.read_core_temp() core_vbat += adcall.read_core_vbat() core_vref += adcall.read_core_vref() vref += adcall.read_vref() battery_level += adcall.read_channel( self.config["Adc"]["Channels"]["Battery_Level"]["Ch"]) current_level += adcall.read_channel( self.config["Adc"]["Channels"]["Current_Level"]["Ch"]) ambient_temperature += adcall.read_channel( self.config["Adc"]["Channels"]["Ambient_Temperature"]["Ch"]) i += 1 core_temp = core_temp / i core_vbat = core_vbat / i core_vref = core_vref / i vref = vref / i battery_level = battery_level / i * vref / pow( 2, int(self.config["Adc"]["Bit"])) current_level = current_level / i * vref / pow( 2, int(self.config["Adc"]["Bit"])) ambient_temperature = ambient_temperature / i * vref / pow( 2, int(self.config["Adc"]["Bit"])) battery_level = self.battery_level(battery_level) current_level = self.current_level(current_level) ambient_temperature = self.ad22103(ambient_temperature, vref) epoch = utime.time() self.data.append(self.config["String_Label"]) self.data.append(str(utils.unix_epoch(epoch))) # unix timestamp self.data.append(utils.datestamp(epoch)) # YYMMDD self.data.append(utils.timestamp(epoch)) # hhmmss self.data.append("{:.4f}".format(battery_level)) self.data.append("{:.4f}".format(current_level)) self.data.append("{:.4f}".format(ambient_temperature)) self.data.append("{:.4f}".format(core_temp)) self.data.append("{:.4f}".format(core_vbat)) self.data.append("{:.4f}".format(core_vref)) self.data.append("{:.4f}".format(vref)) return True
async def main(self): pyb.LED(3).on() core_temp = 0 core_vbat = 0 core_vref = 0 vref = 0 battery_level = 0 current_level = 0 ambient_temperature = 0 self.data = [] channels = [] for key in self.config['Adc']['Channels'].keys(): channels.append(self.config['Adc']['Channels'][key]['Ch']) await asyncio.sleep(0) adcall = pyb.ADCAll(int(self.config['Adc']['Bit']), await self.adcall_mask(channels)) for i in range(int(self.samples) * int(self.sample_rate)): core_temp += adcall.read_core_temp() core_vbat += adcall.read_core_vbat() core_vref += adcall.read_core_vref() vref += adcall.read_vref() battery_level += adcall.read_channel( self.config['Adc']['Channels']['Battery_Level']['Ch']) current_level += adcall.read_channel( self.config['Adc']['Channels']['Current_Level']['Ch']) ambient_temperature += adcall.read_channel( self.config['Adc']['Channels']['Ambient_Temperature']['Ch']) i += 1 await asyncio.sleep(0) core_temp = core_temp / i core_vbat = core_vbat / i core_vref = core_vref / i vref = vref / i battery_level = battery_level / i * vref / pow( 2, int(self.config['Adc']['Bit'])) current_level = current_level / i * vref / pow( 2, int(self.config['Adc']['Bit'])) ambient_temperature = ambient_temperature / i * vref / pow( 2, int(self.config['Adc']['Bit'])) self.data.append(battery_level) self.data.append(current_level) self.data.append(ambient_temperature) self.data.append(core_temp) self.data.append(core_vbat) self.data.append(core_vref) self.data.append(vref) self.data.append(self.fs_freespace()) await self.log() pyb.LED(3).off()
def test_int_adc(): adc = pyb.ADCAll(12) # Test VBAT vbat = adc.read_core_vbat() vbat_diff = abs(vbat - 3.3) if (vbat_diff > 0.1): raise Exception('INTERNAL ADC TEST FAILED VBAT=%fv' % vbat) # Test VREF vref = adc.read_core_vref() vref_diff = abs(vref - 1.2) if (vref_diff > 0.1): raise Exception('INTERNAL ADC TEST FAILED VREF=%fv' % vref) adc = None print('INTERNAL ADC TEST PASSED...')
def test_features(lcd): # if we run on pyboard then use ADC and RTC features try: import pyb adc = pyb.ADCAll(12, 0xf0000) rtc = pyb.RTC() except: adc = None rtc = None # set orientation and clear screen lcd = get_lcd(lcd) lcd.set_orient(lcd160cr.PORTRAIT) lcd.set_pen(0, 0) lcd.erase() # create M-logo mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565) mlogo.fill(0) mlogo.fill_rect(1, 1, 15, 15, 0xffffff) mlogo.vline(4, 4, 12, 0) mlogo.vline(8, 1, 12, 0) mlogo.vline(12, 4, 12, 0) mlogo.vline(14, 13, 2, 0) # create inline framebuf offx = 14 offy = 19 w = 100 h = 75 fbuf = framebuf.FrameBuffer(bytearray(w * h * 2), w, h, framebuf.RGB565) lcd.set_spi_win(offx, offy, w, h) # initialise loop parameters tx = ty = 0 t0 = time.ticks_us() for i in range(300): # update position of cross-hair t, tx2, ty2 = lcd.get_touch() if t: tx2 -= offx ty2 -= offy if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h: tx, ty = tx2, ty2 else: tx = (tx + 1) % w ty = (ty + 1) % h # create and show the inline framebuf fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192)) fbuf.line(w // 2, h // 2, w // 2 + int(40 * math.cos(0.2 * i)), h // 2 + int(40 * math.sin(0.2 * i)), lcd.rgb(128, 255, 64)) fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64)) fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64)) fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64)) for phase in (-0.2, 0, 0.2): x = w // 2 - 8 + int(50 * math.cos(0.05 * i + phase)) y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase)) fbuf.blit(mlogo, x, y) for j in range(-3, 3): fbuf.text('MicroPython', 5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))), lcd.rgb(128 + 10 * j, 0, 128 - 10 * j)) lcd.show_framebuf(fbuf) # show results from the ADC if adc: show_adc(lcd, adc) # show the time if rtc: lcd.set_pos(2, 0) lcd.set_font(1) t = rtc.datetime() lcd.write('%4d-%02d-%02d %2d:%02d:%02d.%01d' % (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000)) # compute the frame rate t1 = time.ticks_us() dt = time.ticks_diff(t1, t0) t0 = t1 # show the frame rate lcd.set_pos(2, 9) lcd.write('%.2f fps' % (1000000 / dt))
def battery_volts(): adc = pyb.ADCAll(12) return adc.read_core_vbat(), 3.3 / (adc.read_core_vref() / 1.21)
def adc_read(self, args): """ (simple) read ADC on a pin - this is a blocking call args: :param pin: pin name of gpio, X1, X2, ... or VBAT, TEMP, VREF, VDD :param samples: number of samples to take and then calculate average, default 1 :param sample_ms: number of milliseconds between samples, default 1 :return: """ pin = args.get("pin", None) if pin not in self.ADC_VALID_PINS and pin not in self.ADC_VALID_INTERNALS: value = {'err': "{} pin is not valid".format(pin)} self._ret.put({ "method": "adc_read", "value": value, "success": False }) return samples = args.get("samples", 1) sample_ms = args.get("sample_ms", 1) # print("DEBUG: test") adc = None adc_read = None if pin in self.ADC_VALID_PINS: adc = pyb.ADC(pyb.Pin('{}'.format(pin))) adc_read = adc.read else: adc = pyb.ADCAll(12, 0x70000) if pin == "TEMP": adc_read = adc.read_core_temp elif pin == "VBAT": adc_read = adc.read_core_vbat elif pin == "VREF": adc_read = adc.read_core_vref elif pin == "VDD": adc_read = adc.read_vref if adc is None or adc_read is None: value = {'err': "{} pin is not valid (internal error)".format(pin)} self._ret.put({ "method": "adc_read", "value": value, "success": False }) return results = [] for i in range(samples): results.append(float(adc_read())) if sample_ms: time.sleep_ms(sample_ms) sum = 0 for r in results: sum += r result = float(sum / len(results)) value = {'value': result, "samples": samples} self._ret.put({"method": "adc_read", "value": value, "success": True})
stm.mem32[stm.RTC + stm.RTC_BKP17R] = stm.mem32[stm.RTC + stm.RTC_BKP16R] stm.mem32[stm.RTC + stm.RTC_BKP16R] = (stm.mem32[stm.RTC] << 8) | ( stm.mem32[stm.RTC + stm.RTC_SSR] & 0xff) stm.mem32[stm.RTC + stm.RTC_BKP19R] += 1 import mymain dt = rtc.datetime() info1 = rtc.info() ts1 = pyb.micros() print('\n%d us 0x%x %d us 0x%x %d us LSx_dt: %d us' % (stupt, info0, ts0 - stupt, info1, ts1 - stupt, ts1 - ts0)) print('%d-%02d-%02d %02d:%02d:%02d.%06d' % (res[0], res[1], res[2], res[4], res[5], res[6], res[7])) try: adc = pyb.ADCAll(12, 0) except: adc = pyb.ADCAll(12) try: vref = adc.read_vref() except: vref = 3.3 print('Tcore: %.1f C Vcore_ref: %.3f V Vbat: %.3f V Vref: %.3f V' % (adc.read_core_temp(), adc.read_core_vref(), adc.read_core_vbat(), vref)) print('freq: ', pyb.freq()) print('LTE:') hexd(stm.RCC + 0x70, 0x10) led.off()
# - Joshua Vaughan # - [email protected] # - http://www.ucs.louisiana.edu/~jev9637 # # Modified: # * # # TODO: # * ############################################################################### import pyb # import the pyboard module import time # import the time module # We'll also read the internal information of the pyboard core_adc = pyb.ADCAll(12, 0x70000) # 12 bit resolution, internal channels # Now read the pot every 250ms, forever while (True): # read the internal board information core_temp = core_adc.read_core_temp() # read MCU temperature core_vbat = core_adc.read_core_vbat() # read MCU VBAT core_vref = core_adc.read_core_vref() # read MCU VREF vref = core_adc.read_vref() # read MCU supply voltage print("Core Properties") print("---------------") print("Core Temperature: {:5.2f} C".format(core_temp)) print("Backup Battery Voltage: {:5.2f} V".format(core_vbat)) print("Core Reference Voltage: {:5.2f} V".format(core_vref)) print("Reference Voltage: {:5.2f} V\n\n".format(vref))
def __init__(self): self.adv = ADC(Pin('X11')) self.adc = ADC(Pin('X12')) self.adt = pyb.ADCAll(12)
import pyb from BME280 import BME280 import ujson bme = BME280() adcall = pyb.ADCAll(12, 0x70000) vref = adcall.read_vref() adc0 = pyb.ADC(pyb.Pin.board.A0) adc1 = pyb.ADC(pyb.Pin.board.A1) adc2 = pyb.ADC(pyb.Pin.board.A2) adc3 = pyb.ADC(pyb.Pin.board.A3) adc4 = pyb.ADC(pyb.Pin.board.A4) adc5 = pyb.ADC(pyb.Pin.board.A5) adc6 = pyb.ADC(pyb.Pin.board.B1) # AIN0 or 6 on pyduino adc7 = pyb.ADC(pyb.Pin.board.B0) # AIN1 or 5 on pyduino usb = pyb.USB_VCP() myLed = pyb.LED(1) myLed.on() pyb.LED(2).on() pyb.LED(3).on() def convertToVoltage(adcVal, vref): return round((adcVal/4095) * vref, 3) while(True): if(usb.any()): req = usb.read()
import pyb import ure import BME280, time, ubinascii, machine from machine import UART, Pin, I2C from struct import unpack from cayennelpp import CayenneLPP adc = pyb.ADCAll(12) # create an ADCAll object rtc = pyb.RTC() rtc.wakeup(60000) led = pyb.LED(1) temp = 0.0 pa = 0.0 hum = 0.0 i2c = I2C(scl=pyb.Pin.board.PB6, sda=pyb.Pin.board.PB7, freq=10000) #i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21)) bme = BME280.BME280(i2c=i2c) uart = UART(2, 115200, timeout=2000) #uart.write("AT+NRB\r\n") #print(uart.read()) time.sleep(2.0) #TTN115 F411 DL7612-AS923 #uart.write("AT\r\n") #print(uart.read()) #uart.write("AT+ADR?\r\n") #print(uart.read())
# ADC Internal Channels Example # # This example shows how to read internal ADC channels. import time, pyb adc = pyb.ADCAll(12) print("VREF = %.1fv VREF = %.1fv Temp = %d" % (adc.read_core_vref(), adc.read_core_vbat(), adc.read_core_temp()))
#This example shows how to use the ADC, and how to # measure the internal reference to get a more accurate # ADC reading import pyb # set adc resolution to 12 bits adca = pyb.ADCAll(12) # channel 17 is the internal 1.21V reference ref_reading = adca.read_channel(17) # channel 0 (PA0) is the Vbus/2 connection usb_reading = adca.read_channel(0) # Use the internal reference to calculate the supply voltage # The supply voltage is used as the ADC reference and is not exactly 3.3V supply_voltage = 4095 / ref_reading * 1.21 print("supply voltage: " + str(supply_voltage) + "\n") # now calculate the USB voltage usb_voltage = usb_reading / 4095 * supply_voltage * 2 print("usb_voltage: " + str(usb_voltage) + "\n")