Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 408
» Latest member: samiksha35
» Forum threads: 3
» Forum posts: 486

Full Statistics

Online Users
There are currently 9 online users.
» 0 Member(s) | 9 Guest(s)

Latest Threads
Sparkfun Battery Babysitt...
Forum: MicroPython
Last Post: olibali
11-05-2019, 01:35 PM
» Replies: 3
» Views: 442
CPU halted
Forum: ESP32
Last Post: brettfeeney
11-02-2019, 09:41 AM
» Replies: 2
» Views: 125
What IDE/tool to use with...
Forum: ESP32
Last Post: brettfeeney
10-24-2019, 12:52 AM
» Replies: 7
» Views: 1,114
unable to run microWebSrv
Forum: ESP32
Last Post: jczic
10-22-2019, 09:26 PM
» Replies: 11
» Views: 3,105
Persistent sessions with ...
Forum: Issues
Last Post: ahanakalibr
10-22-2019, 09:49 AM
» Replies: 4
» Views: 760
RA8876 support in Display...
Forum: General
Last Post: avanti
10-15-2019, 05:41 PM
» Replies: 0
» Views: 238
xpt2046 no calibration
Forum: Issues
Last Post: bingy
10-10-2019, 09:32 PM
» Replies: 0
» Views: 106
MicroPython for ESP32 cur...
Forum: Announcements and updates
Last Post: christian david
10-03-2019, 09:16 PM
» Replies: 8
» Views: 1,241
time.sleep() blocking
Forum: General
Last Post: larabrian
09-26-2019, 06:26 AM
» Replies: 8
» Views: 11,509
Move ESP32 Camera Project...
Forum: General
Last Post: xgarb
09-10-2019, 07:59 AM
» Replies: 2
» Views: 224

 
  CPU halted
Posted by: brettfeeney - 10-24-2019, 12:40 AM - Forum: ESP32 - Replies (2)

Hi there,

very new to micropython, but enjoying it so far. I am a bit of a novice so this may be where my issue lay Smile

I have a script that produces the error ... 

assertion "ATB_GET_KIND(block) == AT_HEAD" failed: file "/home/LoBo2_Razno/ESP32/MicroPython/MicroPython_ESP32_psRAM_LoBo/MicroPython_BUILD/components/micropython/py/gc.c", line 596, function: gc_free

abort() was called at PC 0x40121da3 on core 1

I have seen this mentioned elsewhere on the forum, wrt ports, but none of these discussions help with my current issue.

before posting here I ran the code through flake8 and pylint (ignoring some capitalization formatting etc), to make sure I was somewhat pythonic and free of some issues.

This is code for a flow meter that squirts it's measurements into influxdb, it has 2 threads that I start, one to manage a queue, and the other to keep an eye on the network.

It is no where near complete, and remember I am a novice ... but happy to take pointers to making it better.

Code:
import itertools
import machine
import utime
import _thread
import network
import uheapq
import urequests
#from machine import Pin
import uos
#import gc

sta_if = network.WLAN(network.STA_IF)

class Globals:
   oldTime = 0.0
   newTime = 0.0
   calibrationFactor = 22
   rtc = machine.RTC()
   rtc.ntp_sync(server="au.pool.ntp.org", tz="AEST-10AEDT,M10.1.0,M4.1.0/3")
   INTERRUPTCOUNTER = 0
   myStatus = 0
   journalfile = '/sd/journal.txt'
   readjournalfile = '/sd/readjournal.txt'
   numFlows = 0
   allTimeLiters = 0
   lperSec = 0
   oldqTime = 0
   upTimeStart = 0.0
   upTimeNow = 0.0

newTime = 0.0
flowRate = 0.0
rtc = machine.RTC()
rtc.ntp_sync(server="au.pool.ntp.org", tz="AEST-10AEDT,M10.1.0,M4.1.0/3")
totalInterruptsCounter = 0
oldPrintTime = 0.0
zeroCount = 0
toteMils = 0.0
theChosenOne = 16
counter = itertools.count()

rtc.synced()
myHeap = []
entry_finder = {}
REMOVED = ''
url_string = 'http://192.168.200.20:8086/write?db=Tankdb&precision=u'
urlPre = 'curl -i -XPOST \''
urlData = '\' --data-binary \''



