CLI Command line interface with and threads

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
kjk25
Posts: 2
Joined: Sun Sep 12, 2021 6:52 pm

CLI Command line interface with and threads

Post by kjk25 » Sat Sep 25, 2021 6:49 pm

Hi hope someone can help,

I try to get a cli interface over USB like the MP prompt >>> in my programm to enter in commands from CLI
the principe is simple call input() and wait for the command and execute it. so i can remote controll the device.
>here the command

but: all other threads slow down i guess, not 100% sure but a motor thread for a stepper slow down and the motor turn verry slow.
I use a ESP32 Lolin32 V1.0.0 with tmc2209 stepper driver

the code is shorted to make it more readable
hope someone can help.

Code: Select all

# HW init ESP32
# LOLIN32 Wemos V1.0.0.

import micropython
import sys
import _thread
import time
from time import sleep
import machine
from machine import Pin
from machine import ADC
micropython.alloc_emergency_exception_buf(100)
from tmc.TMC_2209_StepperDriver import *
from statemachine import stepper_statemachine

debug = "position" # position, state, adc
#------------------------------------------------------------
# variables
movespeed = 500    #stepper move speed
parkposition= 600     #park position nach grinding ende

#------------------------------------------------------------
# Boot, following pins influence the serial bootloader mode
# https://github.com/espressif/esptool/wiki/ESP32-Boot-Mode-Selection
#12 (MTDI)
#15 (MTDO)
#GPIO0
#GPIO2

#------------------------------------------------------------
# HW init
led = Pin(5, Pin.OUT)
adc = ADC(Pin(36))          # create ADC object on ADC pin
endstop_i = 13
#------------------------------------------------------------
# HW inputs
endstop_in = machine.Pin(endstop_i, machine.Pin.IN, machine.Pin.PULL_UP)

#------------------------------------------------------------
# # Stepper
stepper = -1
tmc = TMC_2209(27, 14, 26)
tmc.setLoglevel(Loglevel.none)
tmc.setMovementAbsRel(MovementAbsRel.relative)
tmc.setDirection_reg(False)
tmc.setVSense(True)
tmc.setCurrent(200)
tmc.setIScaleAnalog(True)
tmc.setInterpolation(True)
tmc.setSpreadCycle(False)
tmc.setMicrosteppingResolution(2)
tmc.setInternalRSense(False)
tmc.setAcceleration(2000)
tmc.setMaxSpeed(movespeed)

#------------------------------------------------------------
# interrupt inputs
def callback(pin):
    if (pin == start_in):
        stepper.on_event('grind')  
    elif (pin == stop_in):
        if not (str(stepper.state) == "MoveHomeState"): 
            tmc.stop()
        stepper.on_event('move_home')  
    elif (pin == endstop_in):
        tmc.stop()
    else:
        pass
      
endstop_in.irq(trigger=machine.Pin.IRQ_FALLING, handler=callback)
    
kill_threads = False

# command cli 
class PythonSwitch:
    def cmd(self, command): 
        default = "Incorrect command, h for Help"
        return getattr(self, 'case_' + str(command), lambda: print(default))() 
    def case_h(self): 
        return help()
    def case_exit(self):
        global kill_threads        
        kill_threads = True
my_cmd = PythonSwitch()    

def help():
    print("commands:")
    print("h     - help")
    print("exit  - exit programm to python")
        
def ledThread():
    global kill_threads, stepper
    while True:
        if kill_threads:
            print("exit ledThread") 
            _thread.exit()
        try:
            led.value(not led.value())
            sleep(1)
        except OSError as e:
            pass      
        
def communicationThread():
    global kill_threads
    while True:
        if kill_threads:
            print("exit communicationThread") 
            _thread.exit()         
        try:
            var = input(">")
            my_cmd.cmd(var)
            sleep(0.2)
        except:
            pass 

def adcThread():
    global kill_threads, adc, adc_val, stepper   
    while True:
        if kill_threads:
            print("exit adcThread") 
            _thread.exit()         
        try:
            adc_val = adc.read() * 3.3 / 4095      # reading analog pin
            print("adc:", adc_val)
            sleep(0.1)
        except OSError as e:
            print("error ADC", e)
            pass

def mainThread():
    global kill_threads, event, tmc, stepper
    state_tmp = -1
    while True:
        if kill_threads:
            print("exit mainThread") 
            _thread.exit()
        try:
            if not (state_tmp == str(stepper.state)):
                state_tmp = str(stepper.state)
                if(str(stepper.state) == "FinishState"):
                    finish()
                elif(str(stepper.state) == "MoveHomeState"):
                    move_home()
                elif(str(stepper.state) == "ErrorState"):
                    error()
                sleep(0.2)
        except OSError as e:
            pass
    
def main():
    global kill_threads, stepper
    if not stop_in.value():
        print("kill_threads")
        kill_threads = True
    stepper = stepper_statemachine()
    # start threads
    _thread.start_new_thread(ledThread, ())
    _thread.start_new_thread(adcThread, ())    
    _thread.start_new_thread(communicationThread, ())
    _thread.start_new_thread(mainThread, ())

    while True:
        if kill_threads:
            sleep(2)
            stop()
            print("poweroff")
            sys.exit()
        sleep(1.2)

if __name__=="main__":
    main()
main()
best wiches Kai

Post Reply