Compare commits
37 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
f2dc43d7cd | ||
|
7acb5c213a | ||
|
4112d8653c | ||
|
84c88e8f02 | ||
|
c049da3583 | ||
|
1d0ea6a5aa | ||
|
d08b629a0f | ||
|
5cf4b31ff0 | ||
|
2ee07d677c | ||
|
530536f9a3 | ||
|
9dfca6f6c3 | ||
|
1dd8388769 | ||
|
cfd2458599 | ||
|
4aab1e1343 | ||
|
4c149a7743 | ||
|
e65350f643 | ||
|
989f9cce13 | ||
|
c42f5d5d7a | ||
|
59707b5cf4 | ||
|
e2749cf2b9 | ||
|
d206b53194 | ||
|
f8b9e6c862 | ||
|
17d8db2193 | ||
|
9cae5cf75d | ||
|
a22c60b817 | ||
|
7eab4f8a8e | ||
|
3488281502 | ||
|
e8e1070bd1 | ||
|
63f0da25f1 | ||
|
c99e71846c | ||
|
61deaf9ead | ||
|
b6a7ee65ed | ||
|
1e2fa1db8f | ||
|
7bde75806c | ||
|
1d53d3467c | ||
|
0ede3dbfa8 | ||
|
a89d3a1f8c |
14
.gitignore
vendored
14
.gitignore
vendored
@ -1,15 +1,29 @@
|
||||
# ESP-IDF default build directory
|
||||
build
|
||||
sdkconfig.old
|
||||
dependencies.lock
|
||||
|
||||
# VIM files
|
||||
*.swp
|
||||
*.swo
|
||||
**/.cache
|
||||
|
||||
# VS-code
|
||||
settings.json
|
||||
|
||||
# drawio files
|
||||
*.bkp
|
||||
|
||||
# freecad backup files
|
||||
*.FCStd1
|
||||
*.FCBak
|
||||
# stl files are usually temporary
|
||||
*.stl
|
||||
|
||||
# kicad backup files
|
||||
pcb/*/*backups/
|
||||
|
||||
# other
|
||||
octave-workspace
|
||||
del
|
||||
screenshots
|
||||
|
@ -6,4 +6,4 @@ cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
#set(EXTRA_COMPONENT_DIRS ../esp-idf-lib/components)
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(cable-length-cutting)
|
||||
project(cable-length-cutter)
|
||||
|
84
README.md
84
README.md
@ -1,10 +1,42 @@
|
||||
# Hardware
|
||||
## connection plan
|
||||
See [connection-plan.pdf](connection-plan.pdf)
|
||||
# Overview
|
||||
Firmware and documentation of a custom built machine that winds and cuts cable to certain lengths.
|
||||
Extensive details about this project can be found on the website: [pfusch.zone/cable-length-cutter](https://pfusch.zone/cable-length-cutter)
|
||||
|
||||
<img src="img/cable-length-cutter.jpg" alt="Photo machine" style="width:60%;">
|
||||
|
||||
Photo of the built machine
|
||||
|
||||
## Current Features
|
||||
- Measure length using rotary encoder
|
||||
- Wind to set length while start-button is pressed
|
||||
- Automatic wire cutter
|
||||
- Control interface:
|
||||
- 2x 7-Segment display showing lengths and notifications
|
||||
- Buzzer for acoustic notifications
|
||||
- 4 Buttons and Potentiometer for setting the target length
|
||||
- Reset and Cut Button
|
||||
- Stepper motor controlling a linear axis guiding the cable while winding
|
||||
- Store last axis position at shutdown
|
||||
|
||||
|
||||
# Usage
|
||||

|
||||
|
||||
|
||||
# Electrical Details
|
||||
For detailed documentation of all electrical aspects, see [connection-plan.pdf](connection-plan.pdf).
|
||||
|
||||
|
||||
# Printed Parts
|
||||
All designed and 3D-printed parts can be found in the [cad/](cad/) folder. These parts were designed using FreeCAD.
|
||||
|
||||
|
||||
# Components
|
||||
## rotary encoder LPD3806-600BM-G5-24C
|
||||
### Custom pcb with ESP-32 microcontroller
|
||||
See [connection-plan.pdf](connection-plan.pdf)
|
||||
|
||||
### Rotary encoder LPD3806-600BM-G5-24C
|
||||
```
|
||||
- Pulses: 600 p/r (Single-phase 600 pulses /R,Two phase 4 frequency doubling to 2400 pulses)
|
||||
- Power source: DC5-24V
|
||||
- Shaft: 6*13mm/0.23*0.51"
|
||||
@ -15,4 +47,48 @@ See [connection-plan.pdf](connection-plan.pdf)
|
||||
- Cable length: 1.5 meter
|
||||
- size: http://domoticx.com/wp-content/uploads/2020/05/LPD3806-afmetingen.jpg
|
||||
- Wires: Green = A phase, white = B phase, red = Vcc power +, black = V0
|
||||
```
|
||||
### Variable Frequency Drive T13-400W-12-H
|
||||
See [docs/vfd/](docs/vfd/)
|
||||
|
||||
### Stepper-driver TB6600
|
||||
See [docs/stepper-driver_TB6600-Manual.pdf](docs/stepper-driver_TB6600-Manual.pdf)
|
||||
|
||||
### Linear Axis with Nema-12 28HB40 Stepper
|
||||
See [connection-plan.pdf](connection-plan.pdf)
|
||||
|
||||
|
||||
|
||||
|
||||
# Installation
|
||||
For this project **ESP-IDF v4.4.4** is required (with other versions it might not compile)
|
||||
```bash
|
||||
#download esp-idf
|
||||
yay -S esp-idf
|
||||
#alternatively clone the esp-idf repository from github and do `git checkout release/4.4`
|
||||
|
||||
#run installation script in installed folder
|
||||
/opt/esp-idf/install.sh
|
||||
```
|
||||
|
||||
# Build
|
||||
### Set up environment
|
||||
```bash
|
||||
source /opt/esp-idf/export.sh
|
||||
```
|
||||
(run once per terminal)
|
||||
|
||||
### Compile
|
||||
```bash
|
||||
cd board_single
|
||||
idf.py build
|
||||
```
|
||||
|
||||
# Flash
|
||||
- connect FTDI programmer to board (VCC to VCC; TX to RX; RX to TX)
|
||||
- press REST and BOOT button
|
||||
- release RESET button (keep pressing boot)
|
||||
- run flash command:
|
||||
```bash
|
||||
idf.py flash
|
||||
```
|
BIN
cad/assembly_all-parts.FCStd
Normal file
BIN
cad/assembly_all-parts.FCStd
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
cad/reel/cable-reel_v2.2.2.FCStd
Normal file
BIN
cad/reel/cable-reel_v2.2.2.FCStd
Normal file
Binary file not shown.
BIN
cad/reel/cable-reel_v2.2.FCStd
Normal file
BIN
cad/reel/cable-reel_v2.2.FCStd
Normal file
Binary file not shown.
@ -55,9 +55,6 @@ void DendoStepper::init(uint8_t stepP, uint8_t dirP, uint8_t enP, timer_group_t
|
||||
|
||||
void DendoStepper::init()
|
||||
{
|
||||
ESP_LOGW("DendoStepper", "semaphore init");
|
||||
semaphore_isrVariables = xSemaphoreCreateBinary();
|
||||
xSemaphoreGive(semaphore_isrVariables);
|
||||
uint64_t mask = (1ULL << conf.stepPin) | (1ULL << conf.dirPin) | (1ULL << conf.enPin); // put output gpio pins in bitmask
|
||||
gpio_config_t gpio_conf = {
|
||||
// config gpios
|
||||
@ -117,36 +114,39 @@ timer_avail:
|
||||
ESP_ERROR_CHECK(timer_isr_callback_add(conf.timer_group, conf.timer_idx, xISRwrap, this, 0)); // add callback fn to run when alarm is triggrd
|
||||
}
|
||||
|
||||
|
||||
esp_err_t DendoStepper::runPos(int32_t relative)
|
||||
{
|
||||
//TODO only enable when actually moving
|
||||
if (ctrl.status == DISABLED) // if motor is disabled, enable it
|
||||
enableMotor();
|
||||
|
||||
setDir(relative < 0); // set CCW if <0, else set CW
|
||||
|
||||
if (!relative) // why would u call it with 0 wtf
|
||||
return ESP_ERR_NOT_SUPPORTED;
|
||||
|
||||
if (ctrl.status > IDLE) { //currently moving
|
||||
//ctrl.status = ctrl.status==COAST ? COAST : ACC; //stay at coast otherwise switch to ACC
|
||||
ctrl.stepsRemaining = ctrl.stepsToGo - ctrl.stepCnt;
|
||||
calc(abs(relative) + ctrl.stepsRemaining); //calculate new velolcity profile for new+remaining steps
|
||||
ESP_LOGW("DendoStepper", "EXTEND running movement (stepsRemaining: %d + stepsNew: %d - current state: %d)", ctrl.stepsRemaining, abs(relative), (int)ctrl.status);
|
||||
ESP_ERROR_CHECK(timer_set_alarm_value(conf.timer_group, conf.timer_idx, ctrl.stepInterval)); // set HW timer alarm to stepinterval
|
||||
bool newDir = (relative < 0); // CCW if <0, else set CW
|
||||
if (ctrl.dir == newDir){ //current direction is the same
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = ctrl.status==COAST ? COAST : ACC; //stay at coast otherwise switch to ACC
|
||||
calc(abs(relative + ctrl.stepsRemaining)); //calculate new velolcity profile for new+remaining steps
|
||||
} else { //direction has changed
|
||||
//direction change not supported TODO wait for decel finish / queue?
|
||||
STEP_LOGW("DendoStepper", "DIRECTION HOT-CHANGE NOT SUPPORTED - Finising previous move, this command will be ignored");
|
||||
return ESP_ERR_NOT_SUPPORTED;
|
||||
}
|
||||
}
|
||||
|
||||
else { //current state is IDLE
|
||||
//ctrl.statusPrev = ctrl.status; //update previous status
|
||||
calc(abs(relative)); // calculate velocity profile
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = ACC;
|
||||
ESP_ERROR_CHECK(timer_set_alarm_value(conf.timer_group, conf.timer_idx, ctrl.stepInterval)); // set HW timer alarm to stepinterval
|
||||
ESP_ERROR_CHECK(timer_start(conf.timer_group, conf.timer_idx)); // start the timer
|
||||
setDir(relative < 0); // set CCW if <0, else set CW
|
||||
calc(abs(relative)); // calculate velocity profile
|
||||
}
|
||||
|
||||
//printf("runpos end -- steps: %d, status: %d, olddir: %d, newdir: %d\n", relative, ctrl.status, ctrl.dir, newDir);
|
||||
currentPos += relative; //(target position / not actual)
|
||||
ESP_ERROR_CHECK(timer_set_alarm_value(conf.timer_group, conf.timer_idx, ctrl.stepInterval)); // set HW timer alarm to stepinterval
|
||||
//TODO timer has to be stopped before update if already running?
|
||||
ESP_ERROR_CHECK(timer_start(conf.timer_group, conf.timer_idx)); // start the timer
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
@ -159,31 +159,26 @@ esp_err_t DendoStepper::runPosMm(int32_t relative)
|
||||
return runPos(relative * ctrl.stepsPerMm);
|
||||
}
|
||||
|
||||
//customized: if already running and direction is the same immediately pass to runPos
|
||||
esp_err_t DendoStepper::runAbs(uint32_t position)
|
||||
{
|
||||
//exit if nothing to do
|
||||
if (position == currentPos) return 0; //already at position
|
||||
if (getState() > IDLE) // we are already moving, so stop it
|
||||
stop();
|
||||
while (getState() > IDLE)
|
||||
{
|
||||
// waiting for idle, watchdog should take care of inf loop if it occurs
|
||||
vTaskDelay(1);
|
||||
} // shouldnt take long tho
|
||||
|
||||
if (position == currentPos) // we cant go anywhere
|
||||
return 0;
|
||||
|
||||
//calculate steps necessary
|
||||
int32_t relativeSteps = 0;
|
||||
relativeSteps = (int32_t)position - currentPos;
|
||||
|
||||
//wait if direction needs to change
|
||||
if (getState() > IDLE){//already moving
|
||||
bool newDir = (relativeSteps < 0); // CCW if <0, else set CW
|
||||
if (ctrl.dir != newDir){ //direction differs
|
||||
STEP_LOGE("DendoStepper", "DIRECTION HOT-CHANGE NOT SUPPORTED - Waiting for move to finish...");
|
||||
while (getState() > IDLE) vTaskDelay(5); //wait for move to finish
|
||||
}
|
||||
}
|
||||
|
||||
//call runPos with new target position
|
||||
ESP_LOGI("DendoStepper", "Cur: %llu move %d", currentPos, relativeSteps);
|
||||
return runPos(relativeSteps); // run to new position
|
||||
}
|
||||
|
||||
|
||||
esp_err_t DendoStepper::runAbsMm(uint32_t position)
|
||||
{
|
||||
if (ctrl.stepsPerMm == 0)
|
||||
@ -311,7 +306,7 @@ void DendoStepper::stop()
|
||||
}
|
||||
ctrl.runInfinite = false;
|
||||
timer_pause(conf.timer_group, conf.timer_idx); // stop the timer
|
||||
//ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = IDLE;
|
||||
ctrl.stepCnt = 0;
|
||||
gpio_set_level((gpio_num_t)conf.stepPin, 0);
|
||||
@ -338,23 +333,20 @@ bool DendoStepper::xISR()
|
||||
|
||||
ctrl.stepCnt++;
|
||||
|
||||
////CUSTOM: track actual precice current position
|
||||
//if (ctrl.dir) {
|
||||
// ctrl.posActual ++;
|
||||
//} else {
|
||||
// ctrl.posActual --;
|
||||
//}
|
||||
|
||||
//CUSTOM: track actual precice current position
|
||||
if (ctrl.dir) {
|
||||
ctrl.posActual ++;
|
||||
} else {
|
||||
ctrl.posActual --;
|
||||
}
|
||||
//CUSTOM: track remaining steps for eventually resuming
|
||||
//xSemaphoreTake(semaphore_isrVariables, portMAX_DELAY);
|
||||
//ctrl.stepsRemaining = ctrl.stepCnt - ctrl.stepCnt;
|
||||
//xSemaphoreGive(semaphore_isrVariables);
|
||||
ctrl.stepsRemaining = ctrl.stepCnt - ctrl.stepCnt;
|
||||
|
||||
// we are done
|
||||
if (ctrl.stepsToGo == ctrl.stepCnt && !ctrl.runInfinite)
|
||||
{
|
||||
timer_pause(conf.timer_group, conf.timer_idx); // stop the timer
|
||||
//ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = IDLE;
|
||||
ctrl.stepCnt = 0;
|
||||
return 0;
|
||||
@ -363,19 +355,19 @@ bool DendoStepper::xISR()
|
||||
if (ctrl.stepCnt > 0 && ctrl.stepCnt < ctrl.accEnd)
|
||||
{ // we are accelerating
|
||||
ctrl.currentSpeed += ctrl.accInc;
|
||||
//ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = ACC; // we are accelerating, note that*/
|
||||
}
|
||||
else if (ctrl.stepCnt > ctrl.coastEnd && !ctrl.runInfinite)
|
||||
{ // we must be deccelerating then
|
||||
ctrl.currentSpeed -= ctrl.decInc;
|
||||
//ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = DEC; // we are deccelerating
|
||||
}
|
||||
else
|
||||
{
|
||||
ctrl.currentSpeed = ctrl.targetSpeed;
|
||||
//ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = COAST; // we are coasting
|
||||
}
|
||||
|
||||
@ -383,38 +375,25 @@ bool DendoStepper::xISR()
|
||||
// set alarm to calculated interval and disable pin
|
||||
GPIO.out_w1tc = (1ULL << conf.stepPin);
|
||||
timer_set_alarm_value(conf.timer_group, conf.timer_idx, ctrl.stepInterval);
|
||||
ctrl.stepCnt++;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void DendoStepper::calc(uint32_t targetSteps)
|
||||
{
|
||||
//only set initial speed if IDLE
|
||||
if(ctrl.status == 1){
|
||||
ctrl.currentSpeed = 0;
|
||||
ESP_LOGD("DendoStepper", "calc-start: reset speed to 0 (start from idle) %lf\n", ctrl.currentSpeed);
|
||||
}
|
||||
else{
|
||||
ESP_LOGD("DendoStepper", "calc start: NOT resetting speed (extend from ACC/DEC/COAST): %lf\n", ctrl.currentSpeed);
|
||||
}
|
||||
//CUSTOM reset counter if already moving
|
||||
ctrl.stepCnt = 0; //FIXME bugs when set 0 while ISR reads/runs? mutex
|
||||
|
||||
//steps from ctrl.speed -> 0:
|
||||
ctrl.decSteps = 0.5 * ctrl.dec * (ctrl.speed / ctrl.dec) * (ctrl.speed / ctrl.dec);
|
||||
ESP_LOGD("DendoStepper", "decSteps: %d currspeed: %lf, ctrlSpeed: %lf\n", ctrl.decSteps, ctrl.currentSpeed, ctrl.speed);
|
||||
//steps from 0 -> ctrl.speed:
|
||||
//ctrl.accSteps = 0.5 * ctrl.acc * (ctrl.speed / ctrl.acc) * (ctrl.speed / ctrl.acc);
|
||||
//steps from ctrl.currentSpeed -> ctrl.speed:
|
||||
ctrl.accSteps = 0.5 * ctrl.acc * (ctrl.speed / ctrl.acc) * (ctrl.speed / ctrl.acc) * (ctrl.speed - ctrl.currentSpeed) / ctrl.speed;
|
||||
ESP_LOGD("DendoStepper", "accSteps: %d currspeed: %lf, ctrlSpeed: %lf\n", ctrl.accSteps, ctrl.currentSpeed, ctrl.speed);
|
||||
|
||||
if (targetSteps < (ctrl.decSteps + ctrl.accSteps))
|
||||
{
|
||||
ESP_LOGI("Dendostepper", "Computing new speed");
|
||||
|
||||
ctrl.speed = sqrt(2 * targetSteps * ((ctrl.dec * ctrl.acc) / (ctrl.dec + ctrl.acc)));
|
||||
//ctrl.accSteps = 0.5 * ctrl.acc * (ctrl.speed / ctrl.acc) * (ctrl.speed / ctrl.acc);
|
||||
ctrl.accSteps = 0.5 * ctrl.acc * (ctrl.speed / ctrl.acc) * (ctrl.speed / ctrl.acc) * (ctrl.speed - ctrl.currentSpeed) / ctrl.speed;
|
||||
ctrl.accSteps = 0.5 * ctrl.acc * (ctrl.speed / ctrl.acc) * (ctrl.speed / ctrl.acc);
|
||||
ctrl.decSteps = 0.5 * ctrl.dec * (ctrl.speed / ctrl.dec) * (ctrl.speed / ctrl.dec);
|
||||
}
|
||||
|
||||
@ -422,27 +401,13 @@ void DendoStepper::calc(uint32_t targetSteps)
|
||||
ctrl.coastEnd = targetSteps - ctrl.decSteps;
|
||||
ctrl.targetSpeed = ctrl.speed;
|
||||
|
||||
ctrl.accInc = (ctrl.targetSpeed - ctrl.currentSpeed) / (double)ctrl.accSteps;
|
||||
ctrl.accInc = ctrl.targetSpeed / (double)ctrl.accSteps;
|
||||
ctrl.decInc = ctrl.targetSpeed / (double)ctrl.decSteps;
|
||||
|
||||
//only set initial speed if IDLE
|
||||
if(ctrl.status == 1){
|
||||
ctrl.currentSpeed = ctrl.accInc;
|
||||
ESP_LOGD("DendoStepper", "`reset curr speeed to accinc: %lf\n", ctrl.currentSpeed);
|
||||
ESP_LOGD("DendoStepper", "status=%d setting speed to initial value: %lf\n",ctrl.status, ctrl.currentSpeed);
|
||||
}
|
||||
else{
|
||||
ESP_LOGD("DendoStepper", "status=%d NOT resetting speed to initial value %lf\n",ctrl.status, ctrl.currentSpeed);
|
||||
}
|
||||
|
||||
ctrl.stepInterval = TIMER_F / ctrl.currentSpeed;
|
||||
ctrl.stepsToGo = targetSteps;
|
||||
|
||||
//debug log output
|
||||
ESP_LOGD("DendoStepper", "accSteps: %d, accInc: %lf, decSteps: %d, decInc: %lf",
|
||||
ctrl.accSteps, ctrl.accInc, ctrl.decSteps, ctrl.decInc);
|
||||
ESP_LOGD("DendoStepper", "speedNow=%.1f, speedTarget=%.1f, accEnd=%d, coastEnd=%d, accSteps=%d, accInc=%.3f\n",
|
||||
ctrl.currentSpeed, ctrl.targetSpeed, ctrl.accEnd, ctrl.coastEnd, ctrl.accSteps, ctrl.accInc);
|
||||
ESP_LOGD("DendoStepper", "acc end:%u coastend:%u stepstogo:%u speed:%f acc:%f int: %u",
|
||||
ctrl.accEnd, ctrl.coastEnd, ctrl.stepsToGo, ctrl.speed, ctrl.acc, ctrl.stepInterval);
|
||||
STEP_LOGI("calc", "acc end:%u coastend:%u stepstogo:%u speed:%f acc:%f int: %u", ctrl.accEnd, ctrl.coastEnd, ctrl.stepsToGo, ctrl.speed, ctrl.acc, ctrl.stepInterval);
|
||||
}
|
||||
|
@ -29,7 +29,6 @@
|
||||
#include "freertos/task.h"
|
||||
#include "esp_timer.h"
|
||||
#include "math.h"
|
||||
#include "freertos/semphr.h"
|
||||
|
||||
//#define STEP_DEBUG
|
||||
|
||||
@ -96,7 +95,7 @@ typedef struct
|
||||
uint32_t accSteps = 0;
|
||||
uint32_t decSteps = 0;
|
||||
int32_t stepsRemaining = 0;
|
||||
//uint64_t posActual = 0; //actual current pos incremented at every step
|
||||
uint64_t posActual = 0; //actual current pos incremented at every step
|
||||
uint8_t statusPrev = DISABLED; //FIXME currently unused
|
||||
uint8_t status = DISABLED;
|
||||
bool dir = CW;
|
||||
@ -112,7 +111,6 @@ private:
|
||||
ctrl_var_t ctrl;
|
||||
esp_timer_handle_t dyingTimer;
|
||||
TaskHandle_t enTask;
|
||||
SemaphoreHandle_t semaphore_isrVariables = NULL;
|
||||
uint64_t currentPos = 0; // absolute position
|
||||
bool timerStarted = 0;
|
||||
|
||||
|
File diff suppressed because one or more lines are too long
Binary file not shown.
BIN
docs/control-board_schematic.pdf
Normal file
BIN
docs/control-board_schematic.pdf
Normal file
Binary file not shown.
BIN
docs/vfd/modbus-test/setfreq.jpg
Normal file
BIN
docs/vfd/modbus-test/setfreq.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 144 KiB |
BIN
docs/vfd/modbus-test/start.jpg
Normal file
BIN
docs/vfd/modbus-test/start.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 128 KiB |
BIN
docs/vfd/modbus-test/stop.jpg
Normal file
BIN
docs/vfd/modbus-test/stop.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 144 KiB |
File diff suppressed because one or more lines are too long
Binary file not shown.
BIN
img/cable-length-cutter.jpg
Normal file
BIN
img/cable-length-cutter.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 546 KiB |
3
img/panel-layout.svg
Normal file
3
img/panel-layout.svg
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 348 KiB |
@ -1,15 +1,20 @@
|
||||
idf_component_register(
|
||||
SRCS
|
||||
"main.cpp"
|
||||
"config.cpp"
|
||||
"global.cpp"
|
||||
"control.cpp"
|
||||
"buzzer.cpp"
|
||||
"vfd.cpp"
|
||||
"display.cpp"
|
||||
"cutter.cpp"
|
||||
"switchesAnalog.cpp"
|
||||
"stepper.cpp"
|
||||
"guide-stepper.cpp"
|
||||
"encoder.cpp"
|
||||
"shutdown.cpp"
|
||||
INCLUDE_DIRS
|
||||
"."
|
||||
)
|
||||
|
||||
# colored build output (errors, warnings...)
|
||||
idf_build_set_property(COMPILE_OPTIONS "-fdiagnostics-color=always" APPEND)
|
@ -1,5 +1,5 @@
|
||||
#include "buzzer.hpp"
|
||||
#include "config.hpp"
|
||||
#include "config.h"
|
||||
|
||||
static const char *TAG_BUZZER = "buzzer";
|
||||
|
||||
|
151
main/config.h
Normal file
151
main/config.h
Normal file
@ -0,0 +1,151 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_idf_version.h"
|
||||
|
||||
//note: global variables and objects were moved to global.hpp
|
||||
|
||||
//===================================
|
||||
//===== define output gpio pins =====
|
||||
//===================================
|
||||
//4x stepper mosfet outputs for VFD
|
||||
#define GPIO_VFD_FWD GPIO_NUM_4 //ST4
|
||||
#define GPIO_VFD_REV GPIO_NUM_5 //mos2
|
||||
#define GPIO_VFD_D0 GPIO_NUM_2 //ST2
|
||||
#define GPIO_VFD_D1 GPIO_NUM_15 //ST1
|
||||
//#define GPIO_VFD_D2 GPIO_NUM_15 //ST1 (D2 only used with 7.5kw vfd)
|
||||
|
||||
#define GPIO_MOS1 GPIO_NUM_18 //mos1 (free) 2022.02.28: pin used for stepper
|
||||
#define GPIO_LAMP GPIO_NUM_0 //mos2 (5) 2022.02.28: lamp disabled, pin used for stepper
|
||||
#define GPIO_RELAY GPIO_NUM_13
|
||||
#define GPIO_BUZZER GPIO_NUM_12
|
||||
|
||||
|
||||
//==================================
|
||||
//==== define analog input pins ====
|
||||
//==================================
|
||||
#define GPIO_POTI GPIO_NUM_36
|
||||
#define ADC_CHANNEL_POTI ADC1_CHANNEL_0
|
||||
#define GPIO_4SW_TO_ANALOG GPIO_NUM_39
|
||||
#define ADC_CHANNEL_4SW_TO_ANALOG ADC1_CHANNEL_3 //gpio 39
|
||||
|
||||
#define ADC_CHANNEL ADC_CHANNEL_0
|
||||
//#define ADC_LOW_VOLTAGE_THRESHOLD 1000 //adc value where shut down is detected (store certain values before power loss)
|
||||
#define GPIO_PIN GPIO_NUM_2
|
||||
|
||||
#define ADC_CHANNEL_SUPPLY_VOLTAGE ADC1_CHANNEL_7//gpio35 onboard supply voltage
|
||||
//ADC1_CHANNEL_0 gpio36
|
||||
//ADC1_CHANNEL_6 gpio_34
|
||||
//ADC1_CHANNEL_3 gpio_39
|
||||
|
||||
|
||||
//=====================================
|
||||
//==== assign switches to objects =====
|
||||
//=====================================
|
||||
//see config.cpp for available evaluated switch objects
|
||||
#define SW_START sw_gpio_26
|
||||
#define SW_RESET sw_gpio_25
|
||||
#define SW_CUTTER_POS sw_gpio_14
|
||||
#define SW_SET sw_gpio_analog_0
|
||||
#define SW_PRESET1 sw_gpio_analog_1
|
||||
#define SW_PRESET2 sw_gpio_analog_2
|
||||
#define SW_PRESET3 sw_gpio_analog_3
|
||||
#define SW_CUT sw_gpio_33
|
||||
#define SW_AUTO_CUT sw_gpio_32
|
||||
//#define ? sw_gpio_34
|
||||
//note: actual objects are created in global.cpp
|
||||
|
||||
|
||||
|
||||
|
||||
//=============================
|
||||
//======= configuration =======
|
||||
//=============================
|
||||
//--------------------------
|
||||
//----- display config -----
|
||||
//--------------------------
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 0, 0)
|
||||
#define HOST HSPI_HOST
|
||||
#else
|
||||
#define HOST SPI2_HOST
|
||||
#endif
|
||||
#define DISPLAY_PIN_NUM_MOSI GPIO_NUM_23
|
||||
#define DISPLAY_PIN_NUM_CLK GPIO_NUM_22
|
||||
#define DISPLAY_PIN_NUM_CS GPIO_NUM_27
|
||||
#define DISPLAY_DELAY 2000
|
||||
#define DISPLAY_BRIGHTNESS 8
|
||||
|
||||
//--------------------------
|
||||
//----- encoder config -----
|
||||
//--------------------------
|
||||
#define ROT_ENC_A_GPIO GPIO_NUM_19
|
||||
#define ROT_ENC_B_GPIO GPIO_NUM_21
|
||||
#define ENABLE_HALF_STEPS false // Set to true to enable tracking of rotary encoder at half step resolution
|
||||
#define FLIP_DIRECTION false // Set to true to reverse the clockwise/counterclockwise sense
|
||||
|
||||
|
||||
|
||||
//--------------------------
|
||||
//----- stepper config -----
|
||||
//--------------------------
|
||||
//enable stepper test mode (dont start control and encoder task)
|
||||
//#define STEPPER_TEST
|
||||
//pins
|
||||
#define STEPPER_STEP_PIN GPIO_NUM_18 //mos1
|
||||
#define STEPPER_DIR_PIN GPIO_NUM_16 //ST3
|
||||
//driver settings
|
||||
#define STEPPER_STEPS_PER_MM (200/2) //steps/mm (steps-per-rot / spindle-slope)
|
||||
#define STEPPER_SPEED_DEFAULT 25 //mm/s
|
||||
#define STEPPER_SPEED_MIN 4 //mm/s - speed threshold at which stepper immediately starts/stops
|
||||
#define STEPPER_ACCEL_INC 3 //steps/s increment per cycle
|
||||
#define STEPPER_DECEL_INC 7 //steps/s decrement per cycle
|
||||
//options affecting movement are currently defined in guide-stepper.cpp
|
||||
|
||||
|
||||
//---------------------------
|
||||
//------- cable guide -------
|
||||
//---------------------------
|
||||
// default axis coordinates the guide changes direction (winding width)
|
||||
#define GUIDE_MIN_MM 0 // TODO add feature so guide stays at zero for some steps (negative MIN_MM?), currently seems appropriate for even winding
|
||||
#define GUIDE_MAX_MM 90 // 95 still to long at max pos - actual reel is 110, but currently guide turned out to stay at max position for too long, due to cable running diagonal from guide to reel
|
||||
|
||||
// tolerance added to last stored position at previous shutdown.
|
||||
// When calibrating at startup the stepper moves for that sum to get track of zero position (ensure crashes into hardware limit for at least some time)
|
||||
#define AUTO_HOME_TRAVEL_ADD_TO_LAST_POS_MM 20
|
||||
#define MAX_TOTAL_AXIS_TRAVEL_MM 103 // max possible travel distance, needed as fallback for auto-home
|
||||
#define LAYER_THICKNESS_MM 5 // height of one cable layer on reel -> increase in radius every layer
|
||||
#define D_CABLE 6 // determines winds per layer / guide speed
|
||||
#define D_REEL 160 // start diameter of empty reel
|
||||
|
||||
// max winding width that can be set using potentiometer (SET+PRESET1 buttons)
|
||||
#define MAX_SELECTABLE_WINDING_WIDTH_MM 100;
|
||||
// max target length that can be selected using potentiometer (SET button)
|
||||
#define MAX_SELECTABLE_LENGTH_POTI_MM 100000
|
||||
|
||||
// calculate new winding width each time target length changes, according to custom thresholds defined in guide-stepper.cpp
|
||||
// if not defined, winding width is always GUIDE_MAX_MM even for short lengths
|
||||
#define DYNAMIC_WINDING_WIDTH_ENABLED
|
||||
|
||||
|
||||
//--------------------------
|
||||
//------ calibration -------
|
||||
//--------------------------
|
||||
//enable mode encoder test for calibration (determine ENCODER_STEPS_PER_METER)
|
||||
//if defined, displays always show length and steps instead of the normal messages
|
||||
//#define ENCODER_TEST
|
||||
//TODO: add way to calibrate without flashing -> enter calibration mode with certain button sequence, enter steps-per-meter with poti, store in nvs
|
||||
|
||||
//steps per meter
|
||||
//this value is determined experimentally while ENCODER_TEST is enabled
|
||||
//#define ENCODER_STEPS_PER_METER 2127 //until 2024.03.13 roll-v3-gummi-86.6mm - d=89.8mm
|
||||
#define ENCODER_STEPS_PER_METER 2118 //2024.03.13 roll-v3-gummi measured 86.5mm
|
||||
|
||||
//millimeters added to target length
|
||||
//to ensure that length does not fall short when spool slightly rotates back after stop
|
||||
#define TARGET_LENGTH_OFFSET 0
|
||||
|
||||
//millimeters lengthNow can be below lengthTarget to still stay in target_reached state
|
||||
#define TARGET_REACHED_TOLERANCE 5
|
||||
|
||||
|
||||
|
||||
|
138
main/config.hpp
138
main/config.hpp
@ -1,138 +0,0 @@
|
||||
#pragma once
|
||||
extern "C" {
|
||||
#include "driver/adc.h"
|
||||
}
|
||||
#include "gpio_evaluateSwitch.hpp"
|
||||
#include "buzzer.hpp"
|
||||
#include "switchesAnalog.hpp"
|
||||
|
||||
|
||||
//===================================
|
||||
//===== define output gpio pins =====
|
||||
//===================================
|
||||
//4x stepper mosfet outputs for VFD
|
||||
#define GPIO_VFD_FWD GPIO_NUM_4 //ST4
|
||||
#define GPIO_VFD_REV GPIO_NUM_5 //mos2
|
||||
#define GPIO_VFD_D0 GPIO_NUM_2 //ST2
|
||||
#define GPIO_VFD_D1 GPIO_NUM_15 //ST1
|
||||
//#define GPIO_VFD_D2 GPIO_NUM_15 //ST1 (D2 only used with 7.5kw vfd)
|
||||
|
||||
#define GPIO_MOS1 GPIO_NUM_18 //mos1 (free) 2022.02.28: pin used for stepper
|
||||
#define GPIO_LAMP GPIO_NUM_0 //mos2 (5) 2022.02.28: lamp disabled, pin used for stepper
|
||||
#define GPIO_RELAY GPIO_NUM_13
|
||||
#define GPIO_BUZZER GPIO_NUM_12
|
||||
|
||||
|
||||
//==================================
|
||||
//==== define analog input pins ====
|
||||
//==================================
|
||||
#define GPIO_POTI GPIO_NUM_36
|
||||
#define ADC_CHANNEL_POTI ADC1_CHANNEL_0
|
||||
#define GPIO_4SW_TO_ANALOG GPIO_NUM_39
|
||||
#define ADC_CHANNEL_4SW_TO_ANALOG ADC1_CHANNEL_3 //gpio 39
|
||||
//ADC1_CHANNEL_0 gpio36
|
||||
//ADC1_CHANNEL_6 gpio_34
|
||||
//ADC1_CHANNEL_3 gpio_39
|
||||
|
||||
|
||||
//=====================================
|
||||
//==== assign switches to objects =====
|
||||
//=====================================
|
||||
//see config.cpp for available evaluated switch objects
|
||||
#define SW_START sw_gpio_26
|
||||
#define SW_RESET sw_gpio_25
|
||||
#define SW_CUTTER_POS sw_gpio_14
|
||||
#define SW_SET sw_gpio_analog_0
|
||||
#define SW_PRESET1 sw_gpio_analog_1
|
||||
#define SW_PRESET2 sw_gpio_analog_2
|
||||
#define SW_PRESET3 sw_gpio_analog_3
|
||||
#define SW_CUT sw_gpio_33
|
||||
#define SW_AUTO_CUT sw_gpio_32
|
||||
|
||||
//unused but already available evaluated inputs
|
||||
//#define ? sw_gpio_34
|
||||
|
||||
|
||||
|
||||
|
||||
//=============================
|
||||
//======= configuration =======
|
||||
//=============================
|
||||
//--------------------------
|
||||
//----- display config -----
|
||||
//--------------------------
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 0, 0)
|
||||
#define HOST HSPI_HOST
|
||||
#else
|
||||
#define HOST SPI2_HOST
|
||||
#endif
|
||||
#define DISPLAY_PIN_NUM_MOSI GPIO_NUM_23
|
||||
#define DISPLAY_PIN_NUM_CLK GPIO_NUM_22
|
||||
#define DISPLAY_PIN_NUM_CS GPIO_NUM_27
|
||||
#define DISPLAY_DELAY 2000
|
||||
|
||||
//--------------------------
|
||||
//----- encoder config -----
|
||||
//--------------------------
|
||||
#define ROT_ENC_A_GPIO GPIO_NUM_19
|
||||
#define ROT_ENC_B_GPIO GPIO_NUM_21
|
||||
#define ENABLE_HALF_STEPS false // Set to true to enable tracking of rotary encoder at half step resolution
|
||||
#define FLIP_DIRECTION false // Set to true to reverse the clockwise/counterclockwise sense
|
||||
|
||||
|
||||
|
||||
//--------------------------
|
||||
//----- stepper config -----
|
||||
//--------------------------
|
||||
//enable stepper test mode (dont start control and encoder task)
|
||||
//#define STEPPER_TEST
|
||||
#define STEPPER_STEP_PIN GPIO_NUM_18 //mos1
|
||||
#define STEPPER_DIR_PIN GPIO_NUM_16 //ST3
|
||||
#define STEPPER_EN_PIN GPIO_NUM_0 //not connected (-> stepper always on)
|
||||
//more detailed options for testing are currently defined in guide-stepper.cpp
|
||||
|
||||
|
||||
|
||||
//--------------------------
|
||||
//------ calibration -------
|
||||
//--------------------------
|
||||
//enable mode encoder test for calibration
|
||||
//if defined, displays always show length and steps instead of the normal messages
|
||||
//#define ENCODER_TEST
|
||||
|
||||
//steps per meter
|
||||
#define ENCODER_STEPS_PER_METER 2127 //roll-v3-gummi-86.6mm - d=89.8mm
|
||||
|
||||
//millimetres added to target length
|
||||
//to ensure that length does not fall short when spool slightly rotates back after stop
|
||||
#define TARGET_LENGTH_OFFSET 0
|
||||
|
||||
//millimetres lengthNow can be below lengthTarget to still stay in target_reached state
|
||||
#define TARGET_REACHED_TOLERANCE 5
|
||||
|
||||
|
||||
|
||||
|
||||
//============================
|
||||
//===== global variables =====
|
||||
//============================
|
||||
//create global evaluated switch objects
|
||||
//--- switches on digital gpio pins ---
|
||||
//extern gpio_evaluatedSwitch sw_gpio_39;
|
||||
extern gpio_evaluatedSwitch sw_gpio_34;
|
||||
extern gpio_evaluatedSwitch sw_gpio_32;
|
||||
extern gpio_evaluatedSwitch sw_gpio_33;
|
||||
extern gpio_evaluatedSwitch sw_gpio_25;
|
||||
extern gpio_evaluatedSwitch sw_gpio_26;
|
||||
extern gpio_evaluatedSwitch sw_gpio_14;
|
||||
|
||||
//--- switches connected to 4-sw-to-analog stripboard ---
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_0;
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_1;
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_2;
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_3;
|
||||
|
||||
|
||||
|
||||
//create global buzzer object
|
||||
extern buzzer_t buzzer;
|
244
main/control.cpp
244
main/control.cpp
@ -1,20 +1,47 @@
|
||||
#include "control.hpp"
|
||||
extern "C"
|
||||
{
|
||||
#include <stdio.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <esp_idf_version.h>
|
||||
#include "freertos/queue.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_log.h"
|
||||
#include "driver/adc.h"
|
||||
|
||||
#include "max7219.h"
|
||||
|
||||
}
|
||||
#include <cmath>
|
||||
#include "config.h"
|
||||
#include "gpio_evaluateSwitch.hpp"
|
||||
#include "gpio_adc.hpp"
|
||||
#include "buzzer.hpp"
|
||||
#include "vfd.hpp"
|
||||
#include "display.hpp"
|
||||
#include "cutter.hpp"
|
||||
#include "encoder.hpp"
|
||||
#include "guide-stepper.hpp"
|
||||
#include "global.hpp"
|
||||
#include "control.hpp"
|
||||
|
||||
|
||||
//====================
|
||||
//==== variables =====
|
||||
//====================
|
||||
//-----------------------------------------
|
||||
//--------------- variables ---------------
|
||||
//-----------------------------------------
|
||||
static const char *TAG = "control"; //tag for logging
|
||||
|
||||
//control
|
||||
const char* systemStateStr[7] = {"COUNTING", "WINDING_START", "WINDING", "TARGET_REACHED", "AUTO_CUT_WAITING", "CUTTING", "MANUAL"};
|
||||
systemState_t controlState = systemState_t::COUNTING;
|
||||
static uint32_t timestamp_changedState = 0;
|
||||
static uint32_t timestamp_lastStateChange = 0;
|
||||
|
||||
//display
|
||||
static char buf_disp1[10];// 8 digits + decimal point + \0
|
||||
static char buf_disp2[10];// 8 digits + decimal point + \0
|
||||
static char buf_tmp[15];
|
||||
|
||||
//track length
|
||||
static int lengthNow = 0; //length measured in mm
|
||||
static int lengthTarget = 5000; //default target length in mm
|
||||
static int lengthRemaining = 0; //(target - now) length needed for reaching the target
|
||||
@ -27,8 +54,19 @@ static uint32_t timestamp_cut_lastBeep = 0;
|
||||
static uint32_t autoCut_delayMs = 2500; //TODO add this to config
|
||||
static bool autoCutEnabled = false; //store state of toggle switch (no hotswitch)
|
||||
|
||||
//user interface
|
||||
static uint32_t timestamp_lastWidthSelect = 0;
|
||||
//ignore new set events for that time after last value set using poti
|
||||
#define DEAD_TIME_POTI_SET_VALUE 1000
|
||||
|
||||
|
||||
//-----------------------------------------
|
||||
//--------------- functions ---------------
|
||||
//-----------------------------------------
|
||||
|
||||
//========================
|
||||
//===== change State =====
|
||||
//========================
|
||||
//function for changing the controlState with log output
|
||||
void changeState (systemState_t stateNew) {
|
||||
//only proceed when state actually changed
|
||||
@ -40,18 +78,21 @@ void changeState (systemState_t stateNew) {
|
||||
//change state
|
||||
controlState = stateNew;
|
||||
//update timestamp
|
||||
timestamp_changedState = esp_log_timestamp();
|
||||
timestamp_lastStateChange = esp_log_timestamp();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//=================================
|
||||
//===== handle Stop Condition =====
|
||||
//function that checks whether start button is released or target is reached (used in multiple states)
|
||||
//returns true when stopped, false when no action
|
||||
//=================================
|
||||
//function that checks whether start button is released or target is reached
|
||||
//and takes according action if so (used in multiple states)
|
||||
//returns true when stop condition was met, false when no action required
|
||||
bool handleStopCondition(handledDisplay * displayTop, handledDisplay * displayBot){
|
||||
//--- stop conditions ---
|
||||
//stop conditions that are checked in any mode
|
||||
//target reached
|
||||
//target reached -> reached state, stop motor, display message
|
||||
if (lengthRemaining <= 0 ) {
|
||||
changeState(systemState_t::TARGET_REACHED);
|
||||
vfd_setState(false);
|
||||
@ -60,7 +101,7 @@ bool handleStopCondition(handledDisplay * displayTop, handledDisplay * displayBo
|
||||
buzzer.beep(2, 100, 100);
|
||||
return true;
|
||||
}
|
||||
//start button released
|
||||
//start button released -> idle state, stop motor, display message
|
||||
else if (SW_START.state == false) {
|
||||
changeState(systemState_t::COUNTING);
|
||||
vfd_setState(false);
|
||||
@ -74,8 +115,11 @@ bool handleStopCondition(handledDisplay * displayTop, handledDisplay * displayBo
|
||||
}
|
||||
|
||||
|
||||
|
||||
//===================================
|
||||
//===== set dynamic speed level =====
|
||||
//function that sets the vfd speed level dynamicly depending on the remaining distance
|
||||
//===================================
|
||||
//function that sets the vfd speed level dynamically depending on the remaining distance
|
||||
//closer to target -> slower
|
||||
void setDynSpeedLvl(uint8_t lvlMax = 3){
|
||||
uint8_t lvl;
|
||||
@ -103,31 +147,33 @@ void setDynSpeedLvl(uint8_t lvlMax = 3){
|
||||
//========================
|
||||
//===== control task =====
|
||||
//========================
|
||||
//task that controls the entire machine
|
||||
void task_control(void *pvParameter)
|
||||
{
|
||||
|
||||
//initialize display
|
||||
//-- initialize display --
|
||||
max7219_t two7SegDisplays = display_init();
|
||||
//create two separate handled display instances
|
||||
//create two separate custom handled display instances
|
||||
handledDisplay displayTop(two7SegDisplays, 0);
|
||||
handledDisplay displayBot(two7SegDisplays, 8);
|
||||
|
||||
//--- display welcome msg ---
|
||||
//-- display welcome msg --
|
||||
//display welcome message on two 7 segment displays
|
||||
//currently show name and date and scrolling 'hello'
|
||||
display_ShowWelcomeMsg(two7SegDisplays);
|
||||
|
||||
//-- set initial winding width for default length --
|
||||
guide_setWindingWidth(guide_targetLength2WindingWidth(lengthTarget));
|
||||
|
||||
//================
|
||||
//===== loop =====
|
||||
//================
|
||||
// ##############################
|
||||
// ######## control loop ########
|
||||
// ##############################
|
||||
// repeatedly handle the machine
|
||||
while(1){
|
||||
vTaskDelay(10 / portTICK_PERIOD_MS);
|
||||
|
||||
//-----------------------------
|
||||
|
||||
//------ handle switches ------
|
||||
//-----------------------------
|
||||
//run handle functions for all switches
|
||||
//run handle functions for all switches used here
|
||||
SW_START.handle();
|
||||
SW_RESET.handle();
|
||||
SW_SET.handle();
|
||||
@ -138,27 +184,23 @@ void task_control(void *pvParameter)
|
||||
SW_AUTO_CUT.handle();
|
||||
|
||||
|
||||
//---------------------------
|
||||
//------ handle cutter ------
|
||||
//---------------------------
|
||||
//TODO: separate task for cutter?
|
||||
cutter_handle();
|
||||
|
||||
|
||||
//----------------------------
|
||||
//------ rotary encoder ------
|
||||
//----------------------------
|
||||
//--- get current length since last reset ---
|
||||
//get current length since last reset
|
||||
lengthNow = encoder_getLenMm();
|
||||
|
||||
|
||||
//---------------------------
|
||||
//--------- buttons ---------
|
||||
//---------------------------
|
||||
//--- RESET switch ---
|
||||
//#### RESET switch ####
|
||||
if (SW_RESET.risingEdge) {
|
||||
//dont reset when press used for stopping pending auto-cut
|
||||
if (controlState != systemState_t::AUTO_CUT_WAITING) {
|
||||
encoder_reset();
|
||||
guide_moveToZero(); //move axis guiding the cable to start position
|
||||
encoder_reset(); //reset length measurement
|
||||
lengthNow = 0;
|
||||
buzzer.beep(1, 700, 100);
|
||||
displayTop.blink(2, 100, 100, "1ST ");
|
||||
@ -167,7 +209,7 @@ void task_control(void *pvParameter)
|
||||
}
|
||||
}
|
||||
|
||||
//--- CUT switch ---
|
||||
//### CUT switch ####
|
||||
//start cut cycle immediately
|
||||
if (SW_CUT.risingEdge) {
|
||||
//stop cutter if already running
|
||||
@ -190,7 +232,7 @@ void task_control(void *pvParameter)
|
||||
}
|
||||
}
|
||||
|
||||
//--- AUTO_CUT toggle sw ---
|
||||
//#### AUTO_CUT toggle sw ####
|
||||
//beep at change
|
||||
if (SW_AUTO_CUT.risingEdge) {
|
||||
buzzer.beep(2, 100, 50);
|
||||
@ -209,7 +251,7 @@ void task_control(void *pvParameter)
|
||||
autoCutEnabled = false;
|
||||
}
|
||||
|
||||
//--- manual mode ---
|
||||
//#### manual mode ####
|
||||
//switch to manual motor control (2 buttons + poti)
|
||||
if ( SW_PRESET2.state && (SW_PRESET1.state || SW_PRESET3.state) && controlState != systemState_t::MANUAL ) {
|
||||
//enable manual control
|
||||
@ -217,13 +259,44 @@ void task_control(void *pvParameter)
|
||||
buzzer.beep(3, 100, 60);
|
||||
}
|
||||
|
||||
//--- set custom target length ---
|
||||
//set target length to poti position when SET switch is pressed
|
||||
if (SW_SET.state == true) {
|
||||
//##### SET switch + Potentiometer #####
|
||||
//## set winding-width (SET+PRESET1+POTI) ##
|
||||
// set winding width (axis travel) with poti position
|
||||
// when SET and PRESET1 button are pressed
|
||||
if (SW_SET.state == true && SW_PRESET1.state == true) {
|
||||
timestamp_lastWidthSelect = esp_log_timestamp();
|
||||
//read adc
|
||||
potiRead = gpio_readAdc(ADC_CHANNEL_POTI); //0-4095
|
||||
//scale to target length range
|
||||
int lengthTargetNew = (float)potiRead / 4095 * 50000;
|
||||
uint8_t windingWidthNew = (float)potiRead / 4095 * MAX_SELECTABLE_WINDING_WIDTH_MM;
|
||||
//apply hysteresis and round to whole meters //TODO optimize this
|
||||
if (windingWidthNew % 5 < 2) { //round down if remainder less than 2mm
|
||||
ESP_LOGD(TAG, "Poti input = %d -> rounding down", windingWidthNew);
|
||||
windingWidthNew = (windingWidthNew/5 ) * 5; //round down
|
||||
} else if (windingWidthNew % 5 > 4 ) { //round up if remainder more than 4mm
|
||||
ESP_LOGD(TAG, "Poti input = %d -> rounding up", windingWidthNew);
|
||||
windingWidthNew = (windingWidthNew/5 + 1) * 5; //round up
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Poti input = %d -> hysteresis", windingWidthNew);
|
||||
windingWidthNew = guide_getWindingWidth();
|
||||
}
|
||||
//update target width and beep when effectively changed
|
||||
if (windingWidthNew != guide_getWindingWidth()) {
|
||||
//TODO update at button release only?
|
||||
guide_setWindingWidth(windingWidthNew);
|
||||
ESP_LOGW(TAG, "Changed winding width to %d mm", windingWidthNew);
|
||||
buzzer.beep(1, 30, 10);
|
||||
}
|
||||
}
|
||||
|
||||
//## set target length (SET+POTI) ##
|
||||
//set target length to poti position when only SET button is pressed and certain dead time passed after last setWindingWidth (SET and PRESET1 button) to prevent set target at release
|
||||
// FIXME: when going to edit the winding width (SET+PRESET1) sometimes the target-length also updates when initially pressing SET -> update only at actual poti change (works sometimes)
|
||||
else if (SW_SET.state == true && (esp_log_timestamp() - timestamp_lastWidthSelect > DEAD_TIME_POTI_SET_VALUE)) {
|
||||
//read adc
|
||||
potiRead = gpio_readAdc(ADC_CHANNEL_POTI); //0-4095
|
||||
//scale to target length range
|
||||
int lengthTargetNew = (float)potiRead / 4095 * MAX_SELECTABLE_LENGTH_POTI_MM;
|
||||
//apply hysteresis and round to whole meters //TODO optimize this
|
||||
if (lengthTargetNew % 1000 < 200) { //round down if less than .2 meter
|
||||
ESP_LOGD(TAG, "Poti input = %d -> rounding down", lengthTargetNew);
|
||||
@ -239,6 +312,7 @@ void task_control(void *pvParameter)
|
||||
if (lengthTargetNew != lengthTarget) {
|
||||
//TODO update lengthTarget only at button release?
|
||||
lengthTarget = lengthTargetNew;
|
||||
guide_setWindingWidth(guide_targetLength2WindingWidth(lengthTarget));
|
||||
ESP_LOGI(TAG, "Changed target length to %d mm", lengthTarget);
|
||||
buzzer.beep(1, 25, 10);
|
||||
}
|
||||
@ -253,36 +327,40 @@ void task_control(void *pvParameter)
|
||||
}
|
||||
|
||||
|
||||
//--- target length presets ---
|
||||
if (controlState != systemState_t::MANUAL) { //dont apply preset length while controlling motor with preset buttons
|
||||
//##### target length preset buttons #####
|
||||
if (controlState != systemState_t::MANUAL && SW_SET.state == false) { //dont apply preset length while controlling motor with preset buttons
|
||||
if (SW_PRESET1.risingEdge) {
|
||||
lengthTarget = 5000;
|
||||
guide_setWindingWidth(guide_targetLength2WindingWidth(lengthTarget));
|
||||
buzzer.beep(lengthTarget/1000, 25, 30);
|
||||
displayBot.blink(2, 100, 100, "S0LL ");
|
||||
}
|
||||
else if (SW_PRESET2.risingEdge) {
|
||||
lengthTarget = 10000;
|
||||
guide_setWindingWidth(guide_targetLength2WindingWidth(lengthTarget));
|
||||
buzzer.beep(lengthTarget/1000, 25, 30);
|
||||
displayBot.blink(2, 100, 100, "S0LL ");
|
||||
}
|
||||
else if (SW_PRESET3.risingEdge) {
|
||||
lengthTarget = 15000;
|
||||
guide_setWindingWidth(guide_targetLength2WindingWidth(lengthTarget));
|
||||
buzzer.beep(lengthTarget/1000, 25, 30);
|
||||
displayBot.blink(2, 100, 100, "S0LL ");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//---------------------------
|
||||
//--------- control ---------
|
||||
//---------------------------
|
||||
//calculate length difference
|
||||
//statemachine handling the sequential winding process
|
||||
|
||||
//calculate current length difference
|
||||
lengthRemaining = lengthTarget - lengthNow + TARGET_LENGTH_OFFSET;
|
||||
|
||||
//--- statemachine ---
|
||||
switch (controlState) {
|
||||
case systemState_t::COUNTING: //no motor action
|
||||
case systemState_t::COUNTING: //no motor action, just show current length on display
|
||||
vfd_setState(false);
|
||||
//TODO check stop condition before starting - prevents motor from starting 2 cycles when already at target
|
||||
//--- start winding to length ---
|
||||
@ -298,6 +376,7 @@ void task_control(void *pvParameter)
|
||||
case systemState_t::WINDING_START: //wind slow for certain time
|
||||
//set vfd speed depending on remaining distance
|
||||
setDynSpeedLvl(1); //limit to speed lvl 1 (force slow start)
|
||||
//switch to WINDING state (full speed) when 3s have passed
|
||||
if (esp_log_timestamp() - timestamp_motorStarted > 3000) {
|
||||
changeState(systemState_t::WINDING);
|
||||
}
|
||||
@ -307,23 +386,23 @@ void task_control(void *pvParameter)
|
||||
|
||||
case systemState_t::WINDING: //wind fast, slow down when close
|
||||
//set vfd speed depending on remaining distance
|
||||
setDynSpeedLvl(); //slow down when close to target
|
||||
setDynSpeedLvl(); //set motor speed, slow down when close to target
|
||||
handleStopCondition(&displayTop, &displayBot); //stops if button released or target reached
|
||||
//TODO: cancel when there is no cable movement anymore e.g. empty / timeout?
|
||||
break;
|
||||
|
||||
case systemState_t::TARGET_REACHED:
|
||||
case systemState_t::TARGET_REACHED: //prevent further motor rotation and start auto-cut
|
||||
vfd_setState(false);
|
||||
//switch to counting state when no longer at or above target length
|
||||
if ( lengthNow < lengthTarget - TARGET_REACHED_TOLERANCE ) {
|
||||
changeState(systemState_t::COUNTING);
|
||||
}
|
||||
//switch initiate countdown to auto-cut
|
||||
//initiate countdown to auto-cut if enabled
|
||||
else if ( (autoCutEnabled)
|
||||
&& (esp_log_timestamp() - timestamp_changedState > 300) ) { //wait for dislay msg "reached" to finish
|
||||
&& (esp_log_timestamp() - timestamp_lastStateChange > 300) ) { //wait for dislay msg "reached" to finish
|
||||
changeState(systemState_t::AUTO_CUT_WAITING);
|
||||
}
|
||||
//show msg when trying to start, but target is reached
|
||||
//show msg when trying to start, but target is already reached (-> reset button has to be pressed)
|
||||
if (SW_START.risingEdge) {
|
||||
buzzer.beep(2, 50, 30);
|
||||
displayTop.blink(2, 600, 500, " S0LL ");
|
||||
@ -331,9 +410,8 @@ void task_control(void *pvParameter)
|
||||
}
|
||||
break;
|
||||
|
||||
case systemState_t::AUTO_CUT_WAITING:
|
||||
//handle delayed start of cut
|
||||
cut_msRemaining = autoCut_delayMs - (esp_log_timestamp() - timestamp_changedState);
|
||||
case systemState_t::AUTO_CUT_WAITING: //handle delayed start of cut
|
||||
cut_msRemaining = autoCut_delayMs - (esp_log_timestamp() - timestamp_lastStateChange);
|
||||
//- countdown stop conditions -
|
||||
//stop with any button
|
||||
if (!autoCutEnabled
|
||||
@ -357,13 +435,14 @@ void task_control(void *pvParameter)
|
||||
}
|
||||
break;
|
||||
|
||||
case systemState_t::CUTTING:
|
||||
case systemState_t::CUTTING: //prevent any action while cutter is active
|
||||
//exit when finished cutting
|
||||
if (cutter_isRunning() == false) {
|
||||
//TODO stop if start buttons released?
|
||||
changeState(systemState_t::COUNTING);
|
||||
//TODO reset automatically or wait for manual reset?
|
||||
encoder_reset();
|
||||
guide_moveToZero(); //move axis guiding the cable to start position
|
||||
encoder_reset(); //reset length measurement
|
||||
lengthNow = 0;
|
||||
buzzer.beep(1, 700, 100);
|
||||
}
|
||||
@ -400,30 +479,34 @@ void task_control(void *pvParameter)
|
||||
}
|
||||
|
||||
|
||||
|
||||
#ifdef ENCODER_TEST
|
||||
//--------------------------
|
||||
//------ encoder test ------
|
||||
//--------------------------
|
||||
#ifdef ENCODER_TEST
|
||||
//mode for calibrating the cable length measurement (determine ENCODER_STEPS_PER_METER in config.h)
|
||||
//run display handle functions
|
||||
displayTop.handle();
|
||||
displayBot.handle();
|
||||
//-- show encoder steps on display1 ---
|
||||
sprintf(buf_disp1, "EN %05d", encoder_getSteps); //count
|
||||
sprintf(buf_disp1, "EN %05d", encoder_getSteps()); //count
|
||||
displayTop.showString(buf_disp1);
|
||||
//--- show converted distance on display2 ---
|
||||
sprintf(buf_disp2, "Met %5.3f", (float)lengthNow/1000); //m
|
||||
displayBot.showString(buf_disp2);
|
||||
//--- beep every 1m ---
|
||||
//note: only works precicely in forward/positive direction
|
||||
if (lengthNow % 1000 < 50) { //with tolerance in case of missed exact value
|
||||
if (fabs(lengthNow - lengthBeeped) >= 900) { //dont beep multiple times at same meter
|
||||
//TODO: add case for reverse direction. currently beeps 0.1 too early
|
||||
//--- beep every 0.5m ---
|
||||
//note: only works precisely in forward/positive direction, in reverse it it beeps by tolerance too early
|
||||
static int lengthBeeped = 0;
|
||||
if (lengthNow % 500 < 50) { //with tolerance in case of missed exact value
|
||||
if (fabs(lengthNow - lengthBeeped) >= 400) { //dont beep multiple times at same distance
|
||||
//TODO: add case for reverse direction. currently beeps 50mm too early
|
||||
if (lengthNow % 1000 < 50) // 1m beep
|
||||
buzzer.beep(1, 400, 100);
|
||||
else // 0.5m beep
|
||||
buzzer.beep(1, 200, 100);
|
||||
lengthBeeped = lengthNow;
|
||||
}
|
||||
}
|
||||
#else
|
||||
#else //not in encoder calibration mode
|
||||
|
||||
//--------------------------
|
||||
//-------- display1 --------
|
||||
@ -434,6 +517,10 @@ void task_control(void *pvParameter)
|
||||
if (controlState == systemState_t::AUTO_CUT_WAITING) {
|
||||
displayTop.blinkStrings(" CUT 1N ", " ", 70, 30);
|
||||
}
|
||||
//setting winding width: blink info message
|
||||
else if (SW_SET.state && SW_PRESET1.state){
|
||||
displayTop.blinkStrings("SET WIND", " WIDTH ", 900, 900);
|
||||
}
|
||||
//otherwise show current position
|
||||
else {
|
||||
sprintf(buf_tmp, "1ST %5.4f", (float)lengthNow/1000);
|
||||
@ -443,23 +530,13 @@ void task_control(void *pvParameter)
|
||||
displayTop.showString(buf_disp1);
|
||||
}
|
||||
|
||||
|
||||
//--------------------------
|
||||
//-------- display2 --------
|
||||
//--------------------------
|
||||
//run handle function
|
||||
displayBot.handle();
|
||||
//setting target length: blink target length
|
||||
if (SW_SET.state == true) {
|
||||
sprintf(buf_tmp, "S0LL%5.3f", (float)lengthTarget/1000);
|
||||
displayBot.blinkStrings(buf_tmp, "S0LL ", 300, 100);
|
||||
}
|
||||
//manual state: blink "manual"
|
||||
else if (controlState == systemState_t::MANUAL) {
|
||||
displayBot.blinkStrings(" MANUAL ", buf_disp2, 400, 800);
|
||||
}
|
||||
//notify that cutter is active
|
||||
else if (cutter_isRunning()) {
|
||||
if (cutter_isRunning()) {
|
||||
displayBot.blinkStrings("CUTTING]", "CUTTING[", 100, 100);
|
||||
}
|
||||
//show ms countdown to cut when pending
|
||||
@ -468,6 +545,20 @@ void task_control(void *pvParameter)
|
||||
//displayBot.showString(buf_disp2); //TODO:blink "erreicht" overrides this. for now using blink as workaround
|
||||
displayBot.blinkStrings(buf_disp2, buf_disp2, 100, 100);
|
||||
}
|
||||
//manual state: blink "manual"
|
||||
else if (controlState == systemState_t::MANUAL) {
|
||||
displayBot.blinkStrings(" MANUAL ", buf_disp2, 400, 800);
|
||||
}
|
||||
//setting winding width: blink currently set windingWidth
|
||||
else if (SW_SET.state && SW_PRESET1.state){
|
||||
sprintf(buf_tmp, " %03d mm", guide_getWindingWidth());
|
||||
displayBot.blinkStrings(buf_tmp, " ", 300, 100);
|
||||
}
|
||||
//setting target length: blink target length
|
||||
else if (SW_SET.state == true) {
|
||||
sprintf(buf_tmp, "S0LL%5.3f", (float)lengthTarget/1000);
|
||||
displayBot.blinkStrings(buf_tmp, "S0LL ", 300, 100);
|
||||
}
|
||||
//otherwise show target length
|
||||
else {
|
||||
//sprintf(buf_disp2, "%06.1f cm", (float)lengthTarget/10); //cm
|
||||
@ -476,6 +567,7 @@ void task_control(void *pvParameter)
|
||||
displayBot.showString(buf_tmp);
|
||||
}
|
||||
|
||||
#endif // end else ifdef ENCODER_TEST
|
||||
|
||||
//----------------------------
|
||||
//------- control lamp -------
|
||||
@ -492,10 +584,6 @@ void task_control(void *pvParameter)
|
||||
gpio_set_level(GPIO_LAMP, 0);
|
||||
}
|
||||
|
||||
} //end while(1)
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
} //end task_control
|
||||
|
@ -1,34 +1,12 @@
|
||||
#pragma once
|
||||
extern "C"
|
||||
{
|
||||
#include <stdio.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <esp_idf_version.h>
|
||||
#include "freertos/queue.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_log.h"
|
||||
#include "driver/adc.h"
|
||||
|
||||
#include "max7219.h"
|
||||
|
||||
}
|
||||
#include <cmath>
|
||||
|
||||
#include "config.hpp"
|
||||
#include "gpio_evaluateSwitch.hpp"
|
||||
#include "gpio_adc.hpp"
|
||||
#include "buzzer.hpp"
|
||||
#include "vfd.hpp"
|
||||
#include "display.hpp"
|
||||
#include "cutter.hpp"
|
||||
|
||||
|
||||
|
||||
//enum describing the state of the system
|
||||
enum class systemState_t {COUNTING, WINDING_START, WINDING, TARGET_REACHED, AUTO_CUT_WAITING, CUTTING, MANUAL};
|
||||
|
||||
//array with enum as strings for logging states
|
||||
extern const char* systemStateStr[7];
|
||||
|
||||
|
||||
//task that controls the entire machine (has to be created as task in main function)
|
||||
void task_control(void *pvParameter);
|
||||
|
@ -1,4 +1,6 @@
|
||||
#include "cutter.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
|
||||
const char* cutter_stateStr[5] = {"IDLE", "START", "CUTTING", "CANCELED", "TIMEOUT"}; //define strings for logging the state
|
||||
|
||||
@ -39,7 +41,6 @@ void cutter_stop(){
|
||||
if(cutter_state != cutter_state_t::IDLE){
|
||||
setState(cutter_state_t::CANCELED);
|
||||
}
|
||||
//starts motor on state change
|
||||
}
|
||||
|
||||
|
||||
@ -131,7 +132,6 @@ void cutter_handle(){
|
||||
//SW_CUTTER_POS.minOnMs = 10;
|
||||
//SW_CUTTER_POS.minOffMs = 10;
|
||||
|
||||
|
||||
switch(cutter_state){
|
||||
case cutter_state_t::IDLE:
|
||||
case cutter_state_t::TIMEOUT:
|
||||
@ -142,14 +142,13 @@ void cutter_handle(){
|
||||
case cutter_state_t::START:
|
||||
//--- moved away from idle position ---
|
||||
//if (gpio_get_level(GPIO_CUTTER_POS_SW) == 0){ //contact closed
|
||||
if (SW_CUTTER_POS.state == true) { //contact closed -> not at idle pos
|
||||
if (SW_CUTTER_POS.state == true) { //contact closed -> not at idle pos anymore
|
||||
setState(cutter_state_t::CUTTING);
|
||||
}
|
||||
//--- timeout ---
|
||||
else {
|
||||
checkTimeout();
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case cutter_state_t::CUTTING:
|
||||
|
@ -1,5 +1,6 @@
|
||||
#include "display.hpp"
|
||||
|
||||
#include "config.h"
|
||||
|
||||
//=== variables ===
|
||||
static const char *TAG = "display"; //tag for logging
|
||||
@ -34,7 +35,7 @@ max7219_t display_init(){
|
||||
ESP_ERROR_CHECK(max7219_init_desc(&dev, HOST, MAX7219_MAX_CLOCK_SPEED_HZ, DISPLAY_PIN_NUM_CS));
|
||||
ESP_ERROR_CHECK(max7219_init(&dev));
|
||||
//0...15
|
||||
ESP_ERROR_CHECK(max7219_set_brightness(&dev, 8)); //TODO add this to config
|
||||
ESP_ERROR_CHECK(max7219_set_brightness(&dev, DISPLAY_BRIGHTNESS));
|
||||
return dev;
|
||||
//display = dev;
|
||||
ESP_LOGI(TAG, "initializing display - done");
|
||||
@ -50,7 +51,7 @@ void display_ShowWelcomeMsg(max7219_t dev){
|
||||
//show name and date
|
||||
ESP_LOGI(TAG, "showing startup message...");
|
||||
max7219_clear(&dev);
|
||||
max7219_draw_text_7seg(&dev, 0, "CUTTER 29.09.2022");
|
||||
max7219_draw_text_7seg(&dev, 0, "CUTTER 15.03.2024");
|
||||
// 1234567812 34 5678
|
||||
vTaskDelay(pdMS_TO_TICKS(700));
|
||||
//scroll "hello" over 2 displays
|
||||
@ -64,7 +65,7 @@ void display_ShowWelcomeMsg(max7219_t dev){
|
||||
//noticed rare bug that one display does not initialize / is not configured correctly after start
|
||||
//initialize display again after the welcome message in case it did not work the first time
|
||||
ESP_ERROR_CHECK(max7219_init(&dev));
|
||||
ESP_ERROR_CHECK(max7219_set_brightness(&dev, 8)); //TODO add this to config
|
||||
ESP_ERROR_CHECK(max7219_set_brightness(&dev, DISPLAY_BRIGHTNESS));
|
||||
}
|
||||
|
||||
|
||||
@ -83,9 +84,9 @@ handledDisplay::handledDisplay(max7219_t displayDevice, uint8_t posStart_f) {
|
||||
|
||||
|
||||
|
||||
//--------------------------------
|
||||
//---------- showString ----------
|
||||
//--------------------------------
|
||||
//================================
|
||||
//========== showString ==========
|
||||
//================================
|
||||
//function that displays a given string on the display
|
||||
void handledDisplay::showString(const char * buf, uint8_t pos_f){
|
||||
//calculate actual absolute position
|
||||
@ -103,11 +104,11 @@ void handledDisplay::showString(const char * buf, uint8_t pos_f){
|
||||
|
||||
|
||||
//TODO: blinkStrings() and blink() are very similar - can be optimized?
|
||||
//only difficulty currently is the reset behaivor of blinkStrings through showString (blink does not reset)
|
||||
//only difficulty is the reset behaivor of blinkStrings through showString (blink does not reset)
|
||||
|
||||
//----------------------------------
|
||||
//---------- blinkStrings ----------
|
||||
//----------------------------------
|
||||
//==================================
|
||||
//========== blinkStrings ==========
|
||||
//==================================
|
||||
//function switches between two strings in a given interval
|
||||
void handledDisplay::blinkStrings(const char * strOn_f, const char * strOff_f, uint32_t msOn_f, uint32_t msOff_f){
|
||||
//copy/update variables
|
||||
@ -130,9 +131,9 @@ void handledDisplay::blinkStrings(const char * strOn_f, const char * strOff_f, u
|
||||
|
||||
|
||||
|
||||
//-------------------------------
|
||||
//------------ blink ------------
|
||||
//-------------------------------
|
||||
//===============================
|
||||
//============ blink ============
|
||||
//===============================
|
||||
//function triggers certain count and interval of off durations
|
||||
void handledDisplay::blink(uint8_t count_f, uint32_t msOn_f, uint32_t msOff_f, const char * strOff_f) {
|
||||
//copy/update parameters
|
||||
@ -156,9 +157,9 @@ void handledDisplay::blink(uint8_t count_f, uint32_t msOn_f, uint32_t msOff_f, c
|
||||
|
||||
|
||||
|
||||
//--------------------------------
|
||||
//------------ handle ------------
|
||||
//--------------------------------
|
||||
//================================
|
||||
//============ handle ============
|
||||
//================================
|
||||
//function that handles time based modes
|
||||
//writes text to the 7 segment display depending on the current mode
|
||||
void handledDisplay::handle() {
|
||||
|
@ -16,9 +16,8 @@ extern "C"
|
||||
#include <cstring>
|
||||
|
||||
|
||||
#include "config.hpp"
|
||||
|
||||
//function for initializing the display using configuration from macros in config.hpp
|
||||
//function for initializing the display using configuration from macros in config.h
|
||||
max7219_t display_init();
|
||||
|
||||
//show welcome message on the entire display
|
||||
@ -44,8 +43,8 @@ class handledDisplay {
|
||||
//TODO: blinkStrings and blink are very similar - optimize?
|
||||
//TODO: add 'scroll string' method
|
||||
|
||||
private:
|
||||
|
||||
private:
|
||||
//--- variables ---
|
||||
//config
|
||||
max7219_t dev;
|
||||
|
@ -8,6 +8,8 @@ extern "C" {
|
||||
}
|
||||
|
||||
#include "encoder.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
|
||||
|
||||
//----------------------------
|
||||
@ -17,10 +19,14 @@ static rotary_encoder_info_t encoder; //encoder device/info
|
||||
QueueHandle_t encoder_queue = NULL; //encoder event queue
|
||||
|
||||
|
||||
|
||||
//-------------------------
|
||||
//------- functions -------
|
||||
//-------------------------
|
||||
//--- encoder_init ---
|
||||
|
||||
//======================
|
||||
//==== encoder_init ====
|
||||
//======================
|
||||
//initialize encoder and return event queue
|
||||
QueueHandle_t encoder_init(){
|
||||
// esp32-rotary-encoder requires that the GPIO ISR service is installed before calling rotary_encoder_register()
|
||||
@ -41,7 +47,9 @@ QueueHandle_t encoder_init(){
|
||||
}
|
||||
|
||||
|
||||
//--- encoder_getSteps ---
|
||||
//========================
|
||||
//=== encoder_getSteps ===
|
||||
//========================
|
||||
//get steps counted since last reset
|
||||
int encoder_getSteps(){
|
||||
// Poll current position and direction
|
||||
@ -52,14 +60,18 @@ int encoder_getSteps(){
|
||||
}
|
||||
|
||||
|
||||
//--- encoder_getLenMm ---
|
||||
//========================
|
||||
//=== encoder_getLenMm ===
|
||||
//========================
|
||||
//get current length in Mm since last reset
|
||||
int encoder_getLenMm(){
|
||||
return (float)encoder_getSteps() * 1000 / ENCODER_STEPS_PER_METER;
|
||||
}
|
||||
|
||||
|
||||
//--- encoder_reset ---
|
||||
//=======================
|
||||
//==== encoder_reset ====
|
||||
//=======================
|
||||
//reset counted steps / length to 0
|
||||
void encoder_reset(){
|
||||
rotary_encoder_reset(&encoder);
|
||||
|
@ -6,7 +6,6 @@ extern "C" {
|
||||
#include <freertos/task.h>
|
||||
}
|
||||
|
||||
#include "config.hpp"
|
||||
|
||||
|
||||
//----------------------------
|
||||
@ -34,7 +33,6 @@ int encoder_getSteps();
|
||||
int encoder_getLenMm();
|
||||
|
||||
|
||||
|
||||
//--- encoder_reset ---
|
||||
//reset counted steps / length to 0
|
||||
void encoder_reset();
|
||||
|
@ -1,4 +1,5 @@
|
||||
#include "config.hpp"
|
||||
#include "global.hpp"
|
||||
#include "config.h"
|
||||
|
||||
|
||||
//--- inputs ---
|
33
main/global.hpp
Normal file
33
main/global.hpp
Normal file
@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
extern "C" {
|
||||
#include "driver/adc.h"
|
||||
}
|
||||
#include "gpio_evaluateSwitch.hpp"
|
||||
#include "buzzer.hpp"
|
||||
#include "switchesAnalog.hpp"
|
||||
|
||||
//note: in the actual code macro variables to these objects from config.h are used as the objects names
|
||||
|
||||
//============================
|
||||
//===== global variables =====
|
||||
//============================
|
||||
//create global evaluated switch objects for all available pins
|
||||
//--- switches on digital gpio pins ---
|
||||
//extern gpio_evaluatedSwitch sw_gpio_39;
|
||||
extern gpio_evaluatedSwitch sw_gpio_34;
|
||||
extern gpio_evaluatedSwitch sw_gpio_32;
|
||||
extern gpio_evaluatedSwitch sw_gpio_33;
|
||||
extern gpio_evaluatedSwitch sw_gpio_25;
|
||||
extern gpio_evaluatedSwitch sw_gpio_26;
|
||||
extern gpio_evaluatedSwitch sw_gpio_14;
|
||||
|
||||
//--- switches connected to 4-sw-to-analog stripboard ---
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_0;
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_1;
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_2;
|
||||
extern gpio_evaluatedSwitch sw_gpio_analog_3;
|
||||
|
||||
|
||||
//create global buzzer object
|
||||
extern buzzer_t buzzer;
|
@ -5,205 +5,276 @@ extern "C"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_log.h"
|
||||
#include "driver/adc.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/semphr.h"
|
||||
}
|
||||
|
||||
#include "DendoStepper.h"
|
||||
#include "config.hpp"
|
||||
#include "stepper.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
#include "guide-stepper.hpp"
|
||||
#include "encoder.hpp"
|
||||
#include "gpio_evaluateSwitch.hpp"
|
||||
#include "shutdown.hpp"
|
||||
|
||||
|
||||
//macro to get smaller value out of two
|
||||
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
|
||||
|
||||
//---------------------
|
||||
//--- configuration ---
|
||||
//---------------------
|
||||
//also see config.hpp
|
||||
//for pin definition
|
||||
//also see config.h
|
||||
//for pin definitions and guide parameters
|
||||
|
||||
// configure testing modes
|
||||
#define STEPPER_TEST_TRAVEL 65 // mm
|
||||
//
|
||||
#define MIN_MM 0
|
||||
#define MAX_MM 110 //60
|
||||
#define POS_MAX_STEPS MAX_MM * STEPPER_STEPS_PER_MM
|
||||
#define POS_MIN_STEPS MIN_MM * STEPPER_STEPS_PER_MM
|
||||
|
||||
|
||||
// speeds for testing with potentiometer (test task only)
|
||||
#define SPEED_MIN 2.0 // mm/s
|
||||
#define SPEED_MAX 60.0 //mm/s
|
||||
#define SPEED_MAX 70.0 // mm/s
|
||||
//note: actual speed is currently defined in config.h with STEPPER_SPEED_DEFAULT
|
||||
//simulate encoder with reset button to test stepper ctl task
|
||||
//note STEPPER_TEST has to be defined as well
|
||||
//#define STEPPER_SIMULATE_ENCODER
|
||||
|
||||
#define SPEED 10 //35, 100, 50 rev
|
||||
#define ACCEL_MS 800.0 //ms from 0 to max
|
||||
#define DECEL_MS 500.0 //ms from max to 0
|
||||
|
||||
#define STEPPER_STEPS_PER_ROT 1600
|
||||
#define STEPPER_STEPS_PER_MM STEPPER_STEPS_PER_ROT/4
|
||||
|
||||
#define D_CABLE 6
|
||||
#define D_REEL 160 //actual 170
|
||||
#define PI 3.14159
|
||||
|
||||
//#define POS_MAX_STEPS GUIDE_MAX_MM * STEPPER_STEPS_PER_MM //note replaced with posMaxSteps
|
||||
#define POS_MIN_STEPS GUIDE_MIN_MM * STEPPER_STEPS_PER_MM
|
||||
|
||||
|
||||
//----------------------
|
||||
//----- variables ------
|
||||
//----------------------
|
||||
static DendoStepper step;
|
||||
static const char *TAG = "stepper"; //tag for logging
|
||||
typedef enum axisDirection_t {AXIS_MOVING_LEFT = 0, AXIS_MOVING_RIGHT} axisDirection_t;
|
||||
|
||||
static bool stepp_direction = true;
|
||||
static bool dir = true, dirPrev; //TODO local variables in travelSteps?
|
||||
static const char *TAG = "stepper-ctrl"; //tag for logging
|
||||
|
||||
static axisDirection_t currentAxisDirection = AXIS_MOVING_RIGHT;
|
||||
static uint32_t posNow = 0;
|
||||
|
||||
static int layerCount = 0;
|
||||
|
||||
// queue for sending commands to task handling guide movement
|
||||
static QueueHandle_t queue_commandsGuideTask;
|
||||
|
||||
// mutex to prevent multiple axis to config variables also accessed/modified by control task
|
||||
SemaphoreHandle_t configVariables_mutex = xSemaphoreCreateMutex();
|
||||
|
||||
// configured winding width: position the axis returns again in steps
|
||||
static uint32_t posMaxSteps = GUIDE_MAX_MM * STEPPER_STEPS_PER_MM; //assign default width
|
||||
|
||||
|
||||
//----------------------
|
||||
//----- functions ------
|
||||
//----------------------
|
||||
|
||||
//=============================
|
||||
//=== guide_getAxisPosSteps ===
|
||||
//=============================
|
||||
// return local variable posNow
|
||||
// needed at shutdown detection to store last axis position in nvs
|
||||
int guide_getAxisPosSteps(){
|
||||
return posNow;
|
||||
}
|
||||
|
||||
|
||||
//=============================
|
||||
//=== guide_setWindingWidth ===
|
||||
//=============================
|
||||
// set custom winding width (axis position the guide returns in mm)
|
||||
void guide_setWindingWidth(uint8_t maxPosMm)
|
||||
{
|
||||
if (xSemaphoreTake(configVariables_mutex, portMAX_DELAY) == pdTRUE) // mutex to prevent multiple access by control and stepper-ctl task
|
||||
{
|
||||
posMaxSteps = maxPosMm * STEPPER_STEPS_PER_MM;
|
||||
ESP_LOGI(TAG, "set winding width / max pos to %dmm", maxPosMm);
|
||||
xSemaphoreGive(configVariables_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//=======================================
|
||||
//=== guide_targetLength2WindingWidth ===
|
||||
//=======================================
|
||||
// calculate dynamic winding width in mm from cable length in mm
|
||||
uint8_t guide_targetLength2WindingWidth(int lenMm)
|
||||
{
|
||||
#ifdef DYNAMIC_WINDING_WIDTH_ENABLED
|
||||
uint8_t width;
|
||||
//--- config ---
|
||||
// define thresholds for winding widths according to target length:
|
||||
if (lenMm <= 5000) // 0-5m
|
||||
width = 15;
|
||||
else if (lenMm <= 10000) // 6-10m
|
||||
width = 25;
|
||||
else if (lenMm <= 15000) // 11-15m
|
||||
width = 30;
|
||||
else if (lenMm <= 25000) // 16-25m
|
||||
width = 65;
|
||||
else // >25m
|
||||
width = GUIDE_MAX_MM;
|
||||
ESP_LOGW(TAG, "length2width: calculated windingWidth=%dmm from targetLength=%dm", width, lenMm);
|
||||
return width;
|
||||
#else
|
||||
ESP_LOGD(TAG, "length2width: dynamic windingWidh not enabled, stay at GUIDE_MAX=%d", GUIDE_MAX_MM);
|
||||
return GUIDE_MAX_MM;
|
||||
#endif
|
||||
//TODO update winding width here as well already?
|
||||
}
|
||||
|
||||
|
||||
//=============================
|
||||
//=== guide_getWindingWidth ===
|
||||
//=============================
|
||||
// get currently configured winding width (axis position at which the guide returns in mm)
|
||||
uint8_t guide_getWindingWidth()
|
||||
{
|
||||
if (xSemaphoreTake(configVariables_mutex, portMAX_DELAY) == pdTRUE) // mutex to prevent multiple access by control and stepper-ctl task
|
||||
{
|
||||
uint8_t returnValue = posMaxSteps / STEPPER_STEPS_PER_MM;
|
||||
xSemaphoreGive(configVariables_mutex);
|
||||
return returnValue;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
//==========================
|
||||
//==== guide_moveToZero ====
|
||||
//==========================
|
||||
//tell stepper-control task to move cable guide to zero position
|
||||
void guide_moveToZero(){
|
||||
bool valueToSend = true; // or false
|
||||
xQueueSend(queue_commandsGuideTask, &valueToSend, portMAX_DELAY);
|
||||
ESP_LOGI(TAG, "sending command to stepper_ctl task via queue");
|
||||
}
|
||||
|
||||
|
||||
//---------------------
|
||||
//---- travelSteps ----
|
||||
//---------------------
|
||||
//move axis certain Steps (relative) between left and right or reverse when negative
|
||||
void travelSteps(int stepsTarget){
|
||||
//posNow = step.getPositionMm(); //not otherwise controlled, so no update necessary
|
||||
//TODO simplify this function, one simple calculation of new position?
|
||||
//with new custom driver no need to detect direction change
|
||||
|
||||
// cancel when width is zero or no steps received
|
||||
if (posMaxSteps == 0 || stepsTarget == 0){
|
||||
ESP_LOGD(TAG, "travelSteps: MaxSteps or stepsTarget = 0 -> nothing to do");
|
||||
return;
|
||||
}
|
||||
|
||||
int stepsToGo, remaining;
|
||||
|
||||
stepsToGo = abs(stepsTarget);
|
||||
if(stepsTarget < 0) stepp_direction = !stepp_direction; //invert direction in reverse mode
|
||||
|
||||
// invert direction in reverse mode (cable gets spooled off reel)
|
||||
if (stepsTarget < 0) {
|
||||
currentAxisDirection = (currentAxisDirection == AXIS_MOVING_LEFT) ? AXIS_MOVING_RIGHT : AXIS_MOVING_LEFT; //toggle between RIGHT<->Left
|
||||
}
|
||||
|
||||
while (stepsToGo != 0){
|
||||
|
||||
//--- wait if direction changed ---
|
||||
//if (dirPrev != dir){
|
||||
// ESP_LOGW(TAG, " dir-change detected - waiting for move to finish \n ");
|
||||
// while(step.getState() != 1) vTaskDelay(1); //wait for move to finish
|
||||
//}
|
||||
|
||||
//--- currently moving right ---
|
||||
if (stepp_direction == true){ //currently moving right
|
||||
remaining = POS_MAX_STEPS - posNow; //calc remaining distance fom current position to limit
|
||||
if (currentAxisDirection == AXIS_MOVING_RIGHT){ //currently moving right
|
||||
if (xSemaphoreTake(configVariables_mutex, portMAX_DELAY) == pdTRUE) { //prevent multiple acces on posMaxSteps by control-task
|
||||
remaining = posMaxSteps - posNow; //calc remaining distance fom current position to limit
|
||||
if (stepsToGo > remaining){ //new distance will exceed limit
|
||||
step.runAbs (POS_MAX_STEPS); //move to limit
|
||||
dirPrev = dir;
|
||||
dir = 1;
|
||||
//while(step.getState() != 1) vTaskDelay(1); //wait for move to finish
|
||||
posNow = POS_MAX_STEPS;
|
||||
stepp_direction = false; //change current direction for next iteration
|
||||
stepper_setTargetPosSteps(posMaxSteps); //move to limit
|
||||
stepper_waitForStop(1000);
|
||||
posNow = posMaxSteps;
|
||||
currentAxisDirection = AXIS_MOVING_LEFT; //change current direction for next iteration
|
||||
//increment/decrement layer count depending on current cable direction
|
||||
layerCount += (stepsTarget > 0) - (stepsTarget < 0);
|
||||
if (layerCount < 0) layerCount = 0; //negative layers are not possible
|
||||
stepsToGo = stepsToGo - remaining; //decrease target length by already traveled distance
|
||||
ESP_LOGI(TAG, " --- moved to max -> change direction (L) --- \n ");
|
||||
}
|
||||
else { //target distance does not reach the limit
|
||||
step.runAbs (posNow + stepsToGo); //move by (remaining) distance to reach target length
|
||||
dirPrev = dir;
|
||||
dir = 1;
|
||||
//-- dont wait for move to finish since moves in same direction get merged --
|
||||
//while(step.getState() != 1) vTaskDelay(1); //wait for move to finish
|
||||
stepper_setTargetPosSteps(posNow + stepsToGo); //move by (remaining) distance to reach target length
|
||||
ESP_LOGD(TAG, "moving to %d\n", posNow+stepsToGo);
|
||||
posNow += stepsToGo;
|
||||
stepsToGo = 0; //finished, reset target length (could as well exit loop/break)
|
||||
}
|
||||
xSemaphoreGive(configVariables_mutex);
|
||||
}
|
||||
}
|
||||
|
||||
//--- currently moving left ---
|
||||
else {
|
||||
else if (currentAxisDirection == AXIS_MOVING_LEFT){
|
||||
remaining = posNow - POS_MIN_STEPS;
|
||||
if (stepsToGo > remaining){
|
||||
step.runAbs (POS_MIN_STEPS);
|
||||
dirPrev = dir;
|
||||
dir = 0;
|
||||
//while(step.getState() != 1) vTaskDelay(2); //wait for move to finish
|
||||
stepper_setTargetPosSteps(POS_MIN_STEPS);
|
||||
stepper_waitForStop(1000);
|
||||
posNow = POS_MIN_STEPS;
|
||||
stepp_direction = true;
|
||||
currentAxisDirection = AXIS_MOVING_RIGHT; //switch direction
|
||||
//increment/decrement layer count depending on current cable direction
|
||||
layerCount += (stepsTarget > 0) - (stepsTarget < 0);
|
||||
if (layerCount < 0) layerCount = 0; //negative layers are not possible
|
||||
stepsToGo = stepsToGo - remaining;
|
||||
ESP_LOGI(TAG, " --- moved to min -> change direction (R) --- \n ");
|
||||
}
|
||||
else {
|
||||
step.runAbs (posNow - stepsToGo); //when moving left the coordinate has to be decreased
|
||||
dirPrev = dir;
|
||||
dir = 0;
|
||||
//-- dont wait for move to finish since moves in same direction get merged --
|
||||
//while(step.getState() != 1) vTaskDelay(2); //wait for move to finish
|
||||
stepper_setTargetPosSteps(posNow - stepsToGo); //when moving left the coordinate has to be decreased
|
||||
ESP_LOGD(TAG, "moving to %d\n", posNow - stepsToGo);
|
||||
posNow -= stepsToGo;
|
||||
stepsToGo = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(stepsTarget < 0) stepp_direction = !stepp_direction; //undo inversion of stepp_direction after reverse mode is finished
|
||||
|
||||
// undo inversion of currentAxisDirection after reverse mode is finished
|
||||
if (stepsTarget < 0) {
|
||||
currentAxisDirection = (currentAxisDirection == AXIS_MOVING_LEFT) ? AXIS_MOVING_RIGHT : AXIS_MOVING_LEFT; //toggle between RIGHT<->Left
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
//------------------
|
||||
//---- travelMm ----
|
||||
//------------------
|
||||
//move axis certain Mm (relative) between left and right or reverse when negative
|
||||
void travelMm(int length){
|
||||
travelSteps(length * STEPPER_STEPS_PER_MM);
|
||||
}
|
||||
|
||||
|
||||
//define zero/start position
|
||||
//currently crashes into hardware limitation for certain time
|
||||
//TODO: limit switch
|
||||
void home() {
|
||||
ESP_LOGW(TAG, "auto-home...");
|
||||
step.setSpeedMm(100, 500, 10);
|
||||
step.runInf(1);
|
||||
vTaskDelay(1500 / portTICK_PERIOD_MS);
|
||||
step.stop();
|
||||
step.resetAbsolute();
|
||||
ESP_LOGW(TAG, "auto-home finished");
|
||||
}
|
||||
|
||||
|
||||
//----------------------
|
||||
//---- init_stepper ----
|
||||
//----------------------
|
||||
//initialize/configure stepper instance
|
||||
void init_stepper() {
|
||||
//TODO unnecessary wrapper?
|
||||
ESP_LOGW(TAG, "initializing stepper...");
|
||||
DendoStepper_config_t step_cfg = {
|
||||
.stepPin = STEPPER_STEP_PIN,
|
||||
.dirPin = STEPPER_DIR_PIN,
|
||||
.enPin = STEPPER_EN_PIN,
|
||||
.timer_group = TIMER_GROUP_0,
|
||||
.timer_idx = TIMER_0,
|
||||
.miStep = MICROSTEP_32,
|
||||
.stepAngle = 1.8};
|
||||
step.config(&step_cfg);
|
||||
step.init();
|
||||
|
||||
step.setSpeed(1000, 1000, 1000); //random default speed
|
||||
step.setStepsPerMm(STEPPER_STEPS_PER_MM); //guide: 4mm/rot
|
||||
stepper_init();
|
||||
// create queue for sending commands to task handling guide movement
|
||||
// currently length 1 and only one command possible, thus bool
|
||||
queue_commandsGuideTask = xQueueCreate(1, sizeof(bool));
|
||||
}
|
||||
|
||||
|
||||
//function that updates speed value using ADC input and configured MIN/MAX
|
||||
//--------------------------
|
||||
//--- updateSpeedFromAdc ---
|
||||
//--------------------------
|
||||
//function that updates speed value using ADC input and configured MIN/MAX - used for testing only
|
||||
void updateSpeedFromAdc() {
|
||||
int potiRead = gpio_readAdc(ADC_CHANNEL_POTI); //0-4095 GPIO34
|
||||
double poti = potiRead/4095.0;
|
||||
int speed = poti*(SPEED_MAX-SPEED_MIN) + SPEED_MIN;
|
||||
step.setSpeedMm(speed, ACCEL_MS, DECEL_MS);
|
||||
stepper_setSpeed(speed);
|
||||
ESP_LOGW(TAG, "poti: %d (%.2lf%%), set speed to: %d", potiRead, poti*100, speed);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//----------------------------
|
||||
//---- TASK stepper-test -----
|
||||
//----------------------------
|
||||
//============================
|
||||
//==== TASK stepper_test =====
|
||||
//============================
|
||||
//test axis without using encoder input
|
||||
#ifndef STEPPER_SIMULATE_ENCODER
|
||||
void task_stepper_test(void *pvParameter)
|
||||
{
|
||||
init_stepper();
|
||||
home();
|
||||
step.setSpeedMm(SPEED, ACCEL_MS, DECEL_MS);
|
||||
//--- move from left to right repeatedly ---
|
||||
// while (1) {
|
||||
// updateSpeedFromAdc();
|
||||
// step.runPosMm(STEPPER_TEST_TRAVEL);
|
||||
// while(step.getState() != 1) vTaskDelay(2);
|
||||
// ESP_LOGI(TAG, "finished moving right => moving left");
|
||||
|
||||
// 10updateSpeedFromAdc();
|
||||
// step.runPosMm(-STEPPER_TEST_TRAVEL);
|
||||
// while(step.getState() != 1) vTaskDelay(2); //1=idle
|
||||
// ESP_LOGI(TAG, "finished moving left => moving right");
|
||||
// }
|
||||
|
||||
//--- control stepper using preset buttons ---
|
||||
stepper_init();
|
||||
while(1){
|
||||
vTaskDelay(20 / portTICK_PERIOD_MS);
|
||||
|
||||
@ -218,90 +289,179 @@ void task_stepper_test(void *pvParameter)
|
||||
SW_CUT.handle();
|
||||
SW_AUTO_CUT.handle();
|
||||
|
||||
#ifdef ONE_BUTTON_TEST //test with "reset-button" only
|
||||
static int state = 0;
|
||||
//cycle through test commands with one button
|
||||
if (SW_RESET.risingEdge) {
|
||||
ESP_LOGI(TAG, "button - stop stepper\n ");
|
||||
buzzer.beep(1, 1000, 100);
|
||||
step.stop();
|
||||
switch (state){
|
||||
case 0:
|
||||
stepper_setTargetPosMm(50);
|
||||
//stepper_setTargetPosSteps(1000);
|
||||
state++;
|
||||
break;
|
||||
case 1:
|
||||
stepper_setTargetPosMm(80);
|
||||
//stepper_setTargetPosSteps(100);
|
||||
state++;
|
||||
break;
|
||||
case 2:
|
||||
stepper_setTargetPosMm(20);
|
||||
//stepper_setTargetPosSteps(100);
|
||||
state++;
|
||||
break;
|
||||
case 3:
|
||||
stepper_setTargetPosMm(60);
|
||||
//stepper_setTargetPosSteps(2000);
|
||||
state = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
#else //test with all buttons
|
||||
if (SW_RESET.risingEdge) {
|
||||
buzzer.beep(1, 500, 100);
|
||||
stepper_setTargetPosMm(0);
|
||||
}
|
||||
if (SW_PRESET1.risingEdge) {
|
||||
ESP_LOGI(TAG, "button - moving right\n ");
|
||||
buzzer.beep(2, 300, 100);
|
||||
step.setSpeedMm(SPEED, ACCEL_MS, DECEL_MS);
|
||||
step.runPosMm(15);
|
||||
}
|
||||
if (SW_PRESET3.risingEdge) {
|
||||
ESP_LOGI(TAG, "button - moving left\n ");
|
||||
buzzer.beep(1, 500, 100);
|
||||
step.setSpeedMm(SPEED, ACCEL_MS, DECEL_MS);
|
||||
step.runPosMm(-15);
|
||||
buzzer.beep(1, 200, 100);
|
||||
stepper_setTargetPosMm(50);
|
||||
}
|
||||
if (SW_PRESET2.risingEdge) {
|
||||
buzzer.beep(1, 100, 100);
|
||||
ESP_LOGW(TAG, "button - current state: %d\n, pos: %llu", (int)step.getState(), step.getPositionMm());
|
||||
}
|
||||
buzzer.beep(2, 200, 100);
|
||||
stepper_setTargetPosMm(75);
|
||||
}
|
||||
if (SW_PRESET3.risingEdge) {
|
||||
buzzer.beep(3, 200, 100);
|
||||
stepper_setTargetPosMm(100);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif //end SIMULATE_ENCODER
|
||||
|
||||
|
||||
|
||||
//----------------------------
|
||||
//----- TASK stepper-ctl -----
|
||||
//----------------------------
|
||||
//============================
|
||||
//===== TASK stepper_ctl =====
|
||||
//============================
|
||||
//task controlling the linear axis guiding the cable according to wire length spooled
|
||||
#ifdef STEPPER_SIMULATE_ENCODER
|
||||
void task_stepper_test(void *pvParameter)
|
||||
#else
|
||||
void task_stepper_ctl(void *pvParameter)
|
||||
#endif
|
||||
{
|
||||
//variables
|
||||
int encStepsNow = 0; //get curret steps of encoder
|
||||
int encStepsPrev = 0; //steps at last check
|
||||
int encStepsDelta = 0; //steps changed since last iteration
|
||||
//-- variables --
|
||||
static int encStepsPrev = 0; //measured encoder steps at last run
|
||||
static double travelStepsPartial = 0; //store resulted remaining partial steps last run
|
||||
|
||||
//temporary variables for calculating required steps, or logging
|
||||
int encStepsNow = 0; //get curretly measured steps of encoder
|
||||
int encStepsDelta = 0; //encoder steps changed since last iteration
|
||||
|
||||
double cableLen = 0;
|
||||
double travelStepsExact = 0; //steps axis has to travel
|
||||
double travelStepsPartial = 0;
|
||||
int travelStepsFull = 0;
|
||||
double travelMm = 0;
|
||||
double turns = 0;
|
||||
float currentDiameter;
|
||||
|
||||
float potiModifier;
|
||||
|
||||
|
||||
//initialize stepper at task start
|
||||
init_stepper();
|
||||
home();
|
||||
//define zero-position
|
||||
// use last known position stored at last shutdown to reduce time crashing into hardware limit
|
||||
int posLastShutdown = nvsReadLastAxisPosSteps();
|
||||
if (posLastShutdown >= 0)
|
||||
{ // would be -1 when failed
|
||||
ESP_LOGW(TAG, "auto-home: considerting pos last shutdown %dmm + tolerance %dmm",
|
||||
posLastShutdown / STEPPER_STEPS_PER_MM,
|
||||
AUTO_HOME_TRAVEL_ADD_TO_LAST_POS_MM);
|
||||
// home considering last position and offset, but limit to max distance possible
|
||||
stepper_home(MIN((posLastShutdown/STEPPER_STEPS_PER_MM + AUTO_HOME_TRAVEL_ADD_TO_LAST_POS_MM), MAX_TOTAL_AXIS_TRAVEL_MM));
|
||||
}
|
||||
else { // default to max travel when read from nvs failed
|
||||
stepper_home(MAX_TOTAL_AXIS_TRAVEL_MM);
|
||||
}
|
||||
|
||||
//repeatedly read changes in measured cable length and move axis accordingly
|
||||
while(1){
|
||||
|
||||
// guide is disabled when posMaxSteps is zero:
|
||||
if (posMaxSteps == 0)
|
||||
{
|
||||
// move to starting position
|
||||
stepper_setTargetPosSteps(0);
|
||||
vTaskDelay(1000 / portTICK_PERIOD_MS);
|
||||
ESP_LOGD(TAG, "posMaxSteps is zero -> guide disabled, doing nothing");
|
||||
// stop loop iteration
|
||||
continue;
|
||||
}
|
||||
|
||||
#ifdef STEPPER_SIMULATE_ENCODER
|
||||
//TESTING - simulate encoder using switch
|
||||
SW_RESET.handle();
|
||||
//note
|
||||
if (SW_RESET.risingEdge) encStepsNow += 500;
|
||||
#else
|
||||
//get current length
|
||||
encStepsNow = encoder_getSteps();
|
||||
#endif
|
||||
|
||||
// move to zero and reset if command received via queue
|
||||
bool receivedValue;
|
||||
if (xQueueReceive(queue_commandsGuideTask, &receivedValue, 0) == pdTRUE)
|
||||
{
|
||||
// Process the received value
|
||||
// TODO support other commands (currently only move to zero possible)
|
||||
ESP_LOGW(TAG, "task: move-to-zero command received via queue, starting move, waiting until position reached");
|
||||
stepper_setTargetPosMm(0);
|
||||
stepper_waitForStop();
|
||||
//reset variables -> start tracking cable movement starting from position zero
|
||||
// ensure stepsDelta is 0
|
||||
encStepsNow = encoder_getSteps();
|
||||
encStepsPrev = encStepsNow;
|
||||
travelStepsPartial = 0;
|
||||
// set locally stored axis position and counted layers to 0 (used for calculating the target axis coordinate and steps)
|
||||
posNow = 0;
|
||||
layerCount = 0;
|
||||
currentAxisDirection = AXIS_MOVING_RIGHT;
|
||||
ESP_LOGW(TAG, "at position 0, reset variables, resuming normal cable guiding operation");
|
||||
}
|
||||
|
||||
//calculate change
|
||||
encStepsDelta = encStepsNow - encStepsPrev; //FIXME MAJOR BUG: when resetting encoder/length in control task, diff will be huge!
|
||||
encStepsDelta = encStepsNow - encStepsPrev;
|
||||
//check if reset happend without moving to zero before - resulting in huge diff
|
||||
if (encStepsDelta != 0 && encStepsNow == 0){ // this should not happen and causes weird movement
|
||||
ESP_LOGE(TAG, "encoder steps changed to 0 (reset) without previous moveToZero() call, resulting in stepsDelta=%d", encStepsDelta);
|
||||
}
|
||||
|
||||
//read potentiometer and normalize (0-1) to get a variable for testing
|
||||
potiModifier = (float) gpio_readAdc(ADC_CHANNEL_POTI) / 4095; //0-4095 -> 0-1
|
||||
//float potiModifier = (float) gpio_readAdc(ADC_CHANNEL_POTI) / 4095; //0-4095 -> 0-1
|
||||
//ESP_LOGI(TAG, "current poti-modifier = %f", potiModifier);
|
||||
ESP_LOGI(TAG, "delaying stepper-ctl task by %.1f ms (poti value)", 2000 * potiModifier);
|
||||
vTaskDelay(2000 * potiModifier / portTICK_PERIOD_MS);
|
||||
|
||||
//calculate steps to move
|
||||
cableLen = (double)encStepsDelta * 1000 / ENCODER_STEPS_PER_METER;
|
||||
turns = cableLen / (PI * D_REEL);
|
||||
//effective diameter increases each layer
|
||||
currentDiameter = D_REEL + LAYER_THICKNESS_MM * 2 * layerCount;
|
||||
turns = cableLen / (PI * currentDiameter);
|
||||
travelMm = turns * D_CABLE;
|
||||
travelStepsExact = travelMm * STEPPER_STEPS_PER_MM + travelStepsPartial; //convert mm to steps and add not moved partial steps
|
||||
travelStepsPartial = 0;
|
||||
travelStepsFull = (int)travelStepsExact;
|
||||
|
||||
//move axis when ready to move at least 1 step
|
||||
//move axis when ready to move at least 1 full step
|
||||
if (abs(travelStepsFull) > 1){
|
||||
travelStepsPartial = fmod(travelStepsExact, 1); //save remaining partial steps to be added in the next iteration
|
||||
ESP_LOGD(TAG, "cablelen=%.2lf, turns=%.2lf, travelMm=%.3lf, travelStepsExact: %.3lf, travelStepsFull=%d, partialStep=%.3lf", cableLen, turns, travelMm, travelStepsExact, travelStepsFull, travelStepsPartial);
|
||||
ESP_LOGI(TAG, "MOVING %d steps", travelStepsFull);
|
||||
//TODO: calculate variable speed for smoother movement? for example intentionally lag behind and calculate speed according to buffered data
|
||||
step.setSpeedMm(SPEED, ACCEL_MS, DECEL_MS);
|
||||
//testing: get speed from poti
|
||||
//step.setSpeedMm(35, 1000*potiModifier+1, 1000*potiModifier+1);
|
||||
ESP_LOGI(TAG, "dCablelen=%.2lf, dTurns=%.2lf, travelMm=%.3lf, StepsExact: %.3lf, StepsFull=%d, StepsPartial=%.3lf, totalLayerCount=%d, diameter=%.1f", cableLen, turns, travelMm, travelStepsExact, travelStepsFull, travelStepsPartial, layerCount, currentDiameter);
|
||||
ESP_LOGD(TAG, "MOVING %d steps", travelStepsFull);
|
||||
travelSteps(travelStepsExact);
|
||||
encStepsPrev = encStepsNow; //update previous length
|
||||
}
|
||||
else {
|
||||
//TODO use encoder queue to only run this check at encoder event?
|
||||
vTaskDelay(2);
|
||||
}
|
||||
vTaskDelay(5);
|
||||
}
|
||||
vTaskDelay(5 / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
||||
|
@ -10,3 +10,21 @@ void task_stepper_test(void *pvParameter);
|
||||
//task that initializes and controls the stepper motor
|
||||
// - moves stepper according to encoder movement
|
||||
void task_stepper_ctl(void *pvParameter);
|
||||
|
||||
|
||||
//tell stepper-control task to move cable guide to zero position
|
||||
void guide_moveToZero();
|
||||
|
||||
|
||||
// return local variable posNow that stores the current position of cable guide axis in steps
|
||||
// needed by shutdown to store last axis position in nvs
|
||||
int guide_getAxisPosSteps();
|
||||
|
||||
// set custom winding width (axis position the guide returns in mm)
|
||||
void guide_setWindingWidth(uint8_t maxPosMm);
|
||||
|
||||
// get currently configured winding width (axis position the guide returns in mm)
|
||||
uint8_t guide_getWindingWidth();
|
||||
|
||||
// calculate dynamic winding width in mm from cable length in mm according to fixed thresholds
|
||||
uint8_t guide_targetLength2WindingWidth(int lenMm);
|
@ -8,28 +8,38 @@ extern "C"
|
||||
#include "esp_system.h"
|
||||
#include "esp_log.h"
|
||||
#include "driver/adc.h"
|
||||
|
||||
}
|
||||
|
||||
#include "config.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
#include "control.hpp"
|
||||
#include "buzzer.hpp"
|
||||
#include "switchesAnalog.hpp"
|
||||
#include "guide-stepper.hpp"
|
||||
#include "encoder.hpp"
|
||||
#include "shutdown.hpp"
|
||||
|
||||
#include "stepper.hpp"
|
||||
|
||||
|
||||
//=================================
|
||||
//=========== functions ===========
|
||||
//=================================
|
||||
|
||||
//------------------------
|
||||
//--- configure output ---
|
||||
//function to configure gpio pin as output
|
||||
//------------------------
|
||||
//configure a gpio pin as output
|
||||
void gpio_configure_output(gpio_num_t gpio_pin){
|
||||
gpio_pad_select_gpio(gpio_pin);
|
||||
gpio_set_direction(gpio_pin, GPIO_MODE_OUTPUT);
|
||||
}
|
||||
|
||||
|
||||
//--- init gpios ---
|
||||
//--------------------
|
||||
//---- init gpios ----
|
||||
//--------------------
|
||||
void init_gpios(){
|
||||
//--- outputs ---
|
||||
//4x stepper mosfets
|
||||
@ -51,6 +61,8 @@ void init_gpios(){
|
||||
//initialize and configure ADC
|
||||
adc1_config_width(ADC_WIDTH_BIT_12); //=> max resolution 4096
|
||||
adc1_config_channel_atten(ADC_CHANNEL_POTI, ADC_ATTEN_DB_11); //max voltage
|
||||
|
||||
adc1_config_channel_atten(ADC_CHANNEL_SUPPLY_VOLTAGE, ADC_ATTEN_DB_11); //max voltage
|
||||
}
|
||||
|
||||
|
||||
@ -72,33 +84,41 @@ void task_buzzer( void * pvParameters ){
|
||||
//======================================
|
||||
extern "C" void app_main()
|
||||
{
|
||||
//init outputs
|
||||
//init outputs and adc
|
||||
init_gpios();
|
||||
|
||||
//enable 5V volate regulator
|
||||
//enable 5V volage regulator (needed for display)
|
||||
gpio_set_level(GPIO_NUM_17, 1);
|
||||
|
||||
//init encoder (global)
|
||||
encoder_queue = encoder_init();
|
||||
|
||||
//define loglevel
|
||||
esp_log_level_set("*", ESP_LOG_INFO);
|
||||
esp_log_level_set("*", ESP_LOG_INFO); //default loglevel
|
||||
esp_log_level_set("buzzer", ESP_LOG_ERROR);
|
||||
esp_log_level_set("switches-analog", ESP_LOG_WARN);
|
||||
esp_log_level_set("control", ESP_LOG_INFO);
|
||||
esp_log_level_set("stepper", ESP_LOG_DEBUG);
|
||||
esp_log_level_set("DendoStepper", ESP_LOG_DEBUG); //stepper lib
|
||||
esp_log_level_set("stepper-driver", ESP_LOG_WARN);
|
||||
esp_log_level_set("stepper-ctrl", ESP_LOG_WARN);
|
||||
esp_log_level_set("Dendostepper", ESP_LOG_WARN); //stepper lib
|
||||
esp_log_level_set("calc", ESP_LOG_WARN); //stepper lib
|
||||
esp_log_level_set("lowVoltage", ESP_LOG_INFO);
|
||||
|
||||
#ifdef STEPPER_TEST
|
||||
//create task for stepper testing
|
||||
xTaskCreate(task_stepper_test, "task_stepper_test", configMINIMAL_STACK_SIZE * 3, NULL, 5, NULL);
|
||||
//create task for testing the stepper motor
|
||||
xTaskCreate(task_stepper_test, "task_stepper_test", configMINIMAL_STACK_SIZE * 3, NULL, 2, NULL);
|
||||
//xTaskCreate(task_stepper_debug, "task_stepper_test", configMINIMAL_STACK_SIZE * 3, NULL, 2, NULL);
|
||||
#else
|
||||
//create task for controlling the machine
|
||||
xTaskCreate(task_control, "task_control", configMINIMAL_STACK_SIZE * 3, NULL, 5, NULL);
|
||||
//create task for detecting power-off
|
||||
xTaskCreate(&task_shutDownDetection, "task_shutdownDet", 2048, NULL, 2, NULL);
|
||||
// wait for nvs to be initialized in shutDownDetection task
|
||||
vTaskDelay(50 / portTICK_PERIOD_MS);
|
||||
|
||||
//create task for controlling the machine
|
||||
xTaskCreate(task_stepper_ctl, "task_stepper_ctl", configMINIMAL_STACK_SIZE * 5, NULL, 5, NULL);
|
||||
xTaskCreate(task_control, "task_control", configMINIMAL_STACK_SIZE * 3, NULL, 4, NULL);
|
||||
|
||||
//create task for controlling the stepper motor (linear axis that guids the cable)
|
||||
xTaskCreate(task_stepper_ctl, "task_stepper_ctl", configMINIMAL_STACK_SIZE * 3, NULL, 2, NULL);
|
||||
#endif
|
||||
|
||||
//create task for handling the buzzer
|
||||
|
120
main/shutdown.cpp
Normal file
120
main/shutdown.cpp
Normal file
@ -0,0 +1,120 @@
|
||||
extern "C"
|
||||
{
|
||||
#include <stdio.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include "esp_system.h"
|
||||
#include "esp_log.h"
|
||||
#include "driver/adc.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "nvs.h"
|
||||
}
|
||||
|
||||
#include "config.h"
|
||||
#include "shutdown.hpp"
|
||||
|
||||
#include "guide-stepper.hpp"
|
||||
|
||||
#define ADC_LOW_VOLTAGE_THRESHOLD 3200 // adc value where shut down is detected (store certain values before complete power loss)
|
||||
|
||||
static const char *TAG = "lowVoltage"; // tag for logging
|
||||
nvs_handle_t nvsHandle; // access nvs that was opened once, in any function
|
||||
|
||||
|
||||
|
||||
// store a u32 value in nvs as "lastPosSteps"
|
||||
void nvsWriteLastAxisPos(uint32_t value)
|
||||
{
|
||||
// update nvs value
|
||||
esp_err_t err = nvs_set_u32(nvsHandle, "lastPosSteps", value);
|
||||
if (err != ESP_OK)
|
||||
ESP_LOGE(TAG, "nvs: failed writing");
|
||||
err = nvs_commit(nvsHandle);
|
||||
if (err != ESP_OK)
|
||||
ESP_LOGE(TAG, "nvs: failed committing updates");
|
||||
else
|
||||
ESP_LOGI(TAG, "nvs: successfully committed updates");
|
||||
ESP_LOGW(TAG, "updated value in nvs to %d", value);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// read "lastPosSteps" from nvs, returns -1 if failed
|
||||
int nvsReadLastAxisPosSteps()
|
||||
{
|
||||
uint32_t valueRead;
|
||||
esp_err_t err = nvs_get_u32(nvsHandle, "lastPosSteps", &valueRead);
|
||||
switch (err)
|
||||
{
|
||||
case ESP_OK:
|
||||
ESP_LOGW(TAG, "Successfully read value %d from nvs", valueRead);
|
||||
return valueRead;
|
||||
break;
|
||||
case ESP_ERR_NVS_NOT_FOUND:
|
||||
ESP_LOGE(TAG, "nvs: the value '%s' is not initialized yet", "lastPosSteps");
|
||||
return -1;
|
||||
break;
|
||||
default:
|
||||
ESP_LOGE(TAG, "Error (%s) reading nvs!", esp_err_to_name(err));
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// task that repeatedly checks supply voltage (12V) and saves certain values to nvs in case of power off detected
|
||||
// note: with the 2200uF capacitor in the 12V supply and measuring if 12V start do drop here, there is more than enough time to take action until the 3v3 regulator turns off
|
||||
void task_shutDownDetection(void *pvParameter)
|
||||
{
|
||||
//--- Initialize NVS ---
|
||||
ESP_LOGW(TAG, "initializing nvs...");
|
||||
esp_err_t err = nvs_flash_init();
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
|
||||
{
|
||||
ESP_LOGE(TAG, "NVS truncated -> deleting flash");
|
||||
// Retry nvs_flash_init
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
err = nvs_flash_init();
|
||||
}
|
||||
|
||||
//--- open nvs-flash ---
|
||||
ESP_LOGW(TAG, "opening NVS-handle...");
|
||||
// create handle available for all functions in this file
|
||||
err = nvs_open("storage", NVS_READWRITE, &nvsHandle);
|
||||
if (err != ESP_OK)
|
||||
ESP_LOGE(TAG, "Error (%s) opening NVS handle!\n", esp_err_to_name(err));
|
||||
|
||||
// read stored value (returns 0 if unitialized/failed)
|
||||
//int lastPosSteps = nvsReadLastAxisPosSteps();
|
||||
//ESP_LOGW(TAG, "=> read value %d from nvs (stored at last shutdown)", lastPosSteps);
|
||||
|
||||
// repeatedly read ADC and check if below low voltage threshold
|
||||
bool voltageBelowThreshold = false;
|
||||
while (1) //TODO limit save frequency in case voltage repeadedly varys between threshold for some reason (e.g. offset drift)
|
||||
{
|
||||
// read adc
|
||||
int adc_reading = adc1_get_raw(ADC_CHANNEL_SUPPLY_VOLTAGE);
|
||||
|
||||
// evaulate threshold
|
||||
if (adc_reading < ADC_LOW_VOLTAGE_THRESHOLD) // below threshold => POWER SHUTDOWN DETECTED
|
||||
{
|
||||
// write to nvs and log once at change to below
|
||||
if (!voltageBelowThreshold){
|
||||
nvsWriteLastAxisPos(guide_getAxisPosSteps());
|
||||
ESP_LOGE(TAG, "voltage now below threshold! now=%d threshold=%d -> wrote last axis-pos to nvs", adc_reading, ADC_LOW_VOLTAGE_THRESHOLD);
|
||||
voltageBelowThreshold = true;
|
||||
}
|
||||
}
|
||||
else if (voltageBelowThreshold) // above threshold and previously below
|
||||
{
|
||||
// log at change to above
|
||||
ESP_LOGE(TAG, "voltage above threshold again: %d > %d - issue with power supply, or too threshold too high?", adc_reading, ADC_LOW_VOLTAGE_THRESHOLD);
|
||||
voltageBelowThreshold = false;
|
||||
}
|
||||
|
||||
// always log for debugging/calibrating
|
||||
ESP_LOGD(TAG, "read adc battery voltage: %d", adc_reading);
|
||||
|
||||
vTaskDelay(30 / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
7
main/shutdown.hpp
Normal file
7
main/shutdown.hpp
Normal file
@ -0,0 +1,7 @@
|
||||
|
||||
// task that repeatedly checks supply voltage (12V) and saves certain values to nvs in case of it drops below a certain threshold (power off detected)
|
||||
void task_shutDownDetection(void *pvParameter);
|
||||
|
||||
// read last axis position in steps from nvs
|
||||
// returns -1 when reading from nvs failed
|
||||
int nvsReadLastAxisPosSteps();
|
304
main/stepper.cpp
Normal file
304
main/stepper.cpp
Normal file
@ -0,0 +1,304 @@
|
||||
//custom driver for stepper motor
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
#include "hal/timer_types.h"
|
||||
#include <cstdint>
|
||||
#include <inttypes.h>
|
||||
|
||||
extern "C" {
|
||||
#include "driver/timer.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "esp_log.h"
|
||||
}
|
||||
|
||||
|
||||
//=====================
|
||||
//=== configuration ===
|
||||
//=====================
|
||||
//used macros from config.h:
|
||||
//#define STEPPER_STEP_PIN GPIO_NUM_18 //mos1
|
||||
//#define STEPPER_DIR_PIN GPIO_NUM_16 //ST3
|
||||
|
||||
//#define STEPPER_STEPS_PER_MM 200/2 //steps/mm (steps-per-rot / slope)
|
||||
//#define STEPPER_SPEED_DEFAULT 20 //mm/s
|
||||
//#define STEPPER_SPEED_MIN 4 //mm/s - speed threshold at which stepper immediately starts/stops
|
||||
//#define STEPPER_ACCEL_INC 3 //steps/s increment per cycle
|
||||
//#define STEPPER_DECEL_INC 8 //steps/s decrement per cycle
|
||||
|
||||
#define TIMER_F 1000000ULL
|
||||
#define TICK_PER_S TIMER_S
|
||||
#define NS_TO_T_TICKS(x) (x)
|
||||
|
||||
|
||||
|
||||
//========================
|
||||
//=== global variables ===
|
||||
//========================
|
||||
static const char *TAG = "stepper-driver"; //tag for logging
|
||||
|
||||
bool direction = 1;
|
||||
bool directionTarget = 1;
|
||||
bool timerIsRunning = false;
|
||||
bool timer_isr(void *arg);
|
||||
|
||||
static timer_group_t timerGroup = TIMER_GROUP_0;
|
||||
static timer_idx_t timerIdx = TIMER_0;
|
||||
|
||||
//TODO the below variables can be moved to isr function once debug output is no longer needed
|
||||
static uint64_t posTarget = 0;
|
||||
static uint64_t posNow = 0;
|
||||
static uint64_t stepsToGo = 0;
|
||||
static uint32_t speedMin = STEPPER_SPEED_MIN * STEPPER_STEPS_PER_MM;
|
||||
static uint32_t speedNow = speedMin;
|
||||
static int debug = 0;
|
||||
static uint32_t speedTarget = STEPPER_SPEED_DEFAULT * STEPPER_STEPS_PER_MM;
|
||||
//TODO/NOTE increment actually has to be re-calculated every run to have linear accel (because also gets called faster/slower)
|
||||
static uint32_t decel_increment = STEPPER_DECEL_INC;
|
||||
static uint32_t accel_increment = STEPPER_ACCEL_INC;
|
||||
|
||||
|
||||
|
||||
//======================
|
||||
//===== DEBUG task =====
|
||||
//======================
|
||||
void task_stepper_debug(void *pvParameter){
|
||||
while (1){
|
||||
ESP_LOGI("stepper-DEBUG",
|
||||
"timer=%d "
|
||||
"dir=%d "
|
||||
"dirTarget=%d "
|
||||
"posTarget=%llu "
|
||||
"posNow=%llu "
|
||||
"stepsToGo=%llu "
|
||||
"speedNow=%u "
|
||||
"speedTarget=%u "
|
||||
"debug=%d ",
|
||||
|
||||
timerIsRunning,
|
||||
direction,
|
||||
directionTarget,
|
||||
posTarget,
|
||||
posNow,
|
||||
stepsToGo,
|
||||
speedNow,
|
||||
speedTarget,
|
||||
debug
|
||||
);
|
||||
|
||||
vTaskDelay(300 / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//=====================
|
||||
//===== set speed =====
|
||||
//=====================
|
||||
void stepper_setSpeed(uint32_t speedMmPerS) {
|
||||
ESP_LOGI(TAG, "set target speed from %u to %u mm/s (%u steps/s)",
|
||||
speedTarget, speedMmPerS, speedMmPerS * STEPPER_STEPS_PER_MM);
|
||||
speedTarget = speedMmPerS * STEPPER_STEPS_PER_MM;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//==========================
|
||||
//== set target pos STEPS ==
|
||||
//==========================
|
||||
void stepper_setTargetPosSteps(uint64_t target_steps) {
|
||||
ESP_LOGI(TAG, "update target position from %llu to %llu steps (stepsNow: %llu", posTarget, target_steps, posNow);
|
||||
posTarget = target_steps;
|
||||
|
||||
// Check if the timer is currently paused
|
||||
if (!timerIsRunning){
|
||||
// If the timer is paused, start it again with the updated targetSteps
|
||||
timerIsRunning = true;
|
||||
ESP_LOGI(TAG, "starting timer");
|
||||
ESP_ERROR_CHECK(timer_set_alarm_value(timerGroup, timerIdx, 1000));
|
||||
//timer_set_counter_value(timerGroup, timerIdx, 1000);
|
||||
ESP_ERROR_CHECK(timer_start(timerGroup, timerIdx));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//=========================
|
||||
//=== set target pos MM ===
|
||||
//=========================
|
||||
void stepper_setTargetPosMm(uint32_t posMm){
|
||||
ESP_LOGI(TAG, "set target position to %u mm", posMm);
|
||||
stepper_setTargetPosSteps(posMm * STEPPER_STEPS_PER_MM);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//=======================
|
||||
//===== waitForStop =====
|
||||
//=======================
|
||||
//delay until stepper is stopped, optional timeout in ms, 0 = no limit
|
||||
void stepper_waitForStop(uint32_t timeoutMs){
|
||||
ESP_LOGI(TAG, "waiting for stepper to stop...");
|
||||
uint32_t timestampStart = esp_log_timestamp();
|
||||
while (timerIsRunning) {
|
||||
if ( (esp_log_timestamp() - timestampStart) >= timeoutMs && timeoutMs != 0){
|
||||
ESP_LOGE(TAG, "timeout waiting for stepper to stop");
|
||||
return;
|
||||
}
|
||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||
}
|
||||
ESP_LOGI(TAG, "finished waiting stepper to stop");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//======================
|
||||
//======== home ========
|
||||
//======================
|
||||
//define zero/start position
|
||||
//run to limit and define zero/start position.
|
||||
//Currently simply runs stepper for travelMm and bumps into hardware limit
|
||||
void stepper_home(uint32_t travelMm){
|
||||
//TODO add timeout, limitswitch...
|
||||
ESP_LOGW(TAG, "initiate auto-home, moving %d mm...", travelMm);
|
||||
posNow = travelMm * STEPPER_STEPS_PER_MM;
|
||||
while (posNow != 0){
|
||||
//reactivate just in case stopped by other call to prevent deadlock
|
||||
if (!timerIsRunning) {
|
||||
stepper_setTargetPosSteps(0);
|
||||
}
|
||||
vTaskDelay(100 / portTICK_PERIOD_MS);
|
||||
}
|
||||
ESP_LOGW(TAG, "finished auto-home");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//========================
|
||||
//===== init stepper =====
|
||||
//========================
|
||||
void stepper_init(){
|
||||
ESP_LOGI(TAG, "init - configure struct...");
|
||||
|
||||
// Configure pulse and direction pins as outputs
|
||||
ESP_LOGI(TAG, "init - configure gpio pins...");
|
||||
gpio_set_direction(STEPPER_DIR_PIN, GPIO_MODE_OUTPUT);
|
||||
gpio_set_direction(STEPPER_STEP_PIN, GPIO_MODE_OUTPUT);
|
||||
|
||||
ESP_LOGI(TAG, "init - initialize/configure timer...");
|
||||
timer_config_t timer_conf = {
|
||||
.alarm_en = TIMER_ALARM_EN, // we need alarm
|
||||
.counter_en = TIMER_PAUSE, // dont start now lol
|
||||
.intr_type = TIMER_INTR_LEVEL, // interrupt
|
||||
.counter_dir = TIMER_COUNT_UP, // count up duh
|
||||
.auto_reload = TIMER_AUTORELOAD_EN, // reload pls
|
||||
.divider = 80000000ULL / TIMER_F, // ns resolution
|
||||
};
|
||||
ESP_ERROR_CHECK(timer_init(timerGroup, timerIdx, &timer_conf)); // init the timer
|
||||
ESP_ERROR_CHECK(timer_set_counter_value(timerGroup, timerIdx, 0)); // set it to 0
|
||||
ESP_ERROR_CHECK(timer_isr_callback_add(timerGroup, timerIdx, timer_isr, (void *)timerIdx, 0));
|
||||
}
|
||||
|
||||
|
||||
|
||||
//================================
|
||||
//=== timer interrupt function ===
|
||||
//================================
|
||||
bool timer_isr(void *arg) {
|
||||
|
||||
//-----------------
|
||||
//--- variables ---
|
||||
//-----------------
|
||||
//TODO used (currently global) variables here
|
||||
|
||||
//-----------------------------------
|
||||
//--- define direction, stepsToGo ---
|
||||
//-----------------------------------
|
||||
//Note: the idea is that the stepper has to decelerate to min speed first before changeing the direction
|
||||
//define target direction depending on position difference
|
||||
bool directionTarget = posTarget > posNow ? 1 : 0;
|
||||
//DIRECTION DIFFERS (change)
|
||||
if ( (direction != directionTarget) && (posTarget != posNow)) {
|
||||
if (stepsToGo == 0){ //standstill
|
||||
direction = directionTarget; //switch direction
|
||||
gpio_set_level(STEPPER_DIR_PIN, direction);
|
||||
stepsToGo = abs(int64_t(posTarget - posNow));
|
||||
} else {
|
||||
//set to minimun decel steps
|
||||
stepsToGo = (speedNow - speedMin) / decel_increment;
|
||||
}
|
||||
}
|
||||
//NORMAL (any direction 0/1)
|
||||
else {
|
||||
stepsToGo = abs(int64_t(posTarget - posNow));
|
||||
}
|
||||
|
||||
//--------------------
|
||||
//--- define speed ---
|
||||
//--------------------
|
||||
//FIXME noticed crash: division by 0 when min speed > target speed
|
||||
uint64_t stepsDecelRemaining = (speedNow - speedMin) / decel_increment;
|
||||
//DECELERATE
|
||||
|
||||
//prevent hard stop (faster stop than decel ramp)
|
||||
//Idea: when target gets lowered while decelerating,
|
||||
// move further than target to not exceed decel ramp (overshoot),
|
||||
// then change dir and move back to actual target pos
|
||||
if (stepsToGo < stepsDecelRemaining/2){ //significantly less steps planned to comply with decel ramp
|
||||
stepsToGo = stepsDecelRemaining; //set to required steps
|
||||
}
|
||||
|
||||
if (stepsToGo <= stepsDecelRemaining) {
|
||||
if ((speedNow - speedMin) > decel_increment) {
|
||||
speedNow -= decel_increment;
|
||||
} else {
|
||||
speedNow = speedMin; //PAUSE HERE??? / irrelevant?
|
||||
}
|
||||
}
|
||||
//ACCELERATE
|
||||
else if (speedNow < speedTarget) {
|
||||
speedNow += accel_increment;
|
||||
if (speedNow > speedTarget) speedNow = speedTarget;
|
||||
}
|
||||
//COASTING
|
||||
else { //not relevant?
|
||||
speedNow = speedTarget;
|
||||
}
|
||||
|
||||
//-------------------------------
|
||||
//--- update timer, increment ---
|
||||
//-------------------------------
|
||||
//AT TARGET -> STOP
|
||||
if (stepsToGo == 0) {
|
||||
timer_pause(timerGroup, timerIdx);
|
||||
timerIsRunning = false;
|
||||
speedNow = speedMin;
|
||||
return 1;
|
||||
}
|
||||
|
||||
//STEPS REMAINING -> NEXT STEP
|
||||
//update timer with new speed
|
||||
ESP_ERROR_CHECK(timer_set_alarm_value(timerGroup, timerIdx, TIMER_F / speedNow));
|
||||
|
||||
//generate pulse
|
||||
GPIO.out_w1ts = (1ULL << STEPPER_STEP_PIN); //turn on (fast)
|
||||
ets_delay_us(10);
|
||||
GPIO.out_w1tc = (1ULL << STEPPER_STEP_PIN); //turn off (fast)
|
||||
|
||||
//increment pos
|
||||
stepsToGo --;
|
||||
if (direction == 1){
|
||||
posNow ++;
|
||||
} else {
|
||||
//prevent underflow FIXME this case should not happen in the first place?
|
||||
if (posNow != 0){
|
||||
posNow --;
|
||||
} else {
|
||||
ESP_LOGE(TAG,"isr: posNow would be negative - ignoring decrement");
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
25
main/stepper.hpp
Normal file
25
main/stepper.hpp
Normal file
@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
//init stepper pins and timer
|
||||
void stepper_init();
|
||||
|
||||
//delay until stepper is stopped, optional timeout in ms, 0 = no limit
|
||||
void stepper_waitForStop(uint32_t timeoutMs = 0);
|
||||
|
||||
//run to limit and define zero/start position. (busy until finished)
|
||||
//Currently simply runs stepper for travelMm and bumps into hardware limit
|
||||
void stepper_home(uint32_t travelMm = 60);
|
||||
|
||||
//set absolute target position in steps
|
||||
void stepper_setTargetPosSteps(uint64_t steps);
|
||||
|
||||
//set absolute target position in millimeters
|
||||
void stepper_setTargetPosMm(uint32_t posMm);
|
||||
|
||||
//set target speed in millimeters per second
|
||||
void stepper_setSpeed(uint32_t speedMmPerS);
|
||||
|
||||
|
||||
|
||||
//task that periodically logs variables for debugging stepper driver
|
||||
void task_stepper_debug(void *pvParameter);
|
@ -1,4 +1,6 @@
|
||||
#include "switchesAnalog.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
|
||||
#define CHECK_BIT(var,pos) (((var)>>(pos)) & 1) //TODO duplicate code: same macro already used in vfd.cpp
|
||||
|
||||
|
@ -8,7 +8,6 @@ extern "C"
|
||||
#include <math.h>
|
||||
}
|
||||
|
||||
#include "config.hpp"
|
||||
#include "gpio_adc.hpp"
|
||||
|
||||
|
||||
|
@ -1,4 +1,6 @@
|
||||
#include "vfd.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
|
||||
#define CHECK_BIT(var,pos) (((var)>>(pos)) & 1)
|
||||
|
||||
|
@ -9,7 +9,6 @@ extern "C"
|
||||
#include "esp_log.h"
|
||||
}
|
||||
|
||||
#include "config.hpp"
|
||||
|
||||
//enum defining motor direction
|
||||
typedef enum vfd_direction_t {FWD, REV} vfd_direction_t;
|
||||
|
Loading…
x
Reference in New Issue
Block a user