def add_task(task, priority=0):
   'Add a new task or update the priority of an existing task'
   if task in entry_finder:
       remove_task(task)
   count = next(counter)
   entry = [priority, count, task]
   entry_finder[task] = entry
   uheapq.heappush(myHeap, entry)

def remove_task(task):
   'Mark an existing task as REMOVED.  Raise KeyError if not found.'
   entry = entry_finder.pop(task)
   entry[-1] = REMOVED

def pop_task():
   'Remove and return the lowest priority task. Raise KeyError if empty.'
   while myHeap:
       priority, count, task = uheapq.heappop(myHeap)
       if task is not REMOVED:
           del entry_finder[task]
           return task
   #raise KeyError('pop from an empty priority queue')

def tStamper():
   myNow = utime.time()
   if len(str(myNow).split('.')[1]) == 4:
       myU = str(myNow).split('.')[1] + "00"
   if len(str(myNow).split('.')[1]) == 3:
       myU = str(myNow).split('.')[1] + "000"
   if len(str(myNow).split('.')[1]) == 5:
       myU = str(myNow).split('.')[1] + "0"
   if len(str(myNow).split('.')[1]) == 2:
       myU = str(myNow).split('.')[1] + "0000"
   if len(str(myNow).split('.')[1]) == 1:
       myU = str(myNow).split('.')[1] + "00000"
   myuNow = int(str(myNow).split('.')[0] + myU)
   return myuNow

def easyTime():
   myTime = utime.localtime()
   easyT = (str(myTime[0]) + '-' + str("{:02d}".format(myTime[1])) + '-' + str("{:02d}".format(myTime[2])) + 'T' + str("{:02d}".format(myTime[3])) + ':' + str("{:02d}".format(myTime[4])) +  ':' + str("{:02d}".format(myTime[5])))
   return easyT

def queueThread():
   _thread.allowsuspend(True)
   Globals.oldqTime = utime.time()
   while True:
       utime.sleep(0.1)
       ntf = _thread.getnotification()
       if ntf:
           # some notification received
           if ntf == _thread.EXIT:
               print("queueThread: terminated")
               return

       qTime = utime.time()
       if qTime - Globals.oldqTime >= 60000:
           readjournal()
           Globals.oldqTime = utime.time()
       try:
           popped = pop_task()

           if popped is not None:
               Globals.lperSec = popped.split(" ")[0].strip()
               water_flow = popped.split(" ")[1].strip()
               popEd = popped.split(" ")[2].strip()
               popTime = str(popEd.split('.')[0])
               flowy = 'tank_monitor,host=flow01,location=north_east water_flow=' + str(water_flow) + " " + str(popTime) + '\ntank_monitor,host=flow01,location=north_east lPerSec=' + str(Globals.lperSec) + " " + str(popTime)
               #myTime = utime.localtime()

               if Globals.myStatus == 1:
                   #print(urlPre + url_string + urlData + flowy + '\'')
                   addTime = str(tStamper())
                   writejournal(str(Globals.lperSec) + " " + str(water_flow) + " " + addTime + "\n")
                   urequests.post(url_string, data=flowy)
                   #utime.sleep(2)
                   print(easyTime(), '### Sent to DB ###'+addTime+'\n')
                   deletejournal()
               if Globals.myStatus == 0:
                   try:
                       addTime = str(tStamper())
                       #print(urlPre + url_string + urlData + flowy + '\'')
                       writejournal(str(Globals.lperSec) + " " + str(water_flow) + " " + addTime +"\n")
                       print(easyTime(), '### Sent to JOURNAL ###'+addTime+'\n')
                       deletejournal()
                   except Exception as e:
                       print('Error in threadqueue: {}'.format(e))

           elif popped is None:
               utime.sleep(1) #foo = 1 # need something to silence error about empty heap.

       except Exception as e:
           print('Error: {}'.format(e))

def do_connect():
   if sta_if.isconnected() is True:
       print('Network Connected\n')
   if not sta_if.isconnected():
       while True:
           utime.sleep(0.1)
           print('Not Connected\n')
           print('connecting to network...\n')
           sta_if.active(True)
           sta_if.connect('unifi1-out', 'jedrocks')
           utime.sleep(5)
           print(sta_if.isconnected())
           if sta_if.isconnected() is True:
               return
   print('network config:', sta_if.ifconfig())

def networkThread():
   _thread.allowsuspend(True)

   while True:
       utime.sleep(0.1)
       ntf = _thread.getnotification()
       if ntf:
           if ntf == _thread.EXIT:
               print("networkThread: terminated")
               return
       Globals.myStatus = 1
       if sta_if.isconnected() is False:
           print("Network Not Connected")
           Globals.myStatus = 0
           do_connect()
           utime.sleep(10)
           if sta_if.isconnected() is True:
               Globals.myStatus = 1

def datacb(msg):
   if msg[1] == 'test/message' and msg[2] == 'How Are You':
       print('Health Check')
       client.publish('test/message', 'esp32_flow Says, All the people in my village are happy @ ' + str(easyTime()))
   if msg[1] == 'test/message' and msg[2] == 'How Long Have You Been Awake':
       print('Uptime request')
       Globals.myStatus = utime.time()
       curUp = round(Globals.myStatus - Globals.upTimeStart, 2)
       upUpAndAway = utime.strftime('%H:%M:%S', utime.gmtime(int(str(curUp).split('.')[0])))
       client.publish('test/message', 'esp32_flow has been awake for HH:MM:SS: '+ str(upUpAndAway) + " @: " + str(easyTime()))
   if msg[1] == 'test/message' and msg[2] == 'Whats Been Going On':
       print('How much work have I done')
       Globals.myStatus = utime.time()
       curUp = round(Globals.myStatus - Globals.upTimeStart, 2)
       upUpAndAway = utime.strftime('%H:%M:%S', utime.gmtime(int(str(curUp).split('.')[0])))
       client.publish('test/message', 'esp32_flow has flowed '+ str(Globals.numFlows) + ' Times, in ' + str(upUpAndAway) + ' totalling ' + str(Globals.allTimeLiters) + 'L @: ' + str(easyTime()))
   utime.sleep(0.5)

def callback(pin):
   Globals.INTERRUPTCOUNTER = Globals.INTERRUPTCOUNTER + 1


client = network.mqtt(name="pi", server="192.168.200.135", data_cb=datacb, clientid="flowister")
utime.sleep(1)
client.start()
utime.sleep(1)
status = client.status()[1]
print('MQTT status:', status)
client.subscribe('test/message')



def writejournal(what):
   f = open('/sd/journal.txt', "a")
   f.write(what)
   f.close()

def readjournal():
   try:
       myDir = uos.listdir('/sd/')
       print(myDir)
       for myfiles in myDir:
           if myfiles.startswith('readjournal'):
               uos.remove('/sd/readjournal.txt')
               print('### clean up old readjournals')

           if myfiles.startswith('journal.txt'):
               print(myfiles)
               print('### Reading Journal Entries into Queue ###')
               uos.rename('/sd/journal.txt', '/sd/readjournal.txt')
               with open(Globals.readjournalfile) as f:
                   for line in f:
                       line = line.rstrip()
                       add_task(line)
               uos.remove('/sd/readjournal.txt')
   except Exception as e:
       print(e)
       print('### No Journal left layin\' round ###')

def deletejournal():
   uos.remove(Globals.journalfile)


flowSignal = machine.Pin(theChosenOne, machine.Pin.IN, machine.Pin.PULL_UP)
flowSignal.init(trigger=machine.Pin.IRQ_FALLING, handler=callback)

#_thread.stack_size(4*1024)
networkth = _thread.start_new_thread("netty", networkThread, ())
queueth = _thread.start_new_thread("poppy", queueThread, ())



###########################################################

if __name__ == '__main__':
   client.publish('test/message', 'esp32_flow has just come online @ '+ str(easyTime()))
   Globals.upTimeStart = utime.time()
   try:
       #myDir = uos.listdir('/sd/')
       #print("dir", myDir)
       state = machine.disable_irq()
       machine.enable_irq(state)
       readjournal()

       while True:
           utime.sleep(0.1)
           newTime = utime.ticks_ms()
           printTime = newTime

           if Globals.INTERRUPTCOUNTER > 0:
               totalInterruptsCounter = totalInterruptsCounter + 1
               theDiff = newTime - Globals.oldTime

               if Globals.INTERRUPTCOUNTER <= 5 and zeroCount == 0 and totalInterruptsCounter <= 10:
                   client.publish('test/message', 'esp32_flow Started Spooling to Influxdb at ' + str(easyTime()))
                   utime.sleep(0.5)
                   add_task("0 0 " + str(tStamper()-1))
                   print('###   First ZERO')
                   zeroCount = 1

               if theDiff != 0:
                   flowRate = round(((1000 / theDiff) * Globals.INTERRUPTCOUNTER)/Globals.calibrationFactor, 2)

               if printTime - oldPrintTime >= 2000.0:
                   flowMils = round((flowRate/60), 2)
                   toteMils += flowMils
                   fRate = str(round((flowRate/60)*1000, 2))
                   atTime = tStamper()
                   #print("Amount is: ", toteMils, "L, at:", atTime)
                   #print("Flowrate =", fRate + "ml/sec")
                   Globals.lperSec = flowRate
                   oldPrintTime = printTime

                   try:
                       add_task(str(fRate) + " " + str(toteMils) + " " + str(atTime))
                   except Exception as e:
                       print('Error: {}'.format(e))

               Globals.oldTime = newTime
               Globals.INTERRUPTCOUNTER = 0

           if Globals.INTERRUPTCOUNTER == 0 and newTime - Globals.oldTime >= 10000:
               totalInterruptsCounter = 0
               Globals.oldTime = newTime

           #theCollection = theCollection + 1
           #if  theCollection >= 120:
               #gc.collect()
               #myMem = gc.mem_free()
               #print(myMem)
               #theCollection = 0


           if Globals.INTERRUPTCOUNTER == 0 and newTime - oldPrintTime >= 10000 and zeroCount == 1:
               Globals.allTimeLiters = Globals.allTimeLiters + toteMils
               add_task(str(flowRate) + " " + str(toteMils) + " " + str(tStamper()))
               add_task("0 0 " + str(tStamper() + 1))
               print('Last ZERO   ###')
               toteMils = 0
               zeroCount = 0
               flowRate = 0
               #myDir = uos.listdir('/sd/')
               Globals.numFlows = Globals.numFlows + 1
               client.publish('test/message', 'esp32_flow is Done Spooling to Influxdb at ' + str(easyTime()))
               totalInterruptsCounter = 0

   except KeyboardInterrupt:
       print("CNTRL-C has been invoked")
       threadList = _thread.list(False)

       for i in threadList:
           if "netty" in i[2]:
               toSuspend = i[0]
               _thread.stop(toSuspend)

           if "poppy" in i[2]:
               toSuspend = i[0]
               _thread.stop(toSuspend)
So with the information that upy spits out in the core dump, can I determine which part of the script it gets tripped up on ?
cheers
Brett

EDIT: This is running on an esp32 Cam module, but have tested same code on a esp32 Wroom 32, with same results as described above

EDIT2: Seems I have narrowed it down to urequests(), as soon as it fires in the queueThread, that causes the core dump, after a few seconds/minutes ... if I comment it out, the code will run fine for hours (all I have tested)

Print this item

  RA8876 support in Display module?
Posted by: avanti - 10-15-2019, 05:41 PM - Forum: General - No Replies

I see that Boris once worked with the RA8876 display processor, but I can't find any reference to it in the LoBo Display module. Does anyone have a driver for this device?

Print this item

  xpt2046 no calibration
Posted by: bingy - 10-10-2019, 09:32 PM - Forum: Issues - No Replies

I have been unable to run the calibration of a touch screen, ILI9341 with XPT2046 touch controller.

Screen initialised:
from machine import SPI,Pin
import display
import tpcalib

tft = display.TFT()
tft.init(tft.ILI9341, width=240, height=320, miso=12,mosi=13,clk=14,cs=15,dc=26, rst_pin=27,tcs=25,hastouch=tft.TOUCH_XPT, bgr=True)

def touch_cal():
    tpc = tpcalib.Calibrate(tft)
    #dosave = True
    tp_type = tft.TOUCH_XPT
    tpc.tpcalib(tp_type)

on calling touch_cal() the screen is displayed, but is unresponsive to touch.
note: tpc.tpcalib(tt_type,dosave) gives 2 errors should be tp_type and only 1 variable required

I have tested the touch functioality using a driver derived from : http://www.ars-informatica.ca/eclectic/x...libration/
.

Any help appreciated

Print this item

  Move ESP32 Camera Project to MicroPython - Webserver, Camera, Overlay
Posted by: xgarb - 09-09-2019, 05:11 PM - Forum: General - Replies (2)

I’m working on an ESP32 camera project (Arduino IDE) that I would like bring over to a K210 based board for performance reasons.

Here’s a quick video demo of what I have at the moment: https://youtu.be/232PdOVPyPg

At the moment I have a web page hosted on the ESP32. Commands and the video stream are over websockets. The cursor overlay uses the IDF gfx library.

How much of this is possible with the current MP port for the K210? I have a Sipeed M1 and the Maixduino.

Print this item

  Using the Maixduino TFT Display
Posted by: baqwas - 09-05-2019, 03:46 AM - Forum: Hardware - Replies (5)

Hello!

The Grove version of the Maixduino board bundles a 2.4" TFT display (& a camera). I am familiar with these TFT displays being driven through Arduino code. Is there any equivalent MicroPython library module for this purpose?

Thanks.

Print this item

  board reboots with 24bit SPI
Posted by: carl0s - 09-04-2019, 09:33 PM - Forum: Issues - Replies (3)

Hi. On Sipeed Maix Go, I tried to configure SPI with 24bit like so:


Code:
spi = machine.SPI(mosi=28, miso=26, sck=27, cs=29, baudrate=8000000, firstbit=machine.SPI.MSB, bits=24)


then when I try to use it, the REPL hangs, then reboots itself.

Print this item

  ssd1306 heltec wireless-stick oled not work correctly
Posted by: alien1983 - 08-30-2019, 03:56 PM - Forum: Issues - Replies (1)

Hi,
I'm having trouble displaying pixel text on the screen correctly!


Board: https://heltec.org/project/wireless-stick/

System Image: LoBo MicroPython.

Library:
ssd1306.py


# MicroPython SSD1306 OLED driver, I2C and SPI interfaces

import time
import framebuf


# register definitions
SET_CONTRAST        = const(0x81)
SET_ENTIRE_ON       = const(0xa4)
SET_NORM_INV        = const(0xa6)
SET_DISP            = const(0xae)
SET_MEM_ADDR        = const(0x20)
SET_COL_ADDR        = const(0x21)
SET_PAGE_ADDR       = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP       = const(0xa0)
SET_MUX_RATIO       = const(0xa8)
SET_COM_OUT_DIR     = const(0xc0)
SET_DISP_OFFSET     = const(0xd3)
SET_COM_PIN_CFG     = const(0xda)
SET_DISP_CLK_DIV    = const(0xd5)
SET_PRECHARGE       = const(0xd9)
SET_VCOM_DESEL      = const(0xdb)
SET_CHARGE_PUMP     = const(0x8d)


class SSD1306:
    def __init__(self, width, height, external_vcc):
        self.width = width
        self.height = height
        self.external_vcc = external_vcc
        self.pages = self.height // 8
        # Note the subclass must initialize self.framebuf to a framebuffer.
        # This is necessary because the underlying data buffer is different
        # between I2C and SPI implementations (I2C needs an extra byte).
        self.poweron()
        self.init_display()

    def init_display(self):
        for cmd in (
            SET_DISP | 0x00, # off
            # address setting
            SET_MEM_ADDR, 0x00, # horizontal
            # resolution and layout
            SET_DISP_START_LINE | 0x00,
            SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
            SET_MUX_RATIO, self.height - 1,
            SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
            SET_DISP_OFFSET, 0x00,
            SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
            # timing and driving scheme
            SET_DISP_CLK_DIV, 0x80,
            SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
            SET_VCOM_DESEL, 0x30, # 0.83*Vcc
            # display
            SET_CONTRAST, 0xff, # maximum
            SET_ENTIRE_ON, # output follows RAM contents
            SET_NORM_INV, # not inverted
            # charge pump
            SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
            SET_DISP | 0x01): # on
            self.write_cmd(cmd)
        self.fill(0)
        self.show()

    def poweroff(self):
        self.write_cmd(SET_DISP | 0x00)

    def contrast(self, contrast):
        self.write_cmd(SET_CONTRAST)
        self.write_cmd(contrast)

    def invert(self, invert):
        self.write_cmd(SET_NORM_INV | (invert & 1))

    def show(self):
        x0 = 0
        x1 = self.width - 1
        if self.width == 64:
            # displays with width of 64 pixels are shifted by 32
            x0 += 32
            x1 += 32
        self.write_cmd(SET_COL_ADDR)
        self.write_cmd(x0)
        self.write_cmd(x1)
        self.write_cmd(SET_PAGE_ADDR)
        self.write_cmd(0)
        self.write_cmd(self.pages - 1)
        self.write_framebuf()

    def fill(self, col):
        self.framebuf.fill(col)

    def pixel(self, x, y, col):
        self.framebuf.pixel(x, y, col)

    def scroll(self, dx, dy):
        self.framebuf.scroll(dx, dy)

    def text(self, string, x, y, col=1):
        self.framebuf.text(string, x, y, col)


class SSD1306_I2C(SSD1306):
    def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
        self.i2c = i2c
        self.addr = addr
        self.temp = bytearray(2)
        # Add an extra byte to the data buffer to hold an I2C data/command byte
        # to use hardware-compatible I2C transactions.  A memoryview of the
        # buffer is used to mask this byte from the framebuffer operations
        # (without a major memory hit as memoryview doesn't copy to a separate
        # buffer).
        self.buffer = bytearray(((height // 8) * width) + 1)
        self.buffer[0] = 0x40  # Set first byte of data buffer to Co=0, D/C=1
        self.framebuf = framebuf.FrameBuffer1(memoryview(self.buffer)[1:], width, height)
        super().__init__(width, height, external_vcc)

    def write_cmd(self, cmd):
        self.temp[0] = 0x80 # Co=1, D/C#=0
        self.temp[1] = cmd
        self.i2c.writeto(self.addr, self.temp)

    def write_framebuf(self):
        # Blast out the frame buffer using a single I2C transaction to support
        # hardware I2C interfaces.
        self.i2c.writeto(self.addr, self.buffer)

    def poweron(self):
        pass


class SSD1306_SPI(SSD1306):
    def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
        self.rate = 10 * 1024 * 1024
        dc.init(dc.OUT, value=0)
        res.init(res.OUT, value=0)
        cs.init(cs.OUT, value=1)
        self.spi = spi
        self.dc = dc
        self.res = res
        self.cs = cs
        self.buffer = bytearray((height // 8) * width)
        self.framebuf = framebuf.FrameBuffer1(self.buffer, width, height)
        super().__init__(width, height, external_vcc)

    def write_cmd(self, cmd):
        self.spi.init(baudrate=self.rate, polarity=0, phase=0)
        self.cs.high()
        self.dc.low()
        self.cs.low()
        self.spi.write(bytearray([cmd]))
        self.cs.high()

    def write_framebuf(self):
        self.spi.init(baudrate=self.rate, polarity=0, phase=0)
        self.cs.high()
        self.dc.high()
        self.cs.low()
        self.spi.write(self.buffer)
        self.cs.high()

    def poweron(self):
        self.res.high()
        time.sleep_ms(1)
        self.res.low()
        time.sleep_ms(10)
        self.res.high()





ssd1306_i2c_example.py

import machine
from ssd1306 import SSD1306_I2C

#PG MOD
testPin = machine.Pin(16, machine.Pin.OUT)
testPin.value(1) #VEXT ON

WIDTH = const(128)
HEIGHT = const (64)
sda_pin = machine.Pin(4)
scl_pin = machine.Pin(15)

i2c = machine.I2C(scl=scl_pin, sda=sda_pin, speed=400000)

ssd = SSD1306_I2C(WIDTH, HEIGHT, i2c)

import freesans20

from writer import Writer
wri2 = Writer(ssd, freesans20, verbose=True)

Writer.set_clip(True, True)
Writer.set_textpos(0, 0)
wri2.printstring('MicroPython\nby LoBo\n10/2017')

ssd.show()
ssd.pixel(1,1,1)
ssd.pixel(2,2,1)
ssd.pixel(3,3,1)
ssd.pixel(4,4,1)
ssd.pixel(5,5,1)
ssd.pixel(6,6,1)
ssd.pixel(7,7,1)
ssd.pixel(8,8,1)
ssd.pixel(9,9,1)
ssd.pixel(10,10,1)
ssd.pixel(11,11,1)
ssd.pixel(12,12,1)
ssd.pixel(30,30,1)
ssd.show()

Most pixels do not display!
Text do not display correctly,
most are out of the screen.

New settings with :

WIDTH = const(64)
HEIGHT = const (32)

Setting to the real display value (64x32) also does not work correctly! :/

Print this item

  Sparkfun Battery Babysitter I2C
Posted by: BoredBSEE - 08-28-2019, 07:29 PM - Forum: MicroPython - Replies (3)

I've been trying to talk to Sparkfun's wonderful Battery Babysitter today.

The chip on board is the BQ27441-G1, over I2C.  There is a fairly simple Arduino library I've been using for inspiration, here.


I have the hardware set up correctly, I believe.  I'm able to do this:


Code:
MicroPython ESP32_LoBo_v3.2.24 - 2018-09-06 on ESP32 board with ESP32
Type "help()" for more information.
>>> import machine
>>> m = machine.I2C(0, sda=21, scl=22, speed=100000)
>>> m.scan()
[85]
>>> m.is_ready(85)
True
>>>

85 is what you'd expect, from the Arduino stuff:

Code:
#define BQ72441_I2C_ADDRESS 0x55 // Default I2C address of the BQ27441-G1A

85 == 0x55, so apparently we're talking pretty well.  Everybody seems happy so far.

I'm trying to read something simple to start, the SOH (state of health).  It should be a number around 90 or so, a % of battery health.  Here's the Arduino code that makes that happen:

Code:
#define BQ27441_COMMAND_SOH                0x20 // StateOfHealth()

...

// Reads and returns specified state of health measurement
uint8_t BQ27441::soh(soh_measure type)
{
    uint16_t sohRaw = readWord(BQ27441_COMMAND_SOH);
    uint8_t sohStatus = sohRaw >> 8;
    uint8_t sohPercent = sohRaw & 0x00FF;
    
    if (type == PERCENT)    
        return sohPercent;
    else
        return sohStatus;
}

...readWord() is a 16 bit int wrapper around i2cReadBytes() ...

// Read a 16-bit command word from the BQ27441-G1A
uint16_t BQ27441::readWord(uint16_t subAddress)
{
    uint8_t data[2];
    i2cReadBytes(subAddress, data, 2);
    return ((uint16_t) data[1] << 8) | data[0];
}

... i2cReadBytes() does the work...

// Read a specified number of bytes over I2C at a given subAddress
int16_t BQ27441::i2cReadBytes(uint8_t subAddress, uint8_t * dest, uint8_t count)
{
    int16_t timeout = BQ72441_I2C_TIMEOUT;    
    Wire.beginTransmission(_deviceAddress);
    Wire.write(subAddress);
    Wire.endTransmission(true);
    
    Wire.requestFrom(_deviceAddress, count);
    
    for (int i=0; i<count; i++)
    {
        dest[i] = Wire.read();
    }
    
    return timeout;
}

To me, this all looks like you should do this:


Code:
m.is_ready(85)
b = bytearray([32])
m.writeto(85,b)
r = m.readfrom(85,2)

That seems like it should do the trick.  But it fails:


Code:
>>> b = bytearray([32])
>>> m.writeto(85,b);r=readfrom(85,2)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
OSError: I2C bus error (263)
>>>

Any ideas what I'm getting wrong?  Thanks.   Smile

Print this item

  Hello World FAQ
Posted by: baqwas - 08-22-2019, 03:23 PM - Forum: MicroPython - No Replies

Hello,

I am embarking on the MicroPython excursion with newbie steps. May I ask for a link to some Hello World exercises for an absolute beginner in MicroPython who hasn't completed flashing his firmware as yet but wants to get his ducks in a row to start the adventure. Perhaps, I didn't search properly, trust you won't mind and oblige.

Kind regards.

P.S. My nominal browsing/search didn't reveal links. I can do Hello World in Python! Big Grin

Print this item

  Micropython and c on separate cores
Posted by: madgrizzlemaslow - 08-03-2019, 10:56 PM - Forum: General - No Replies

I have two applications, one written in Python and the other in C and am interested in knowing if they can both be run on an esp32, each app running in its own core.  I saw something about pinning the micropython to a task on a particular core.  Is something like this feasible?

Print this item