Compare commits
126 Commits
encoder-te
...
main
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 | ||
|
279ac0e07e | ||
|
1c59e0097b | ||
|
5d7c67ab9a | ||
|
8d2428d285 | ||
|
dc6deeb3d0 | ||
|
0a05340763 | ||
|
45409676a0 | ||
|
de42b6252e | ||
|
a0032ea07f | ||
|
9595940004 | ||
|
423348be9f | ||
|
6c9b1b6fcf | ||
|
4edd1780ea | ||
|
28889bd912 | ||
|
226aa4794c | ||
|
118e9714b5 | ||
|
ac4ca5450a | ||
|
5dd392586d | ||
|
74adcbc78a | ||
|
0ede3dbfa8 | ||
|
06ebb1fbc6 | ||
|
a89d3a1f8c | ||
|
3d4f327832 | ||
|
58c5a92d1e | ||
|
2651a83ce7 | ||
|
ef0ac39c9b | ||
|
ad2ce8c33b | ||
|
8f5b33c554 | ||
|
592351c265 | ||
|
d473bf6b8c | ||
|
4cb6b41a6b | ||
|
bf87be2590 | ||
|
63706e4aa7 | ||
|
5b49406cb8 | ||
|
2cf1762569 | ||
|
826dd983c4 | ||
|
bb7cdddc6c | ||
|
8a265c2bae | ||
|
6dfa47e3e8 | ||
|
2f86fbeb80 | ||
|
9b386c3d73 | ||
|
992d852189 | ||
|
824bad930e | ||
|
ced7cda002 | ||
|
6242d6a5fc | ||
|
59df1a9aa2 | ||
|
3a99b8bc5c | ||
|
451981b165 | ||
|
1f53fabd19 | ||
|
d2d85952df | ||
|
38ad266488 | ||
|
a932460924 | ||
|
09ee67f583 | ||
|
f52a58aa1c | ||
|
fab75661c2 | ||
|
9600932ae8 | ||
|
bb22fb340d | ||
|
7eb06fe228 | ||
|
5a3c6b15bc | ||
|
248668c526 | ||
|
9d416d29e6 | ||
|
070fd7069d | ||
|
c1a12d93f0 | ||
|
92f7299080 | ||
|
2e331d841d | ||
|
9f329101a1 | ||
|
4e2cc070d1 | ||
|
586c335896 | ||
|
6acf99d894 | ||
|
9665560bbb | ||
|
c8ffd94fe9 | ||
|
c5438b6c4c | ||
|
01c5db39c1 | ||
|
b238e582cc | ||
|
ae41b93e63 | ||
|
5ddf8699e2 | ||
|
8900da9113 | ||
|
68f97644be | ||
|
e9e1df9ea1 | ||
|
dddd54b03a | ||
|
f6b2093650 | ||
|
68dc012fcc | ||
|
8b9b5ff736 | ||
|
0aea494783 | ||
|
7ccde65893 | ||
|
59bb48902d | ||
|
b68dae7e59 | ||
|
7fae539f14 | ||
|
22f8aef8d2 | ||
|
739f5ef4c2 | ||
|
a3f3cb340c |
1
.gitattributes
vendored
Normal file
@ -0,0 +1 @@
|
||||
*.fcstd text
|
23
.gitignore
vendored
@ -1,6 +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)
|
||||
|
94
README.md
Normal file
@ -0,0 +1,94 @@
|
||||
# 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
|
||||
### 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"
|
||||
- Size: 38*35.5mm/1.49*1.39"
|
||||
- Output :AB 2phase output rectangular orthogonal pulse circuit, the output for the NPN open collector output type
|
||||
- Maximum mechanical speed: 5000 R / min
|
||||
- Response frequency: 0-20KHz
|
||||
- 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/box/box-holder_v1.0.FCStd
Normal file
BIN
cad/box/box_v1.0.FCStd
Normal file
2356
cad/box/panel.svg
Normal file
After Width: | Height: | Size: 67 KiB |
BIN
cad/cable-mounts/clamps-startButtons.FCStd
Normal file
BIN
cad/cable-mounts/mounts-item.FCStd
Normal file
BIN
cad/cnc-guide/axis-mount.stl
Normal file
BIN
cad/cnc-guide/axis_mounts.FCStd
Normal file
BIN
cad/cutter/angle-bracket_v2.0.FCStd
Normal file
BIN
cad/cutter/cutter-mount_2.2.FCStd
Normal file
BIN
cad/emergency-sw/sw_holder_v1.0.FCStd
Normal file
BIN
cad/encoder/disk-flat_SE.par
Normal file
BIN
cad/encoder/disk-flat_SE.stl
Normal file
BIN
cad/encoder/disk-half_SE.par
Normal file
BIN
cad/encoder/disk-half_SE.stl
Normal file
BIN
cad/encoder/holder_v1.0.FCStd
Normal file
BIN
cad/encoder/holder_v2.0.FCStd
Normal file
BIN
cad/encoder/holder_v3.2.FCStd
Normal file
4
cad/export/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
# Ignore everything in this directory
|
||||
*
|
||||
# Except this file
|
||||
!.gitignore
|
BIN
cad/guides/distance-rings.FCStd
Normal file
BIN
cad/guides/guide-cutter_spacer.FCStd
Normal file
BIN
cad/guides/guide-cutter_v1.0.FCStd
Normal file
BIN
cad/guides/guide-cutter_v2.0.FCStd
Normal file
BIN
cad/guides/guide-cutter_v3.0.FCStd
Normal file
BIN
cad/guides/guide-cutter_v4.2.FCStd
Normal file
BIN
cad/guides/guide-cutter_v5.0.FCStd
Normal file
BIN
cad/guides/guide-cutter_v5.1.FCStd
Normal file
BIN
cad/guides/guide-in-long-rolls_SE.par
Normal file
BIN
cad/guides/guide-in-long-rolls_SE.stl
Normal file
BIN
cad/guides/guide-in-long_SE.par
Normal file
BIN
cad/guides/guide-in-long_SE.stl
Normal file
BIN
cad/guides/guide-in_v1.0.FCStd
Normal file
BIN
cad/guides/guide-in_v1.1.FCStd
Normal file
BIN
cad/guides/guide-in_v2.1.FCStd
Normal file
BIN
cad/reel/cable-reel_v1_SE.par
Normal file
BIN
cad/reel/cable-reel_v1_SE.stl
Normal file
BIN
cad/reel/cable-reel_v2.1.FCStd
Normal file
BIN
cad/reel/cable-reel_v2.2.2.FCStd
Normal file
BIN
cad/reel/cable-reel_v2.2.FCStd
Normal file
1
components/DendoStepper/CMakeLists.txt
Normal file
@ -0,0 +1 @@
|
||||
idf_component_register(SRCS DendoStepper.cpp INCLUDE_DIRS include)
|
413
components/DendoStepper/DendoStepper.cpp
Normal file
@ -0,0 +1,413 @@
|
||||
#include "DendoStepper.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
#define STEP_DEBUG
|
||||
|
||||
#ifdef STEP_DEBUG
|
||||
#define STEP_LOGI(...) ESP_LOGI(__VA_ARGS__)
|
||||
#define STEP_LOGW(...) ESP_LOGW(__VA_ARGS__)
|
||||
#define STEP_LOGE(...) ESP_LOGE(__VA_ARGS__)
|
||||
#else
|
||||
#define STEP_LOGI(...) while (0)
|
||||
#define STEP_LOGW(...) while (0)
|
||||
#define STEP_LOGE(...) ESP_LOGE(__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
bool state = 0;
|
||||
|
||||
// PUBLIC definitions
|
||||
|
||||
DendoStepper::DendoStepper()
|
||||
{
|
||||
}
|
||||
|
||||
void DendoStepper::config(DendoStepper_config_t *config)
|
||||
{
|
||||
memcpy(&conf, config, sizeof(conf));
|
||||
}
|
||||
|
||||
void DendoStepper::disableMotor()
|
||||
{
|
||||
setEn(true);
|
||||
STEP_LOGI("DendoStepper", "Disabled");
|
||||
ctrl.status = DISABLED;
|
||||
}
|
||||
|
||||
void DendoStepper::enableMotor()
|
||||
{
|
||||
setEn(false);
|
||||
ctrl.status = IDLE;
|
||||
STEP_LOGI("DendoStepper", "Enabled");
|
||||
timerStarted = 0;
|
||||
}
|
||||
|
||||
void DendoStepper::init(uint8_t stepP, uint8_t dirP, uint8_t enP, timer_group_t group, timer_idx_t index, microStepping_t microstepping = MICROSTEP_1, uint16_t stepsPerRot = 200)
|
||||
{
|
||||
conf.stepPin = stepP;
|
||||
conf.dirPin = dirP;
|
||||
conf.enPin = enP;
|
||||
conf.timer_group = group;
|
||||
conf.timer_idx = index;
|
||||
conf.miStep = microstepping;
|
||||
ctrl.status = 0;
|
||||
init();
|
||||
}
|
||||
|
||||
void DendoStepper::init()
|
||||
{
|
||||
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
|
||||
.pin_bit_mask = mask,
|
||||
.mode = GPIO_MODE_OUTPUT,
|
||||
.pull_up_en = GPIO_PULLUP_DISABLE,
|
||||
.pull_down_en = GPIO_PULLDOWN_DISABLE,
|
||||
.intr_type = GPIO_INTR_DISABLE,
|
||||
};
|
||||
// set the gpios as per gpio_conf
|
||||
ESP_ERROR_CHECK(gpio_config(&gpio_conf));
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
// calculate stepsPerRot
|
||||
ctrl.stepsPerRot = (360.0 / conf.stepAngle) * conf.miStep;
|
||||
|
||||
STEP_LOGI("DendoStepper", "Steps per one rotation:%d", ctrl.stepsPerRot);
|
||||
|
||||
if (conf.timer_group != TIMER_GROUP_MAX && conf.timer_idx != TIMER_MAX)
|
||||
{
|
||||
// timer was configured explixitly in config structure, we dont need to do it here
|
||||
goto timer_avail;
|
||||
}
|
||||
|
||||
// try to find free timer
|
||||
timer_config_t temp;
|
||||
for (int i = 0; i < 1; i++)
|
||||
{
|
||||
for (int j = 0; j < 1; j++)
|
||||
{
|
||||
timer_get_config((timer_group_t)i, (timer_idx_t)j, &temp);
|
||||
if (temp.alarm_en == TIMER_ALARM_DIS)
|
||||
{
|
||||
// if the alarm is disabled, chances are no other dendostepper instance is using it
|
||||
conf.timer_group = (timer_group_t)i;
|
||||
conf.timer_idx = (timer_idx_t)j;
|
||||
goto timer_avail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if we got here it means that there isnt any free timer available
|
||||
STEP_LOGE("DendoStepper", "No free timer available, this stepper wont work");
|
||||
return;
|
||||
|
||||
timer_avail:
|
||||
ESP_ERROR_CHECK(timer_init(conf.timer_group, conf.timer_idx, &timer_conf)); // init the timer
|
||||
ESP_ERROR_CHECK(timer_set_counter_value(conf.timer_group, conf.timer_idx, 0)); // set it to 0
|
||||
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();
|
||||
|
||||
if (!relative) // why would u call it with 0 wtf
|
||||
return ESP_ERR_NOT_SUPPORTED;
|
||||
|
||||
if (ctrl.status > IDLE) { //currently moving
|
||||
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
|
||||
ctrl.status = ACC;
|
||||
setDir(relative < 0); // set CCW if <0, else set CW
|
||||
calc(abs(relative)); // calculate velocity profile
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
esp_err_t DendoStepper::runPosMm(int32_t relative)
|
||||
{
|
||||
if (ctrl.stepsPerMm == 0)
|
||||
{
|
||||
STEP_LOGE("DendoStepper", "Steps per millimeter not set, cannot move!");
|
||||
}
|
||||
return runPos(relative * ctrl.stepsPerMm);
|
||||
}
|
||||
|
||||
esp_err_t DendoStepper::runAbs(uint32_t 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;
|
||||
|
||||
int32_t relativeSteps = 0;
|
||||
relativeSteps = (int32_t)position - currentPos;
|
||||
|
||||
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)
|
||||
{
|
||||
STEP_LOGE("DendoStepper", "Steps per millimeter not set, cannot move!");
|
||||
}
|
||||
return runAbs(position * ctrl.stepsPerMm);
|
||||
}
|
||||
|
||||
void DendoStepper::setSpeed(uint32_t speed, uint16_t accT, uint16_t decT)
|
||||
{
|
||||
ctrl.speed = speed;
|
||||
ctrl.acc = ctrl.speed / (accT / 4000.0);
|
||||
ctrl.dec = ctrl.speed / (decT / 4000.0);
|
||||
STEP_LOGI("DendoStepper", "Speed set: %d steps/s t+=%d s t-=%d s", speed, accT, decT);
|
||||
}
|
||||
|
||||
void DendoStepper::setSpeedMm(uint32_t speed, uint16_t accT, uint16_t decT)
|
||||
{
|
||||
if (ctrl.stepsPerMm == 0)
|
||||
{
|
||||
STEP_LOGE("DendoStepper", "Steps per millimeter not set, cannot set the speed!");
|
||||
}
|
||||
ctrl.speed = speed * ctrl.stepsPerMm;
|
||||
|
||||
ctrl.acc = ctrl.speed / (accT / 4000.0);
|
||||
ctrl.dec = ctrl.speed / (decT / 4000.0);
|
||||
STEP_LOGI("DendoStepper", "Speed set: v=%d mm/s t+=%d s t-=%d s", speed, accT, decT);
|
||||
}
|
||||
|
||||
//CUSTOM - change speed while running
|
||||
//FIXME: this approach does not work, since calc function would have to be run after change, this will mess up target steps...
|
||||
//void DendoStepper::changeSpeed(uint32_t speed)
|
||||
//{
|
||||
// //TODO reduce duplicate code (e.g. call setSpeed function)
|
||||
// //change speed
|
||||
// ctrl.speed = speed;
|
||||
// //change status to ACC/DEC
|
||||
// STEP_LOGI("DendoStepper", "Speed changed: from v=%.2f rad/s to v=%.2f rad/s", ctrl.speed, speed);
|
||||
// if (speed > ctrl.speed) ctrl.status = ACC;
|
||||
// if (speed < ctrl.speed) ctrl.status = DEC;
|
||||
//}
|
||||
//
|
||||
//void DendoStepper::changeSpeedMm(uint32_t speed)
|
||||
//{
|
||||
// //TODO reduce duplicate code (e.g. call setSpeedMm function)
|
||||
// if (ctrl.stepsPerMm == 0)
|
||||
// {
|
||||
// STEP_LOGE("DendoStepper", "Steps per millimeter not set, cannot set the speed!");
|
||||
// }
|
||||
// //calc new speed
|
||||
// float speedNew = speed * ctrl.stepsPerMm;
|
||||
// //change status to ACC/DEC
|
||||
// if (speedNew > ctl.speed) ctrl.status = ACC;
|
||||
// if (speedNew < ctl.speed) ctrl.status = DEC;
|
||||
// //update speed, log output
|
||||
// ctrl.speed = speedNew;
|
||||
// STEP_LOGI("DendoStepper", "Speed changed: from v=%.2f rad/s to v=%.2f rad/s", ctrl.speed, speedNew);
|
||||
//}
|
||||
|
||||
|
||||
void DendoStepper::setStepsPerMm(uint16_t steps)
|
||||
{
|
||||
ctrl.stepsPerMm = steps;
|
||||
}
|
||||
|
||||
uint16_t DendoStepper::getStepsPerMm()
|
||||
{
|
||||
return ctrl.stepsPerMm;
|
||||
}
|
||||
|
||||
uint8_t DendoStepper::getState()
|
||||
{
|
||||
return ctrl.status;
|
||||
}
|
||||
|
||||
uint64_t DendoStepper::getPosition()
|
||||
{
|
||||
return currentPos;
|
||||
}
|
||||
|
||||
uint64_t DendoStepper::getPositionMm()
|
||||
{
|
||||
return getPosition() / ctrl.stepsPerMm;
|
||||
}
|
||||
|
||||
void DendoStepper::resetAbsolute()
|
||||
{
|
||||
currentPos = 0;
|
||||
}
|
||||
|
||||
void DendoStepper::runInf(bool direction)
|
||||
{
|
||||
if (ctrl.status > IDLE)
|
||||
{
|
||||
STEP_LOGE("DendoStepper", "Motor is moving, this command will be ignored");
|
||||
return;
|
||||
}
|
||||
if (ctrl.status == DISABLED)
|
||||
{
|
||||
enableMotor();
|
||||
}
|
||||
ctrl.runInfinite = true;
|
||||
setDir(direction);
|
||||
calc(UINT32_MAX);
|
||||
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
|
||||
}
|
||||
|
||||
uint16_t DendoStepper::getSpeed()
|
||||
{
|
||||
return ctrl.speed;
|
||||
}
|
||||
|
||||
float DendoStepper::getAcc()
|
||||
{
|
||||
return ctrl.acc;
|
||||
}
|
||||
|
||||
void DendoStepper::stop()
|
||||
{
|
||||
if (ctrl.status <= IDLE)
|
||||
{
|
||||
return;
|
||||
}
|
||||
ctrl.runInfinite = false;
|
||||
timer_pause(conf.timer_group, conf.timer_idx); // stop the timer
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = IDLE;
|
||||
ctrl.stepCnt = 0;
|
||||
gpio_set_level((gpio_num_t)conf.stepPin, 0);
|
||||
}
|
||||
|
||||
// PRIVATE definitions
|
||||
|
||||
void DendoStepper::setEn(bool state)
|
||||
{
|
||||
ESP_ERROR_CHECK(gpio_set_level((gpio_num_t)conf.enPin, state));
|
||||
}
|
||||
|
||||
void DendoStepper::setDir(bool state)
|
||||
{
|
||||
ctrl.dir = state;
|
||||
ESP_ERROR_CHECK(gpio_set_level((gpio_num_t)conf.dirPin, state));
|
||||
}
|
||||
|
||||
/* Timer callback, used for generating pulses and calculating speed profile in real time */
|
||||
bool DendoStepper::xISR()
|
||||
{
|
||||
GPIO.out_w1ts = (1ULL << conf.stepPin);
|
||||
// add and substract one step
|
||||
|
||||
ctrl.stepCnt++;
|
||||
|
||||
//CUSTOM: track actual precice current position
|
||||
if (ctrl.dir) {
|
||||
ctrl.posActual ++;
|
||||
} else {
|
||||
ctrl.posActual --;
|
||||
}
|
||||
//CUSTOM: track remaining steps for eventually resuming
|
||||
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.status = IDLE;
|
||||
ctrl.stepCnt = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (ctrl.stepCnt > 0 && ctrl.stepCnt < ctrl.accEnd)
|
||||
{ // we are accelerating
|
||||
ctrl.currentSpeed += ctrl.accInc;
|
||||
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.status = DEC; // we are deccelerating
|
||||
}
|
||||
else
|
||||
{
|
||||
ctrl.currentSpeed = ctrl.targetSpeed;
|
||||
ctrl.statusPrev = ctrl.status; //update previous status
|
||||
ctrl.status = COAST; // we are coasting
|
||||
}
|
||||
|
||||
ctrl.stepInterval = TIMER_F / ctrl.currentSpeed;
|
||||
// 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)
|
||||
{
|
||||
//steps from ctrl.speed -> 0:
|
||||
ctrl.decSteps = 0.5 * ctrl.dec * (ctrl.speed / ctrl.dec) * (ctrl.speed / ctrl.dec);
|
||||
//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;
|
||||
|
||||
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.decSteps = 0.5 * ctrl.dec * (ctrl.speed / ctrl.dec) * (ctrl.speed / ctrl.dec);
|
||||
}
|
||||
|
||||
ctrl.accEnd = ctrl.accSteps;
|
||||
ctrl.coastEnd = targetSteps - ctrl.decSteps;
|
||||
ctrl.targetSpeed = ctrl.speed;
|
||||
|
||||
ctrl.accInc = ctrl.targetSpeed / (double)ctrl.accSteps;
|
||||
ctrl.decInc = ctrl.targetSpeed / (double)ctrl.decSteps;
|
||||
|
||||
ctrl.currentSpeed = ctrl.accInc;
|
||||
|
||||
ctrl.stepInterval = TIMER_F / ctrl.currentSpeed;
|
||||
ctrl.stepsToGo = targetSteps;
|
||||
|
||||
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);
|
||||
}
|
674
components/DendoStepper/LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
139
components/DendoStepper/README.md
Normal file
@ -0,0 +1,139 @@
|
||||
# DendoStepper
|
||||
|
||||
Work in progress, maybe unstable. Opening issues is more than welcome.
|
||||
This library takes care of pulse generating for stepper motor drivers with STEP/DIR interface. Pulse generating utilizes general purpose timers to achieve some usable accuracy and smoothness.
|
||||
Currently supports only linear acceleration and deceleration.
|
||||
|
||||
### Known limitations
|
||||
- maximum number of controlled stepper motors is 4, this is limited by number of general purpose timers
|
||||
- If the motor is moving, it is not possible to move it to another direction.
|
||||
|
||||
## Usage
|
||||
|
||||
```c++
|
||||
typedef struct
|
||||
{
|
||||
uint8_t stepPin; /** step signal pin */
|
||||
uint8_t dirPin; /** dir signal pin */
|
||||
uint8_t enPin; /** enable signal pin */
|
||||
timer_group_t timer_group; /** timer group, useful if we are controlling more than 2 steppers */
|
||||
timer_idx_t timer_idx; /** timer index, useful if we are controlling 2steppers */
|
||||
microStepping_t miStep; /** microstepping configured on driver - used in distance calculation */
|
||||
float stepAngle; /** one step angle in degrees (usually 1.8deg), used in steps per rotation calculation */
|
||||
} DendoStepper_config_t;
|
||||
|
||||
enum microStepping_t
|
||||
{
|
||||
MICROSTEP_1 = 0x1,
|
||||
MICROSTEP_2,
|
||||
MICROSTEP_4 = 0x4,
|
||||
MICROSTEP_8 = 0x8,
|
||||
MICROSTEP_16 = 0x10,
|
||||
MICROSTEP_32 = 0x20,
|
||||
MICROSTEP_64 = 0x40,
|
||||
MICROSTEP_128 = 0x80,
|
||||
MICROSTEP_256 = 0x100,
|
||||
};
|
||||
|
||||
```
|
||||
Configuration struct, can be allocated on stack or heap.
|
||||
|
||||
```c++
|
||||
void init();
|
||||
```
|
||||
Initializes GPIO and Timer peripherals, registers ISR. Expects populated config struct is alreay passed to the class using config()
|
||||
|
||||
```c++
|
||||
void config(DendoStepper_config_t* config);
|
||||
```
|
||||
Configures the class as per passed config struct pointer.
|
||||
|
||||
```c++
|
||||
void setStepsPerMm(uint16_t steps);
|
||||
uint16_t getStepsPerMm();
|
||||
```
|
||||
Sets or gets steps needed to move one millimiter, useful if stepper is moving along linear axis.
|
||||
|
||||
```c++
|
||||
void setSpeed(uint16_t speed,uint16_t accT, uint16_t decT);
|
||||
uint16_t getSpeed();
|
||||
float getAcc();
|
||||
```
|
||||
Sets maximum speed in steps per second, acceleration and deceleration time in milliseconds.
|
||||
Gets speed in steps per second
|
||||
Gets acceleration in steps per second per second
|
||||
|
||||
```c++
|
||||
void setSpeedMm(uint16_t speed,uint16_t accT, uint16_t decT);
|
||||
```
|
||||
Sets maximum speed in mm/s, acceleration and deceleration time in milliseconds. Expects already defined steps per millimeter with setStepsPerMm()
|
||||
|
||||
```c++
|
||||
void runPos(int32_t relative);
|
||||
```
|
||||
Runs motor to position relative from current position in steps, respecting constraints set with setSpeed()
|
||||
|
||||
```c++
|
||||
void runPosMm(int32_t relative);
|
||||
```
|
||||
Runs motor to position relative from current position in millimeters, respecting constraints set with setSpeed()
|
||||
Expects already defined steps per millimeter with setStepsPerMm()
|
||||
|
||||
```c++
|
||||
bool runAbsolute(uint32_t position);
|
||||
```
|
||||
Runs motor in absolute coordinate plane. Unit: steps (should be constrained with home switch)
|
||||
|
||||
```c++
|
||||
bool runAbsoluteMm(uint32_t position);
|
||||
```
|
||||
Runs motor in absolute coordinate plane. Unit: millimeters (should be constrained with home switch)
|
||||
Expects already defined steps per millimeter with setStepsPerMm()
|
||||
|
||||
```c++
|
||||
bool runInf(bool direction);
|
||||
```
|
||||
Runs motor infintely in desired direction with constrains set using setSpeed().
|
||||
|
||||
```c++
|
||||
void disableMotor();
|
||||
void enableMotor();
|
||||
```
|
||||
Disables and enables motor via EN pin
|
||||
|
||||
```c++
|
||||
uint8_t getState();
|
||||
|
||||
enum motor_status{
|
||||
DISABLED,
|
||||
IDLE,
|
||||
ACC,
|
||||
COAST,
|
||||
DEC,
|
||||
};
|
||||
```
|
||||
Returns current state of motor, return type is enum motor_status
|
||||
|
||||
|
||||
```c++
|
||||
void resetAbsolute();
|
||||
```
|
||||
Resets absolute position to 0. Called for ex. when endswitch is hit.
|
||||
|
||||
```c++
|
||||
void getPosition();
|
||||
```
|
||||
Gets current position in absolute coordinate plane in steps.
|
||||
|
||||
```c++
|
||||
void getPositionMm();
|
||||
```
|
||||
Gets current position in absolute coordinate plane in millimeters.
|
||||
Expects already defined steps per millimeter with setStepsPerMm()
|
||||
|
||||
```c++
|
||||
void stop();
|
||||
```
|
||||
Stops the motor dead on the spot. No deceleration is performed this way. Eg. e-stop.
|
||||
|
||||
|
0
components/DendoStepper/component.mk
Normal file
3
components/DendoStepper/example/.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
build/
|
||||
sdkconfig
|
||||
sdkconfig.old
|
9
components/DendoStepper/example/CMakeLists.txt
Normal file
@ -0,0 +1,9 @@
|
||||
# For more information about build system see
|
||||
# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html
|
||||
# The following five lines of boilerplate have to be in your project's
|
||||
# CMakeLists in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
set(EXTRA_COMPONENT_DIRS "../")
|
||||
project(example)
|
32
components/DendoStepper/example/README.md
Normal file
@ -0,0 +1,32 @@
|
||||
# _Sample project_
|
||||
|
||||
(See the README.md file in the upper level 'examples' directory for more information about examples.)
|
||||
|
||||
This is the simplest buildable example. The example is used by command `idf.py create-project`
|
||||
that copies the project to user specified path and set it's name. For more information follow the [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project)
|
||||
|
||||
|
||||
|
||||
## How to use example
|
||||
We encourage the users to use the example as a template for the new projects.
|
||||
A recommended way is to follow the instructions on a [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project).
|
||||
|
||||
## Example folder contents
|
||||
|
||||
The project **sample_project** contains one source file in C language [main.c](main/main.c). The file is located in folder [main](main).
|
||||
|
||||
ESP-IDF projects are built using CMake. The project build configuration is contained in `CMakeLists.txt`
|
||||
files that provide set of directives and instructions describing the project's source files and targets
|
||||
(executable, library, or both).
|
||||
|
||||
Below is short explanation of remaining files in the project folder.
|
||||
|
||||
```
|
||||
├── CMakeLists.txt
|
||||
├── main
|
||||
│ ├── CMakeLists.txt
|
||||
│ └── main.c
|
||||
└── README.md This is the file you are currently reading
|
||||
```
|
||||
Additionally, the sample project contains Makefile and component.mk files, used for the legacy Make based build system.
|
||||
They are not used or needed when building with CMake and idf.py.
|
3
components/DendoStepper/example/main/CMakeLists.txt
Normal file
@ -0,0 +1,3 @@
|
||||
idf_component_register(SRCS "main.cpp"
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES DendoStepper freertos)
|
49
components/DendoStepper/example/main/main.cpp
Normal file
@ -0,0 +1,49 @@
|
||||
#include <stdio.h>
|
||||
#include "DendoStepper.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
DendoStepper step;
|
||||
DendoStepper step1;
|
||||
|
||||
extern "C" void app_main(void)
|
||||
{
|
||||
DendoStepper_config_t step_cfg = {
|
||||
.stepPin = 16,
|
||||
.dirPin = 17,
|
||||
.enPin = 15,
|
||||
.timer_group = TIMER_GROUP_0,
|
||||
.timer_idx = TIMER_0,
|
||||
.miStep = MICROSTEP_32,
|
||||
.stepAngle = 1.8};
|
||||
|
||||
DendoStepper_config_t step1_cfg = {
|
||||
.stepPin = 18,
|
||||
.dirPin = 19,
|
||||
.enPin = 20,
|
||||
.timer_group = TIMER_GROUP_0,
|
||||
.timer_idx = TIMER_1,
|
||||
.miStep = MICROSTEP_32,
|
||||
.stepAngle = 1.8};
|
||||
|
||||
step.config(&step_cfg);
|
||||
step1.config(&step1_cfg);
|
||||
|
||||
step.init();
|
||||
step1.init();
|
||||
|
||||
step.setSpeed(10000, 1000, 1000);
|
||||
step1.setSpeed(20000, 1000, 1000);
|
||||
|
||||
// step.runInf(true);
|
||||
step.setStepsPerMm(10);
|
||||
|
||||
while (1)
|
||||
{
|
||||
step.runPosMm(500);
|
||||
step1.runPos(10000);
|
||||
vTaskDelay(1000);
|
||||
// step.runAbs(5000);
|
||||
}
|
||||
}
|
281
components/DendoStepper/include/DendoStepper.h
Normal file
@ -0,0 +1,281 @@
|
||||
#pragma once
|
||||
|
||||
/* ESP-IDF library for bipolar stepper motor drivers with STEP/DIR interface
|
||||
Copyright (C) 2022 Denis Voltmann
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef DENDOSTEPPER_H
|
||||
#define DENDOSTEPPER_H
|
||||
|
||||
#include "stdint.h"
|
||||
#include "stdio.h"
|
||||
#include <cstring>
|
||||
#include "driver/timer.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_timer.h"
|
||||
#include "math.h"
|
||||
|
||||
//#define STEP_DEBUG
|
||||
|
||||
#define NS_TO_T_TICKS(x) (x)
|
||||
#define TIMER_F 1000000ULL
|
||||
#define TICK_PER_S TIMER_F
|
||||
|
||||
enum motor_status
|
||||
{
|
||||
DISABLED,
|
||||
IDLE,
|
||||
ACC,
|
||||
COAST,
|
||||
DEC
|
||||
};
|
||||
|
||||
enum dir
|
||||
{
|
||||
CW,
|
||||
CCW
|
||||
};
|
||||
|
||||
enum microStepping_t
|
||||
{
|
||||
MICROSTEP_1 = 0x1,
|
||||
MICROSTEP_2,
|
||||
MICROSTEP_4 = 0x4,
|
||||
MICROSTEP_8 = 0x8,
|
||||
MICROSTEP_16 = 0x10,
|
||||
MICROSTEP_32 = 0x20,
|
||||
MICROSTEP_64 = 0x40,
|
||||
MICROSTEP_128 = 0x80,
|
||||
MICROSTEP_256 = 0x100,
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Configuration structure
|
||||
*/
|
||||
typedef struct
|
||||
{
|
||||
uint8_t stepPin; /** step signal pin */
|
||||
uint8_t dirPin; /** dir signal pin */
|
||||
uint8_t enPin; /** enable signal pin */
|
||||
timer_group_t timer_group; /** timer group, useful if we are controlling more than 2 steppers */
|
||||
timer_idx_t timer_idx; /** timer index, useful if we are controlling 2steppers */
|
||||
microStepping_t miStep; /** microstepping configured on driver - used in distance calculation */
|
||||
float stepAngle; /** one step angle in degrees (usually 1.8deg), used in steps per rotation calculation */
|
||||
} DendoStepper_config_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
uint32_t stepInterval = 40000; // step interval in ns/25
|
||||
double targetSpeed = 0; // target speed in steps/s
|
||||
double currentSpeed = 0;
|
||||
double accInc = 0;
|
||||
double decInc = 0;
|
||||
uint32_t stepCnt = 0; // step counter
|
||||
uint32_t accEnd; // when to end acc and start coast
|
||||
uint32_t coastEnd; // when to end coast and start decel
|
||||
uint32_t stepsToGo = 0; // steps we need to take
|
||||
float speed = 100; // speed in rad/s
|
||||
float acc = 100; // acceleration in rad*second^-2
|
||||
float dec = 100; // decceleration in rad*second^-2
|
||||
uint32_t accSteps = 0;
|
||||
uint32_t decSteps = 0;
|
||||
int32_t stepsRemaining = 0;
|
||||
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;
|
||||
bool runInfinite = false;
|
||||
uint16_t stepsPerRot; // steps per one revolution, 360/stepAngle * microstep
|
||||
uint16_t stepsPerMm = 0; /** Steps per one milimiter, if the motor is performing linear movement */
|
||||
} ctrl_var_t;
|
||||
|
||||
class DendoStepper
|
||||
{
|
||||
private:
|
||||
DendoStepper_config_t conf;
|
||||
ctrl_var_t ctrl;
|
||||
esp_timer_handle_t dyingTimer;
|
||||
TaskHandle_t enTask;
|
||||
uint64_t currentPos = 0; // absolute position
|
||||
bool timerStarted = 0;
|
||||
|
||||
/** @brief PRIVATE: Step interval calculation
|
||||
* @param speed maximum movement speed
|
||||
* @param accTimeMs acceleration time in ms
|
||||
* @param target target position
|
||||
*/
|
||||
void calc(uint32_t);
|
||||
|
||||
/** @brief sets En GPIO
|
||||
* @param state 0-LOW,1-HIGH
|
||||
* @return void
|
||||
*/
|
||||
void setEn(bool);
|
||||
|
||||
/** @brief sets Dir GPIO
|
||||
* @param state 0-CW 1-CCW
|
||||
*/
|
||||
void setDir(bool);
|
||||
|
||||
/** @brief static wrapper for ISR function
|
||||
* @param _this DendoStepper* this pointer
|
||||
* @return bool
|
||||
*/
|
||||
static bool xISRwrap(void *_this)
|
||||
{
|
||||
return static_cast<DendoStepper *>(_this)->xISR();
|
||||
}
|
||||
|
||||
/** @brief enableMotor wrapper
|
||||
*/
|
||||
static void _disableMotor(void *_this)
|
||||
{
|
||||
static_cast<DendoStepper *>(_this)->disableMotor();
|
||||
}
|
||||
|
||||
bool xISR();
|
||||
|
||||
public:
|
||||
/** @brief Costructor - conf variables to be passed later
|
||||
*/
|
||||
DendoStepper();
|
||||
|
||||
/** @brief Configuration of library, used with constructor w/o params
|
||||
* @param config DendoStepper_config_t structure pointer - can be freed after this call
|
||||
*/
|
||||
void config(DendoStepper_config_t *config);
|
||||
|
||||
/** @brief initialize GPIO and Timer peripherals
|
||||
* @param stepP step pulse pin
|
||||
* @param dirP direction signal pin
|
||||
* @param enP enable signal Pin
|
||||
* @param group timer group to use (0 or 1)
|
||||
* @param index which timer to use (0 or 1)
|
||||
* @param microstepping microstepping performed by the driver, used for more accuracy
|
||||
* @param stepsPerRot how many steps it takes for the motor to move 2Pi rads. this can be also used instead of microstepping parameter
|
||||
*/
|
||||
void init(uint8_t, uint8_t, uint8_t, timer_group_t, timer_idx_t, microStepping_t microstep, uint16_t stepsPerRot);
|
||||
|
||||
/** @brief initialize GPIO and Timer peripherals, class must be configured beforehand with @attention config()
|
||||
*/
|
||||
void init();
|
||||
|
||||
/** @brief runs motor to relative position in steps
|
||||
* @param relative number of steps to run, negative is reverse
|
||||
*/
|
||||
esp_err_t runPos(int32_t relative);
|
||||
|
||||
/** @brief runs motor to relative position in mm
|
||||
* @param relative number of mm to run, negative is reverse
|
||||
*/
|
||||
esp_err_t runPosMm(int32_t relative);
|
||||
|
||||
/** @brief run motor to position in absolute coordinates (steps)
|
||||
* @param postition absolute position in steps from home position (must be positive);
|
||||
* @return ESP_OK if motor can run immediately, ESP_ERR if it is currently moving
|
||||
*/
|
||||
esp_err_t runAbs(uint32_t position);
|
||||
|
||||
/** @brief run motor to position in absolute coordinates (millimiters)
|
||||
* @param postition absolute position in mm from home position (must be positive);
|
||||
* @return ESP_OK if motor can run immediately, ESP_ERR if it is currently moving
|
||||
*/
|
||||
esp_err_t runAbsMm(uint32_t position);
|
||||
|
||||
/** @brief sets motor speed
|
||||
* @param speed speed in steps per second
|
||||
* @param accT acceleration time in ms
|
||||
* @param decT deceleration time in ms
|
||||
*/
|
||||
void setSpeed(uint32_t speed, uint16_t accT, uint16_t decT);
|
||||
|
||||
/** @brief sets motor speed and accel in millimeters/second
|
||||
* @param speed speed mm*s^-1
|
||||
* @param accT acceleration time in ms
|
||||
* @param accT deceleration time in ms
|
||||
*/
|
||||
void setSpeedMm(uint32_t speed, uint16_t accT, uint16_t decT);
|
||||
|
||||
//CUSTOM: change speed while running
|
||||
void changeSpeedMm(uint32_t speed);
|
||||
|
||||
/**
|
||||
* @brief Set steps per 1 mm of linear movement
|
||||
*
|
||||
* @param steps steps needed to move one millimiter
|
||||
*/
|
||||
void setStepsPerMm(uint16_t steps);
|
||||
|
||||
/**
|
||||
* @brief get steps per 1mm settings
|
||||
*
|
||||
*/
|
||||
uint16_t getStepsPerMm();
|
||||
|
||||
/** @brief set EN pin 1, stops movement
|
||||
*/
|
||||
void disableMotor();
|
||||
|
||||
/** @brief set EN pin to 0, enables movement
|
||||
*/
|
||||
void enableMotor();
|
||||
|
||||
/** @brief returns current state
|
||||
* @return motor_status enum
|
||||
*/
|
||||
uint8_t getState();
|
||||
|
||||
/** @brief run motor to position in absolute coordinates (millimiters)
|
||||
* @param postition absolute position in steps from home position (must be positive);
|
||||
* @return ESP_OK if motor can run immediately, ESP_ERR if it is currently moving
|
||||
*/
|
||||
esp_err_t runAbsoluteMm(uint32_t position);
|
||||
|
||||
/** @brief returns current absolute position
|
||||
* @return current absolute postion in steps
|
||||
*/
|
||||
uint64_t getPosition();
|
||||
|
||||
/** @brief returns current absolute position
|
||||
* @return current absolute postion in steps
|
||||
*/
|
||||
uint64_t getPositionMm();
|
||||
|
||||
/** @brief resets absolute pos to 0
|
||||
*/
|
||||
void resetAbsolute();
|
||||
|
||||
/** @brief
|
||||
*
|
||||
*/
|
||||
void runInf(bool direction);
|
||||
|
||||
/** @brief returns current speed in steps per second
|
||||
*/
|
||||
uint16_t getSpeed();
|
||||
|
||||
/** @brief returns current acceleration time in ms
|
||||
*/
|
||||
float getAcc();
|
||||
|
||||
/** @brief stops the motor dead, but stays enabled
|
||||
*/
|
||||
void stop();
|
||||
};
|
||||
|
||||
#endif
|
6
components/gpio/CMakeLists.txt
Normal file
@ -0,0 +1,6 @@
|
||||
idf_component_register(
|
||||
SRCS
|
||||
"gpio_evaluateSwitch.cpp"
|
||||
"gpio_adc.cpp"
|
||||
INCLUDE_DIRS "."
|
||||
)
|
21
components/gpio/gpio_adc.cpp
Normal file
@ -0,0 +1,21 @@
|
||||
#include "gpio_adc.hpp"
|
||||
|
||||
|
||||
//=============================
|
||||
//========= readAdc ===========
|
||||
//=============================
|
||||
//function for multisampling an anlog input
|
||||
int gpio_readAdc(adc1_channel_t adc_channel, bool inverted) {
|
||||
//make multiple measurements
|
||||
int adc_reading = 0;
|
||||
for (int i = 0; i < 32; i++) {
|
||||
adc_reading += adc1_get_raw(adc_channel);
|
||||
}
|
||||
adc_reading = adc_reading / 32;
|
||||
//return original or inverted result
|
||||
if (inverted) {
|
||||
return 4095 - adc_reading;
|
||||
} else {
|
||||
return adc_reading;
|
||||
}
|
||||
}
|
9
components/gpio/gpio_adc.hpp
Normal file
@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include <stdio.h>
|
||||
#include "driver/adc.h"
|
||||
|
||||
//function for multisampling an anlog input
|
||||
//measures 30 times and returns average
|
||||
//if invertion is used currently 11bit resolution is assumed (subtracts from 4095)
|
||||
//TODO: rework this function to be more universal
|
||||
int gpio_readAdc(adc1_channel_t adc_channel, bool inverted = false);
|
146
components/gpio/gpio_evaluateSwitch.cpp
Normal file
@ -0,0 +1,146 @@
|
||||
#include "gpio_evaluateSwitch.hpp"
|
||||
|
||||
static const char *TAG = "evaluateSwitch";
|
||||
|
||||
|
||||
gpio_evaluatedSwitch::gpio_evaluatedSwitch( //minimal (use default values)
|
||||
gpio_num_t gpio_num_declare
|
||||
){
|
||||
gpio_num = gpio_num_declare;
|
||||
pullup = true;
|
||||
inverted = false;
|
||||
inputSource = inputSource_t::GPIO;
|
||||
|
||||
initGpio();
|
||||
};
|
||||
|
||||
|
||||
gpio_evaluatedSwitch::gpio_evaluatedSwitch( //optional parameters given
|
||||
gpio_num_t gpio_num_declare,
|
||||
bool pullup_declare,
|
||||
bool inverted_declare
|
||||
){
|
||||
gpio_num = gpio_num_declare;
|
||||
pullup = pullup_declare;
|
||||
inverted = inverted_declare;
|
||||
inputSource = inputSource_t::GPIO;
|
||||
|
||||
initGpio();
|
||||
};
|
||||
|
||||
|
||||
gpio_evaluatedSwitch::gpio_evaluatedSwitch( //with function as input source
|
||||
bool (*getInputStatePtr_f)(void),
|
||||
bool inverted_f){
|
||||
//gpio_num = NULL;
|
||||
//pullup = NULL;
|
||||
inverted = inverted_f;
|
||||
getInputStatePtr = getInputStatePtr_f;
|
||||
inputSource = inputSource_t::FUNCTION;
|
||||
};
|
||||
|
||||
|
||||
|
||||
void gpio_evaluatedSwitch::initGpio(){
|
||||
ESP_LOGI(TAG, "initializing gpio pin %d", (int)gpio_num);
|
||||
|
||||
//define gpio pin as input
|
||||
gpio_pad_select_gpio(gpio_num);
|
||||
gpio_set_direction(gpio_num, GPIO_MODE_INPUT);
|
||||
|
||||
if (pullup == true){ //enable pullup if desired (default)
|
||||
gpio_pad_select_gpio(gpio_num);
|
||||
gpio_set_pull_mode(gpio_num, GPIO_PULLUP_ONLY);
|
||||
}else{
|
||||
gpio_set_pull_mode(gpio_num, GPIO_FLOATING);
|
||||
gpio_pad_select_gpio(gpio_num);
|
||||
}
|
||||
//TODO add pulldown option
|
||||
//gpio_set_pull_mode(gpio_num, GPIO_PULLDOWN_ONLY);
|
||||
};
|
||||
|
||||
|
||||
|
||||
void gpio_evaluatedSwitch::handle(){ //Statemachine for debouncing and edge detection
|
||||
|
||||
//--- get pin state with required method ---
|
||||
switch (inputSource){
|
||||
case inputSource_t::GPIO: //from gpio pin
|
||||
if (gpio_get_level(gpio_num) == 0){ //pin low
|
||||
inputState = true;
|
||||
} else { //pin high
|
||||
inputState = false;
|
||||
}
|
||||
break;
|
||||
case inputSource_t::FUNCTION: //from funtion
|
||||
inputState = (*getInputStatePtr)();
|
||||
break;
|
||||
}
|
||||
|
||||
//--- invert state ---
|
||||
//not inverted: switch switches to GND when active
|
||||
//inverted: switch switched to VCC when active
|
||||
if (inverted == true){
|
||||
inputState = !inputState;
|
||||
}
|
||||
|
||||
|
||||
//=========================================================
|
||||
//========= Statemachine for evaluateing switch ===========
|
||||
//=========================================================
|
||||
switch (p_state){
|
||||
default:
|
||||
p_state = switchState::FALSE;
|
||||
break;
|
||||
|
||||
case switchState::FALSE: //input confirmed high (released)
|
||||
fallingEdge = false; //reset edge event
|
||||
if (inputState == true){ //pin high (on)
|
||||
p_state = switchState::HIGH;
|
||||
timestampHigh = esp_log_timestamp(); //save timestamp switched from low to high
|
||||
} else {
|
||||
msReleased = esp_log_timestamp() - timestampLow; //update duration released
|
||||
}
|
||||
break;
|
||||
|
||||
case switchState::HIGH: //input recently switched to high (pressed)
|
||||
if (inputState == true){ //pin still high (on)
|
||||
if (esp_log_timestamp() - timestampHigh > minOnMs){ //pin in same state long enough
|
||||
p_state = switchState::TRUE;
|
||||
state = true;
|
||||
risingEdge = true;
|
||||
msReleased = timestampHigh - timestampLow; //calculate duration the button was released
|
||||
}
|
||||
}else{
|
||||
p_state = switchState::FALSE;
|
||||
}
|
||||
break;
|
||||
|
||||
case switchState::TRUE: //input confirmed high (pressed)
|
||||
risingEdge = false; //reset edge event
|
||||
if (inputState == false){ //pin low (off)
|
||||
timestampLow = esp_log_timestamp();
|
||||
p_state = switchState::LOW;
|
||||
} else {
|
||||
msPressed = esp_log_timestamp() - timestampHigh; //update duration pressed
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case switchState::LOW: //input recently switched to low (released)
|
||||
if (inputState == false){ //pin still low (off)
|
||||
if (esp_log_timestamp() - timestampLow > minOffMs){ //pin in same state long enough
|
||||
p_state = switchState::FALSE;
|
||||
msPressed = timestampLow - timestampHigh; //calculate duration the button was pressed
|
||||
state=false;
|
||||
fallingEdge=true;
|
||||
}
|
||||
}else{
|
||||
p_state = switchState::TRUE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
71
components/gpio/gpio_evaluateSwitch.hpp
Normal file
@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "esp_log.h"
|
||||
}
|
||||
|
||||
//constructor examples:
|
||||
//switch to gnd and us internal pullup:
|
||||
//gpio_evaluatedSwitch s3(GPIO_NUM_14);
|
||||
//switch to gnd dont use internal pullup:
|
||||
//gpio_evaluatedSwitch s3(GPIO_NUM_14 false);
|
||||
//switch to VCC (inverted) and dont use internal pullup:
|
||||
//gpio_evaluatedSwitch s3(GPIO_NUM_14 false, true);
|
||||
|
||||
enum class inputSource_t {GPIO, FUNCTION};
|
||||
|
||||
class gpio_evaluatedSwitch {
|
||||
public:
|
||||
//--- input ---
|
||||
uint32_t minOnMs = 30;
|
||||
uint32_t minOffMs = 30;
|
||||
|
||||
//constructor minimal (default parameters pullup=true, inverted=false)
|
||||
gpio_evaluatedSwitch(
|
||||
gpio_num_t gpio_num_declare
|
||||
);
|
||||
|
||||
//constructor with optional parameters
|
||||
gpio_evaluatedSwitch(
|
||||
gpio_num_t gpio_num_declare,
|
||||
bool pullup_declare,
|
||||
bool inverted_declare=false
|
||||
);
|
||||
|
||||
//constructor with a function as source for input state instead of a gpio pin
|
||||
gpio_evaluatedSwitch(bool (*getInputStatePtr_f)(void), bool inverted_f=false);
|
||||
|
||||
|
||||
//--- output --- TODO make readonly? (e.g. public section: const int& x = m_x;)
|
||||
bool state = false;
|
||||
bool risingEdge = false;
|
||||
bool fallingEdge = false;
|
||||
uint32_t msPressed = 0;
|
||||
uint32_t msReleased = 0;
|
||||
|
||||
//--- functions ---
|
||||
void handle(); //Statemachine for debouncing and edge detection
|
||||
|
||||
private:
|
||||
gpio_num_t gpio_num;
|
||||
bool pullup;
|
||||
bool inverted;
|
||||
bool (*getInputStatePtr)(void); //pointer to function for getting current input state
|
||||
inputSource_t inputSource = inputSource_t::GPIO;
|
||||
|
||||
enum class switchState {TRUE, FALSE, LOW, HIGH};
|
||||
switchState p_state = switchState::FALSE;
|
||||
bool inputState = false;
|
||||
uint32_t timestampLow = 0;
|
||||
uint32_t timestampHigh = 0;
|
||||
void initGpio();
|
||||
|
||||
};
|
||||
|
||||
|
@ -236,7 +236,7 @@ esp_err_t max7219_draw_text_7seg(max7219_t *dev, uint8_t pos, const char *s)
|
||||
{
|
||||
CHECK_ARG(dev && s);
|
||||
|
||||
while (s && pos < dev->digits)
|
||||
while (*s != '\0' && pos < dev->digits)
|
||||
{
|
||||
uint8_t c = get_char(dev, *s);
|
||||
if (*(s + 1) == '.')
|
||||
|
1117
connection-plan.drawio
Normal file
BIN
connection-plan.drawio.pdf
Normal file
BIN
docs/control-board_schematic.pdf
Normal file
BIN
docs/display_MAX7219-MAX7221-7_manual.pdf
Normal file
BIN
docs/encoder-LPD3806_dimensions.jpg
Normal file
After Width: | Height: | Size: 31 KiB |
BIN
docs/linear-axis_dimensions.jpg
Normal file
After Width: | Height: | Size: 594 KiB |
BIN
docs/safety-relay_3SK1111-1AB30_con1.jpg
Normal file
After Width: | Height: | Size: 60 KiB |
BIN
docs/safety-relay_3SK1111-1AB30_con2.jpg
Normal file
After Width: | Height: | Size: 54 KiB |
BIN
docs/stepper-driver_MKS-SERVO28C-manual.pdf
Normal file
BIN
docs/stepper-driver_TB6600-Manual.pdf
Normal file
BIN
docs/vfd/T13-400W-12-HT13-750W-12H-1.jpg
Normal file
After Width: | Height: | Size: 82 KiB |
BIN
docs/vfd/T13-400W-12-HT13-750W-12H-2.jpg
Normal file
After Width: | Height: | Size: 39 KiB |
BIN
docs/vfd/T13-400W-12-HT13-750W-12H.jpg
Normal file
After Width: | Height: | Size: 72 KiB |
BIN
docs/vfd/T13-400W-12-HT13-750W-12H_modbus.jpg
Normal file
After Width: | Height: | Size: 126 KiB |
BIN
docs/vfd/T13-400W-12-H_download.pdf
Normal file
BIN
docs/vfd/T13-400W-12-H_scan.PDF
Normal file
2
docs/vfd/currently-used_T13-750W-12-h.txt
Normal file
@ -0,0 +1,2 @@
|
||||
currently the vfd 'T13-750W-12-h' is actually used.
|
||||
Included documentation about T13-400W here too, modbus specification might be the same.
|
BIN
docs/vfd/modbus-test/setfreq.jpg
Normal file
After Width: | Height: | Size: 144 KiB |
BIN
docs/vfd/modbus-test/start.jpg
Normal file
After Width: | Height: | Size: 128 KiB |
BIN
docs/vfd/modbus-test/stop.jpg
Normal file
After Width: | Height: | Size: 144 KiB |
1080
function-diagram.drawio
Normal file
BIN
function-diagram.drawio.pdf
Normal file
BIN
img/cable-length-cutter.jpg
Normal file
After Width: | Height: | Size: 546 KiB |
3
img/panel-layout.svg
Normal file
After Width: | Height: | Size: 348 KiB |
@ -1,2 +1,20 @@
|
||||
idf_component_register(SRCS "main.c"
|
||||
INCLUDE_DIRS ".")
|
||||
idf_component_register(
|
||||
SRCS
|
||||
"main.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)
|
98
main/buzzer.cpp
Normal file
@ -0,0 +1,98 @@
|
||||
#include "buzzer.hpp"
|
||||
#include "config.h"
|
||||
|
||||
static const char *TAG_BUZZER = "buzzer";
|
||||
|
||||
//============================
|
||||
//========== init ============
|
||||
//============================
|
||||
//define gpio pin as output, initialize queue
|
||||
void buzzer_t::init(){
|
||||
//define buzzer pin as output
|
||||
gpio_pad_select_gpio(gpio_pin);
|
||||
gpio_set_direction(gpio_pin, GPIO_MODE_OUTPUT);
|
||||
//create queue
|
||||
beepQueue = xQueueCreate( 20, sizeof( struct beepEntry ) );
|
||||
}
|
||||
|
||||
|
||||
//=============================
|
||||
//======== constructor ========
|
||||
//=============================
|
||||
//copy provided config parameters to private variables, run init function
|
||||
buzzer_t::buzzer_t(gpio_num_t gpio_pin_f, uint16_t msGap_f){
|
||||
ESP_LOGI(TAG_BUZZER, "Initializing buzzer");
|
||||
//copy configuration parameters to variables
|
||||
gpio_pin = gpio_pin_f;
|
||||
msGap = msGap_f;
|
||||
//run init function to initialize gpio and queue
|
||||
init();
|
||||
};
|
||||
|
||||
|
||||
//============================
|
||||
//=========== beep ===========
|
||||
//============================
|
||||
//function to add a beep command to the queue
|
||||
void buzzer_t::beep(uint8_t count, uint16_t msOn, uint16_t msOff, bool noGap){
|
||||
//create entry struct with provided data
|
||||
struct beepEntry entryInsert = {
|
||||
count = count,
|
||||
msOn = msOn,
|
||||
msOff = msOff,
|
||||
noGap = noGap
|
||||
};
|
||||
|
||||
// Send a pointer to a struct AMessage object. Don't block if the
|
||||
// queue is already full.
|
||||
//struct beepEntry *entryInsertPointer;
|
||||
//entryInsertPointer = &entryInsertData;
|
||||
ESP_LOGW(TAG_BUZZER, "Inserted object to queue - count=%d, msOn=%d, msOff=%d", entryInsert.count, entryInsert.msOn, entryInsert.msOff);
|
||||
//xQueueGenericSend( beepQueue, ( void * ) &entryInsertPointer, ( TickType_t ) 0, queueSEND_TO_BACK );
|
||||
xQueueSend( beepQueue, ( void * )&entryInsert, ( TickType_t ) 0 );
|
||||
}
|
||||
|
||||
|
||||
//==============================
|
||||
//======== processQueue ========
|
||||
//==============================
|
||||
void buzzer_t::processQueue(){
|
||||
//struct for receiving incomming events
|
||||
struct beepEntry entryRead = { };
|
||||
|
||||
//loop forever
|
||||
while(1){
|
||||
ESP_LOGD(TAG_BUZZER, "processQueue: waiting for beep command");
|
||||
|
||||
//if queue is ready
|
||||
if( beepQueue != 0 )
|
||||
{
|
||||
// wait for a queue entry to be available indefinetely if INCLUDE_vTaskSuspend is enabled in the FreeRTOS config
|
||||
// otherwise waits for at least 7 weeks
|
||||
if( xQueueReceive( beepQueue, &entryRead, portMAX_DELAY ) )
|
||||
{
|
||||
ESP_LOGW(TAG_BUZZER, "Read entry from queue: count=%d, msOn=%d, msOff=%d", entryRead.count, entryRead.msOn, entryRead.msOff);
|
||||
|
||||
//beep requested count with requested delays
|
||||
for (int i = entryRead.count; i--;){
|
||||
//turn on
|
||||
ESP_LOGD(TAG_BUZZER, "turning buzzer on");
|
||||
gpio_set_level(gpio_pin, 1);
|
||||
vTaskDelay(entryRead.msOn / portTICK_PERIOD_MS);
|
||||
//turn off
|
||||
ESP_LOGD(TAG_BUZZER, "turning buzzer off");
|
||||
gpio_set_level(gpio_pin, 0);
|
||||
vTaskDelay(entryRead.msOff / portTICK_PERIOD_MS);
|
||||
}
|
||||
if( entryRead.noGap == false ){
|
||||
//wait for minimum gap between beep events
|
||||
vTaskDelay(msGap / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
||||
}else{ //wait for queue to become available
|
||||
vTaskDelay(50 / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
57
main/buzzer.hpp
Normal file
@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "esp_log.h"
|
||||
}
|
||||
|
||||
#include "freertos/queue.h"
|
||||
|
||||
|
||||
|
||||
//===================================
|
||||
//========= buzzer_t class ==========
|
||||
//===================================
|
||||
//class which blinks a gpio pin for the provided count and durations.
|
||||
//- 'processQueue' has to be run in a separate task
|
||||
//- uses a queue to queue up multiple beep commands
|
||||
class buzzer_t {
|
||||
public:
|
||||
//--- constructor ---
|
||||
buzzer_t(gpio_num_t gpio_pin_f, uint16_t msGap_f = 200);
|
||||
|
||||
//--- functions ---
|
||||
void processQueue(); //has to be run once in a separate task, waits for and processes queued events
|
||||
void beep(uint8_t count, uint16_t msOn, uint16_t msOff, bool noGap = false);
|
||||
//void clear(); (TODO - not implemented yet)
|
||||
//void createTask(); (TODO - not implemented yet)
|
||||
|
||||
//--- variables ---
|
||||
uint16_t msGap; //gap between beep entries (when multiple queued)
|
||||
|
||||
private:
|
||||
//--- functions ---
|
||||
void init();
|
||||
|
||||
//--- variables ---
|
||||
gpio_num_t gpio_pin;
|
||||
|
||||
struct beepEntry {
|
||||
uint8_t count;
|
||||
uint16_t msOn;
|
||||
uint16_t msOff;
|
||||
bool noGap;
|
||||
};
|
||||
|
||||
//queue for queueing up multiple events while one is still processing
|
||||
QueueHandle_t beepQueue = NULL;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
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
|
||||
|
||||
|
||||
|
||||
|
589
main/control.cpp
Normal file
@ -0,0 +1,589 @@
|
||||
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 ---------------
|
||||
//-----------------------------------------
|
||||
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_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
|
||||
static int potiRead = 0; //voltage read from adc
|
||||
static uint32_t timestamp_motorStarted = 0; //timestamp winding started
|
||||
|
||||
//automatic cut
|
||||
static int cut_msRemaining = 0;
|
||||
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
|
||||
if (controlState == stateNew) {
|
||||
return; //already at target state -> nothing to do
|
||||
}
|
||||
//log change
|
||||
ESP_LOGW(TAG, "changed state from %s to %s", systemStateStr[(int)controlState], systemStateStr[(int)stateNew]);
|
||||
//change state
|
||||
controlState = stateNew;
|
||||
//update timestamp
|
||||
timestamp_lastStateChange = esp_log_timestamp();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//=================================
|
||||
//===== handle Stop Condition =====
|
||||
//=================================
|
||||
//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 -> reached state, stop motor, display message
|
||||
if (lengthRemaining <= 0 ) {
|
||||
changeState(systemState_t::TARGET_REACHED);
|
||||
vfd_setState(false);
|
||||
displayTop->blink(1, 0, 1000, " S0LL ");
|
||||
displayBot->blink(1, 0, 1000, "ERREICHT");
|
||||
buzzer.beep(2, 100, 100);
|
||||
return true;
|
||||
}
|
||||
//start button released -> idle state, stop motor, display message
|
||||
else if (SW_START.state == false) {
|
||||
changeState(systemState_t::COUNTING);
|
||||
vfd_setState(false);
|
||||
displayTop->blink(2, 900, 1000, "- STOP -");
|
||||
displayBot->blink(2, 900, 1000, " TASTER ");
|
||||
buzzer.beep(3, 200, 100);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//===================================
|
||||
//===== set dynamic speed level =====
|
||||
//===================================
|
||||
//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;
|
||||
//define speed level according to difference
|
||||
if (lengthRemaining < 40) {
|
||||
lvl = 0;
|
||||
} else if (lengthRemaining < 300) {
|
||||
lvl = 1;
|
||||
} else if (lengthRemaining < 700) {
|
||||
lvl = 2;
|
||||
} else { //more than last step remaining
|
||||
lvl = 3;
|
||||
}
|
||||
//limit to max lvl
|
||||
if (lvl > lvlMax) {
|
||||
lvl = lvlMax;
|
||||
}
|
||||
//update vfd speed level
|
||||
vfd_setSpeedLevel(lvl);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//========================
|
||||
//===== control task =====
|
||||
//========================
|
||||
//task that controls the entire machine
|
||||
void task_control(void *pvParameter)
|
||||
{
|
||||
//-- initialize display --
|
||||
max7219_t two7SegDisplays = display_init();
|
||||
//create two separate custom handled display instances
|
||||
handledDisplay displayTop(two7SegDisplays, 0);
|
||||
handledDisplay displayBot(two7SegDisplays, 8);
|
||||
|
||||
//-- 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));
|
||||
|
||||
// ##############################
|
||||
// ######## control loop ########
|
||||
// ##############################
|
||||
// repeatedly handle the machine
|
||||
while(1){
|
||||
vTaskDelay(10 / portTICK_PERIOD_MS);
|
||||
|
||||
|
||||
//------ handle switches ------
|
||||
//run handle functions for all switches used here
|
||||
SW_START.handle();
|
||||
SW_RESET.handle();
|
||||
SW_SET.handle();
|
||||
SW_PRESET1.handle();
|
||||
SW_PRESET2.handle();
|
||||
SW_PRESET3.handle();
|
||||
SW_CUT.handle();
|
||||
SW_AUTO_CUT.handle();
|
||||
|
||||
|
||||
//------ handle cutter ------
|
||||
//TODO: separate task for cutter?
|
||||
cutter_handle();
|
||||
|
||||
|
||||
//------ rotary encoder ------
|
||||
//get current length since last reset
|
||||
lengthNow = encoder_getLenMm();
|
||||
|
||||
|
||||
//--------- buttons ---------
|
||||
//#### RESET switch ####
|
||||
if (SW_RESET.risingEdge) {
|
||||
//dont reset when press used for stopping pending auto-cut
|
||||
if (controlState != systemState_t::AUTO_CUT_WAITING) {
|
||||
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 ");
|
||||
//TODO: stop cutter with reset switch?
|
||||
//cutter_stop();
|
||||
}
|
||||
}
|
||||
|
||||
//### CUT switch ####
|
||||
//start cut cycle immediately
|
||||
if (SW_CUT.risingEdge) {
|
||||
//stop cutter if already running
|
||||
if (cutter_isRunning()) {
|
||||
cutter_stop();
|
||||
buzzer.beep(1, 600, 0);
|
||||
}
|
||||
else if (controlState == systemState_t::AUTO_CUT_WAITING) {
|
||||
//do nothing when press used for stopping pending auto-cut
|
||||
}
|
||||
//start cutter when motor not active
|
||||
else if (controlState != systemState_t::WINDING_START //TODO use vfd state here?
|
||||
&& controlState != systemState_t::WINDING) {
|
||||
cutter_start();
|
||||
buzzer.beep(1, 70, 50);
|
||||
}
|
||||
//error cant cut while motor is on
|
||||
else {
|
||||
buzzer.beep(6, 100, 50);
|
||||
}
|
||||
}
|
||||
|
||||
//#### AUTO_CUT toggle sw ####
|
||||
//beep at change
|
||||
if (SW_AUTO_CUT.risingEdge) {
|
||||
buzzer.beep(2, 100, 50);
|
||||
} else if (SW_AUTO_CUT.fallingEdge) {
|
||||
buzzer.beep(1, 400, 50);
|
||||
}
|
||||
//update enabled state
|
||||
if (SW_AUTO_CUT.state) {
|
||||
//enable autocut when not in target_reached state
|
||||
//(prevent immediate/unexpected cut)
|
||||
if (controlState != systemState_t::TARGET_REACHED) {
|
||||
autoCutEnabled = true;
|
||||
}
|
||||
} else {
|
||||
//disable anytime (also stops countdown to auto cut)
|
||||
autoCutEnabled = false;
|
||||
}
|
||||
|
||||
//#### 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
|
||||
changeState(systemState_t::MANUAL);
|
||||
buzzer.beep(3, 100, 60);
|
||||
}
|
||||
|
||||
//##### 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
|
||||
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);
|
||||
lengthTargetNew = (lengthTargetNew/1000 ) * 1000; //round down
|
||||
} else if (lengthTargetNew % 1000 > 800 ) { //round up if more than .8 meter
|
||||
ESP_LOGD(TAG, "Poti input = %d -> rounding up", lengthTargetNew);
|
||||
lengthTargetNew = (lengthTargetNew/1000 + 1) * 1000; //round up
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Poti input = %d -> hysteresis", lengthTargetNew);
|
||||
lengthTargetNew = lengthTarget;
|
||||
}
|
||||
//update target length and beep when effectively changed
|
||||
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);
|
||||
}
|
||||
}
|
||||
//beep start and end of editing
|
||||
if (SW_SET.risingEdge) {
|
||||
buzzer.beep(1, 70, 50);
|
||||
}
|
||||
if (SW_SET.fallingEdge) {
|
||||
buzzer.beep(2, 70, 50);
|
||||
displayBot.blink(2, 100, 100, "S0LL ");
|
||||
}
|
||||
|
||||
|
||||
//##### 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 ---------
|
||||
//---------------------------
|
||||
//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, 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 ---
|
||||
if (SW_START.risingEdge) {
|
||||
changeState(systemState_t::WINDING_START);
|
||||
vfd_setSpeedLevel(1); //start at low speed
|
||||
vfd_setState(true); //start motor
|
||||
timestamp_motorStarted = esp_log_timestamp(); //save time started
|
||||
buzzer.beep(1, 100, 0);
|
||||
}
|
||||
break;
|
||||
|
||||
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);
|
||||
}
|
||||
handleStopCondition(&displayTop, &displayBot); //stops if button released or target reached
|
||||
//TODO: cancel when there was no cable movement during start time?
|
||||
break;
|
||||
|
||||
case systemState_t::WINDING: //wind fast, slow down when close
|
||||
//set vfd speed depending on remaining distance
|
||||
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: //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);
|
||||
}
|
||||
//initiate countdown to auto-cut if enabled
|
||||
else if ( (autoCutEnabled)
|
||||
&& (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 already reached (-> reset button has to be pressed)
|
||||
if (SW_START.risingEdge) {
|
||||
buzzer.beep(2, 50, 30);
|
||||
displayTop.blink(2, 600, 500, " S0LL ");
|
||||
displayBot.blink(2, 600, 500, "ERREICHT");
|
||||
}
|
||||
break;
|
||||
|
||||
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
|
||||
|| SW_RESET.state || SW_CUT.state
|
||||
|| SW_SET.state || SW_PRESET1.state
|
||||
|| SW_PRESET2.state || SW_PRESET3.state) {//TODO: also stop when target not reached anymore?
|
||||
changeState(systemState_t::COUNTING);
|
||||
buzzer.beep(5, 100, 50);
|
||||
}
|
||||
//- trigger cut if delay passed -
|
||||
else if (cut_msRemaining <= 0) {
|
||||
cutter_start();
|
||||
changeState(systemState_t::CUTTING);
|
||||
}
|
||||
//- beep countdown -
|
||||
//time passed since last beep > time remaining / 6
|
||||
else if ( (esp_log_timestamp() - timestamp_cut_lastBeep) > (cut_msRemaining / 6)
|
||||
&& (esp_log_timestamp() - timestamp_cut_lastBeep) > 50 ) { //dont trigger beeps faster than beep time
|
||||
buzzer.beep(1, 50, 0);
|
||||
timestamp_cut_lastBeep = esp_log_timestamp();
|
||||
}
|
||||
break;
|
||||
|
||||
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?
|
||||
guide_moveToZero(); //move axis guiding the cable to start position
|
||||
encoder_reset(); //reset length measurement
|
||||
lengthNow = 0;
|
||||
buzzer.beep(1, 700, 100);
|
||||
}
|
||||
break;
|
||||
|
||||
case systemState_t::MANUAL: //manually control motor via preset buttons + poti
|
||||
//read poti value
|
||||
potiRead = gpio_readAdc(ADC_CHANNEL_POTI); //0-4095
|
||||
//scale poti to speed levels 0-3
|
||||
uint8_t level = round( (float)potiRead / 4095 * 3 );
|
||||
//exit manual mode if preset2 released
|
||||
if ( SW_PRESET2.state == false ) {
|
||||
changeState(systemState_t::COUNTING);
|
||||
buzzer.beep(1, 1000, 100);
|
||||
}
|
||||
//P2 + P1 -> turn left
|
||||
else if ( SW_PRESET1.state && !SW_PRESET3.state ) {
|
||||
vfd_setSpeedLevel(level);
|
||||
vfd_setState(true, REV);
|
||||
sprintf(buf_disp2, "[--%02i ", level);
|
||||
// 123 45 678
|
||||
}
|
||||
//P2 + P3 -> turn right
|
||||
else if ( SW_PRESET3.state && !SW_PRESET1.state ) {
|
||||
vfd_setSpeedLevel(level);
|
||||
vfd_setState(true, FWD);
|
||||
sprintf(buf_disp2, " %02i--]", level);
|
||||
}
|
||||
//no valid switch combination -> turn off motor
|
||||
else {
|
||||
vfd_setState(false);
|
||||
sprintf(buf_disp2, " %02i ", level);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#ifdef ENCODER_TEST
|
||||
//--------------------------
|
||||
//------ 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
|
||||
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 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 //not in encoder calibration mode
|
||||
|
||||
//--------------------------
|
||||
//-------- display1 --------
|
||||
//--------------------------
|
||||
//run handle function
|
||||
displayTop.handle();
|
||||
//indicate upcoming cut when pending
|
||||
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);
|
||||
// 123456789
|
||||
//limit length to 8 digits + decimal point (drop decimal places when it does not fit)
|
||||
sprintf(buf_disp1, "%.9s", buf_tmp);
|
||||
displayTop.showString(buf_disp1);
|
||||
}
|
||||
|
||||
//--------------------------
|
||||
//-------- display2 --------
|
||||
//--------------------------
|
||||
//run handle function
|
||||
displayBot.handle();
|
||||
//notify that cutter is active
|
||||
if (cutter_isRunning()) {
|
||||
displayBot.blinkStrings("CUTTING]", "CUTTING[", 100, 100);
|
||||
}
|
||||
//show ms countdown to cut when pending
|
||||
else if (controlState == systemState_t::AUTO_CUT_WAITING) {
|
||||
sprintf(buf_disp2, " %04d ", cut_msRemaining);
|
||||
//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
|
||||
sprintf(buf_tmp, "S0LL%5.3f", (float)lengthTarget/1000); //m
|
||||
// 1234 5678
|
||||
displayBot.showString(buf_tmp);
|
||||
}
|
||||
|
||||
#endif // end else ifdef ENCODER_TEST
|
||||
|
||||
//----------------------------
|
||||
//------- control lamp -------
|
||||
//----------------------------
|
||||
//basic functionality of lamp:
|
||||
//turn on when not idling
|
||||
//TODO: add switch-case for different sates
|
||||
//e.g. blink with different frequencies in different states
|
||||
if (controlState != systemState_t::COUNTING
|
||||
&& controlState != systemState_t::TARGET_REACHED) {
|
||||
gpio_set_level(GPIO_LAMP, 1);
|
||||
}
|
||||
else {
|
||||
gpio_set_level(GPIO_LAMP, 0);
|
||||
}
|
||||
|
||||
} //end while(1)
|
||||
|
||||
} //end task_control
|
12
main/control.hpp
Normal file
@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
|
||||
//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);
|
168
main/cutter.cpp
Normal file
@ -0,0 +1,168 @@
|
||||
#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
|
||||
|
||||
|
||||
//---------------------------
|
||||
//----- local functions -----
|
||||
//---------------------------
|
||||
//declare local functions
|
||||
void setState(cutter_state_t stateNew);
|
||||
bool checkTimeout();
|
||||
|
||||
|
||||
|
||||
//---------------------------
|
||||
//----- local variables -----
|
||||
//---------------------------
|
||||
static cutter_state_t cutter_state = cutter_state_t::IDLE;
|
||||
static uint32_t timestamp_turnedOn;
|
||||
static uint32_t msTimeout = 3000;
|
||||
static const char *TAG = "cutter"; //tag for logging
|
||||
|
||||
|
||||
|
||||
//=========================
|
||||
//========= start =========
|
||||
//=========================
|
||||
void cutter_start(){
|
||||
setState(cutter_state_t::START);
|
||||
//starts motor on state change
|
||||
}
|
||||
|
||||
|
||||
|
||||
//========================
|
||||
//========= stop =========
|
||||
//========================
|
||||
void cutter_stop(){
|
||||
if(cutter_state != cutter_state_t::IDLE){
|
||||
setState(cutter_state_t::CANCELED);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//===========================
|
||||
//===== cutter_getState =====
|
||||
//===========================
|
||||
cutter_state_t cutter_getState(){
|
||||
return cutter_state;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//============================
|
||||
//===== cutter_isRunning =====
|
||||
//============================
|
||||
bool cutter_isRunning(){
|
||||
if (cutter_state == cutter_state_t::START
|
||||
|| cutter_state == cutter_state_t::CUTTING) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//---------------------------
|
||||
//-------- setState ---------
|
||||
//---------------------------
|
||||
//local function for changing state, taking corresponding actions and sending log output
|
||||
void setState(cutter_state_t stateNew){
|
||||
//only proceed and send log output when state or direction actually changed
|
||||
if ( cutter_state == stateNew) {
|
||||
//already at target state -> do nothing
|
||||
return;
|
||||
}
|
||||
|
||||
//log old and new state
|
||||
ESP_LOGI(TAG, "CHANGING state from: %s",cutter_stateStr[(int)cutter_state]);
|
||||
ESP_LOGI(TAG, "CHANGING state to: %s",cutter_stateStr[(int)stateNew]);
|
||||
//update stored state
|
||||
cutter_state = stateNew;
|
||||
|
||||
switch(stateNew){
|
||||
case cutter_state_t::IDLE:
|
||||
case cutter_state_t::TIMEOUT:
|
||||
case cutter_state_t::CANCELED:
|
||||
//--- turn motor off ---
|
||||
gpio_set_level(GPIO_RELAY, 0);
|
||||
break;
|
||||
|
||||
case cutter_state_t::START:
|
||||
case cutter_state_t::CUTTING:
|
||||
//--- turn motor on ---
|
||||
gpio_set_level(GPIO_RELAY, 1);
|
||||
//update state, timestamp
|
||||
timestamp_turnedOn = esp_log_timestamp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//--------------------------
|
||||
//------ checkTimeout ------
|
||||
//--------------------------
|
||||
//local function that checks for timeout
|
||||
bool checkTimeout(){
|
||||
if (esp_log_timestamp() - timestamp_turnedOn > msTimeout){
|
||||
setState(cutter_state_t::TIMEOUT);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
//========================
|
||||
//======== handle ========
|
||||
//========================
|
||||
//function that handles the cutter logic -> has to be run repeatedly
|
||||
void cutter_handle(){
|
||||
//handle evaluated switch (position switch)
|
||||
SW_CUTTER_POS.handle();
|
||||
//TODO add custom thresholds once at initialization?
|
||||
//SW_CUTTER_POS.minOnMs = 10;
|
||||
//SW_CUTTER_POS.minOffMs = 10;
|
||||
|
||||
switch(cutter_state){
|
||||
case cutter_state_t::IDLE:
|
||||
case cutter_state_t::TIMEOUT:
|
||||
case cutter_state_t::CANCELED:
|
||||
//wait for state change via cutter_start();
|
||||
break;
|
||||
|
||||
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 anymore
|
||||
setState(cutter_state_t::CUTTING);
|
||||
}
|
||||
//--- timeout ---
|
||||
else {
|
||||
checkTimeout();
|
||||
}
|
||||
break;
|
||||
|
||||
case cutter_state_t::CUTTING:
|
||||
//--- idle position reached ---
|
||||
//if (gpio_get_level(GPIO_CUTTER_POS_SW) == 1){ //contact not closed
|
||||
//TODO: add min on duration
|
||||
if (SW_CUTTER_POS.state == false) { //contact open -> at idle pos
|
||||
setState(cutter_state_t::IDLE);
|
||||
}
|
||||
//--- timeout ---
|
||||
else {
|
||||
checkTimeout();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
37
main/cutter.hpp
Normal file
@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
extern "C"
|
||||
{
|
||||
#include <stdio.h>
|
||||
#include "esp_log.h"
|
||||
}
|
||||
|
||||
#include "buzzer.hpp"
|
||||
#include "display.hpp"
|
||||
#include "gpio_evaluateSwitch.hpp"
|
||||
|
||||
|
||||
//--- variables ---
|
||||
//enum for state of cutter
|
||||
enum class cutter_state_t {IDLE, START, CUTTING, CANCELED, TIMEOUT};
|
||||
//string for logging the state name
|
||||
extern const char* cutter_stateStr[5];
|
||||
|
||||
|
||||
|
||||
//--- functions ---
|
||||
//trigger cut cycle (no effect if already running)
|
||||
void cutter_start();
|
||||
|
||||
//cancel cutting action
|
||||
void cutter_stop();
|
||||
|
||||
//return current state
|
||||
cutter_state_t cutter_getState();
|
||||
//TODO: bool cutter_isOn() (simply return boolean instead of enum)
|
||||
|
||||
//check if cutter is currently operating
|
||||
bool cutter_isRunning();
|
||||
|
||||
//handle function - has to be run repeatedly
|
||||
void cutter_handle();
|
204
main/display.cpp
Normal file
@ -0,0 +1,204 @@
|
||||
#include "display.hpp"
|
||||
|
||||
#include "config.h"
|
||||
|
||||
//=== variables ===
|
||||
static const char *TAG = "display"; //tag for logging
|
||||
|
||||
|
||||
|
||||
//==============================
|
||||
//======== init display ========
|
||||
//==============================
|
||||
//initialize display with parameters defined in config.hpp
|
||||
//TODO: dont use global variables/macros here
|
||||
max7219_t display_init(){
|
||||
|
||||
ESP_LOGI(TAG, "initializing display...");
|
||||
// Configure SPI bus
|
||||
spi_bus_config_t cfg;
|
||||
memset(&cfg, 0, sizeof(spi_bus_config_t)); //init bus config with 0 to prevent bugs with random flags
|
||||
cfg.mosi_io_num = DISPLAY_PIN_NUM_MOSI;
|
||||
cfg.miso_io_num = -1;
|
||||
cfg.sclk_io_num = DISPLAY_PIN_NUM_CLK;
|
||||
cfg.quadwp_io_num = -1;
|
||||
cfg.quadhd_io_num = -1;
|
||||
cfg.max_transfer_sz = 0;
|
||||
cfg.flags = 0;
|
||||
ESP_ERROR_CHECK(spi_bus_initialize(HOST, &cfg, 1));
|
||||
|
||||
// Configure device
|
||||
max7219_t dev;
|
||||
dev.cascade_size = 2;
|
||||
dev.digits = 0;
|
||||
dev.mirrored = true;
|
||||
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, DISPLAY_BRIGHTNESS));
|
||||
return dev;
|
||||
//display = dev;
|
||||
ESP_LOGI(TAG, "initializing display - done");
|
||||
}
|
||||
|
||||
|
||||
|
||||
//===================================
|
||||
//======= display welcome msg =======
|
||||
//===================================
|
||||
void display_ShowWelcomeMsg(max7219_t dev){
|
||||
//display welcome message on two 7 segment displays
|
||||
//show name and date
|
||||
ESP_LOGI(TAG, "showing startup message...");
|
||||
max7219_clear(&dev);
|
||||
max7219_draw_text_7seg(&dev, 0, "CUTTER 15.03.2024");
|
||||
// 1234567812 34 5678
|
||||
vTaskDelay(pdMS_TO_TICKS(700));
|
||||
//scroll "hello" over 2 displays
|
||||
for (int offset = 0; offset < 23; offset++) {
|
||||
max7219_clear(&dev);
|
||||
char hello[40] = " HELL0 ";
|
||||
max7219_draw_text_7seg(&dev, 0, hello + (22 - offset) );
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
}
|
||||
|
||||
//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, DISPLAY_BRIGHTNESS));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//---------------------------------
|
||||
//---------- constructor ----------
|
||||
//---------------------------------
|
||||
handledDisplay::handledDisplay(max7219_t displayDevice, uint8_t posStart_f) {
|
||||
ESP_LOGI(TAG, "Creating handledDisplay instance with startPos at %i", posStart);
|
||||
//copy variables
|
||||
dev = displayDevice;
|
||||
posStart = posStart_f;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//================================
|
||||
//========== showString ==========
|
||||
//================================
|
||||
//function that displays a given string on the display
|
||||
void handledDisplay::showString(const char * buf, uint8_t pos_f){
|
||||
//calculate actual absolute position
|
||||
posCurrent = posStart + pos_f;
|
||||
//copy the desired string
|
||||
strcpy(strOn, buf);
|
||||
//exit blinking mode
|
||||
if (mode == displayMode::BLINK_STRINGS){
|
||||
mode = displayMode::NORMAL;
|
||||
ESP_LOGI(TAG, "pos:%i - disable blink strings mode -> normal mode str='%s'", posStart, strOn);
|
||||
}
|
||||
handle(); //draws the text depending on mode
|
||||
}
|
||||
|
||||
|
||||
|
||||
//TODO: blinkStrings() and blink() are very similar - can be optimized?
|
||||
//only difficulty is the reset behaivor of blinkStrings through showString (blink does not reset)
|
||||
|
||||
//==================================
|
||||
//========== 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
|
||||
strcpy(strOn, strOn_f);
|
||||
strcpy(strOff, strOff_f);
|
||||
msOn = msOn_f;
|
||||
msOff = msOff_f;
|
||||
//if changed to blink mode just now:
|
||||
if (mode != displayMode::BLINK_STRINGS) {
|
||||
//switch mode
|
||||
ESP_LOGI(TAG, "pos:%i - toggle blink strings mode on/off=%d/%d stings='%s'/'%s'", posStart, msOn, msOff, strOn, strOff);
|
||||
mode = displayMode::BLINK_STRINGS;
|
||||
//start with on state
|
||||
state = true;
|
||||
timestampOn = esp_log_timestamp();
|
||||
}
|
||||
//run handle function for display update
|
||||
handle();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//===============================
|
||||
//============ 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
|
||||
count = count_f;
|
||||
msOn = msOn_f;
|
||||
msOff = msOff_f;
|
||||
strcpy(strOff, strOff_f);
|
||||
//FIXME this strings length must be dynamic depending on display size (posEnd - posStart) -> otherwise overwrites next segments if other display size or start pos
|
||||
//if changed to blink mode just now:
|
||||
if (mode != displayMode::BLINK) {
|
||||
//set to blink mode
|
||||
mode = displayMode::BLINK;
|
||||
ESP_LOGI(TAG, "pos:%i - start blinking: count=%i on/off=%d/%d sting='%s'",posStart, count, msOn, msOff, strOff);
|
||||
//start with off state
|
||||
state = false;
|
||||
timestampOff = esp_log_timestamp();
|
||||
}
|
||||
//run handle function for display update
|
||||
handle();
|
||||
}
|
||||
|
||||
|
||||
|
||||
//================================
|
||||
//============ handle ============
|
||||
//================================
|
||||
//function that handles time based modes
|
||||
//writes text to the 7 segment display depending on the current mode
|
||||
void handledDisplay::handle() {
|
||||
switch (mode){
|
||||
case displayMode::NORMAL:
|
||||
//daw given string
|
||||
max7219_draw_text_7seg(&dev, posCurrent, strOn);
|
||||
break;
|
||||
|
||||
case displayMode::BLINK:
|
||||
case displayMode::BLINK_STRINGS:
|
||||
//--- define state on/off ---
|
||||
if (state == true){ //display in ON state
|
||||
if (esp_log_timestamp() - timestampOn > msOn){
|
||||
state = false;
|
||||
timestampOff = esp_log_timestamp();
|
||||
//decrement remaining counts in BLINK mode each cycle
|
||||
if (mode == displayMode::BLINK) count--;
|
||||
}
|
||||
} else { //display in OFF state
|
||||
if (esp_log_timestamp() - timestampOff > msOff) {
|
||||
state = true;
|
||||
timestampOn = esp_log_timestamp();
|
||||
}
|
||||
}
|
||||
//--- draw text of current state ---
|
||||
if (state) {
|
||||
max7219_draw_text_7seg(&dev, posStart, strOn);
|
||||
} else {
|
||||
max7219_draw_text_7seg(&dev, posStart, strOff);
|
||||
}
|
||||
|
||||
//--- check finished condition in BLINK mode ---
|
||||
if (mode == displayMode::BLINK){
|
||||
if (count == 0) {
|
||||
mode = displayMode::NORMAL;
|
||||
ESP_LOGI(TAG, "pos:%i - finished blinking -> normal mode", posStart);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
64
main/display.hpp
Normal file
@ -0,0 +1,64 @@
|
||||
#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 "rotary_encoder.h"
|
||||
}
|
||||
#include <cstring>
|
||||
|
||||
|
||||
|
||||
//function for initializing the display using configuration from macros in config.h
|
||||
max7219_t display_init();
|
||||
|
||||
//show welcome message on the entire display
|
||||
void display_ShowWelcomeMsg(max7219_t displayDevice);
|
||||
|
||||
enum class displayMode {NORMAL, BLINK_STRINGS, BLINK};
|
||||
|
||||
class handledDisplay {
|
||||
public:
|
||||
//--- constructor ---
|
||||
//TODO add posMax to prevent writing in segments of other instance
|
||||
handledDisplay(max7219_t displayDevice, uint8_t posStart);
|
||||
|
||||
//--- methods ---
|
||||
void showString(const char * buf, uint8_t pos = 0);
|
||||
//function switches between two strings in a given interval
|
||||
void blinkStrings(const char * strOn, const char * strOff, uint32_t msOn, uint32_t msOff);
|
||||
//triggers certain count of blinking between currently shown string and off or optional certain string
|
||||
void blink(uint8_t count, uint32_t msOn, uint32_t msOff, const char * strOff = " ");
|
||||
//function that handles time based modes and writes text to display
|
||||
void handle(); //has to be run regularly when blink method is used
|
||||
|
||||
//TODO: blinkStrings and blink are very similar - optimize?
|
||||
//TODO: add 'scroll string' method
|
||||
|
||||
|
||||
private:
|
||||
//--- variables ---
|
||||
//config
|
||||
max7219_t dev;
|
||||
uint8_t posStart; //absolute position this display instance starts (e.g. multiple or very long 7 segment display)
|
||||
uint8_t posCurrent;
|
||||
|
||||
displayMode mode = displayMode::NORMAL;
|
||||
//blink modes
|
||||
uint8_t count = 0;
|
||||
char strOn[20];
|
||||
char strOff[20];
|
||||
bool state = false;
|
||||
uint32_t msOn;
|
||||
uint32_t msOff;
|
||||
uint32_t timestampOn;
|
||||
uint32_t timestampOff;
|
||||
};
|
79
main/encoder.cpp
Normal file
@ -0,0 +1,79 @@
|
||||
extern "C" {
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include "esp_system.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
#include "rotary_encoder.h"
|
||||
}
|
||||
|
||||
#include "encoder.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
|
||||
|
||||
//----------------------------
|
||||
//----- global variables -----
|
||||
//----------------------------
|
||||
static rotary_encoder_info_t encoder; //encoder device/info
|
||||
QueueHandle_t encoder_queue = NULL; //encoder event queue
|
||||
|
||||
|
||||
|
||||
//-------------------------
|
||||
//------- functions -------
|
||||
//-------------------------
|
||||
|
||||
//======================
|
||||
//==== 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()
|
||||
ESP_ERROR_CHECK(gpio_install_isr_service(0));
|
||||
|
||||
// Initialise the rotary encoder device with the GPIOs for A and B signals
|
||||
ESP_ERROR_CHECK(rotary_encoder_init(&encoder, ROT_ENC_A_GPIO, ROT_ENC_B_GPIO));
|
||||
ESP_ERROR_CHECK(rotary_encoder_enable_half_steps(&encoder, ENABLE_HALF_STEPS));
|
||||
#ifdef FLIP_DIRECTION
|
||||
ESP_ERROR_CHECK(rotary_encoder_flip_direction(&encoder));
|
||||
#endif
|
||||
|
||||
// Create a queue for events from the rotary encoder driver.
|
||||
// Tasks can read from this queue to receive up to date position information.
|
||||
QueueHandle_t event_queue = rotary_encoder_create_queue();
|
||||
ESP_ERROR_CHECK(rotary_encoder_set_queue(&encoder, event_queue));
|
||||
return event_queue;
|
||||
}
|
||||
|
||||
|
||||
//========================
|
||||
//=== encoder_getSteps ===
|
||||
//========================
|
||||
//get steps counted since last reset
|
||||
int encoder_getSteps(){
|
||||
// Poll current position and direction
|
||||
rotary_encoder_state_t encoderState;
|
||||
rotary_encoder_get_state(&encoder, &encoderState);
|
||||
//calculate total distance since last reset
|
||||
return encoderState.position;
|
||||
}
|
||||
|
||||
|
||||
//========================
|
||||
//=== encoder_getLenMm ===
|
||||
//========================
|
||||
//get current length in Mm since last reset
|
||||
int encoder_getLenMm(){
|
||||
return (float)encoder_getSteps() * 1000 / ENCODER_STEPS_PER_METER;
|
||||
}
|
||||
|
||||
|
||||
//=======================
|
||||
//==== encoder_reset ====
|
||||
//=======================
|
||||
//reset counted steps / length to 0
|
||||
void encoder_reset(){
|
||||
rotary_encoder_reset(&encoder);
|
||||
return;
|
||||
}
|
38
main/encoder.hpp
Normal file
@ -0,0 +1,38 @@
|
||||
/* in this file all used functions from original rotary_encoder.h library are wrapped with custom functions to reduce global variables and duplicate code
|
||||
*/
|
||||
//TODO create a cpp class for an encoder?
|
||||
#pragma once
|
||||
extern "C" {
|
||||
#include <freertos/task.h>
|
||||
}
|
||||
|
||||
|
||||
|
||||
//----------------------------
|
||||
//----- global variables -----
|
||||
//----------------------------
|
||||
//TODO ignore global encoder queue, since it is not used?
|
||||
extern QueueHandle_t encoder_queue; //encoder event queue
|
||||
|
||||
|
||||
//-------------------------
|
||||
//------- functions -------
|
||||
//-------------------------
|
||||
|
||||
//--- encoder_init ---
|
||||
//init encoder
|
||||
QueueHandle_t encoder_init();
|
||||
|
||||
//--- encoder_getSteps ---
|
||||
//get steps counted since last reset
|
||||
int encoder_getSteps();
|
||||
|
||||
|
||||
//--- encoder_getLenMm ---
|
||||
//get current length in Mm since last reset
|
||||
int encoder_getLenMm();
|
||||
|
||||
|
||||
//--- encoder_reset ---
|
||||
//reset counted steps / length to 0
|
||||
void encoder_reset();
|
23
main/global.cpp
Normal file
@ -0,0 +1,23 @@
|
||||
#include "global.hpp"
|
||||
#include "config.h"
|
||||
|
||||
|
||||
//--- inputs ---
|
||||
//create and configure objects for evaluated switches
|
||||
//gpio_evaluatedSwitch sw_gpio_39(GPIO_NUM_39, false, true); //pullup false, INVERTED (switch to 3V3, pulldown on pcb soldered)
|
||||
gpio_evaluatedSwitch sw_gpio_34(GPIO_NUM_34, false, true); //pullup false, INVERTED (switch to 3V3, pulldown on pcb soldered)
|
||||
gpio_evaluatedSwitch sw_gpio_32(GPIO_NUM_32, true, false); //pullup true, not inverted (switch to GND, internal pullup used)
|
||||
gpio_evaluatedSwitch sw_gpio_33(GPIO_NUM_33, true, false); //pullup true, not inverted (switch to GND, internal pullup used)
|
||||
gpio_evaluatedSwitch sw_gpio_25(GPIO_NUM_25, true, false); //pullup true, not inverted (switch to GND, internal pullup used)
|
||||
gpio_evaluatedSwitch sw_gpio_26(GPIO_NUM_26, true, false); //pullup true, not inverted (switch to GND, internal pullup used)
|
||||
gpio_evaluatedSwitch sw_gpio_14(GPIO_NUM_14, true, false); //pullup true, not inverted (switch to GND, internal pullup used)
|
||||
|
||||
//--- switches connected to 4 sw to analog stripboard ---
|
||||
//evaluated switches with function to obtain the current input state instead of gpio
|
||||
gpio_evaluatedSwitch sw_gpio_analog_0(&switchesAnalog_getState_sw0);
|
||||
gpio_evaluatedSwitch sw_gpio_analog_1(&switchesAnalog_getState_sw1);
|
||||
gpio_evaluatedSwitch sw_gpio_analog_2(&switchesAnalog_getState_sw2);
|
||||
gpio_evaluatedSwitch sw_gpio_analog_3(&switchesAnalog_getState_sw3);
|
||||
|
||||
//create buzzer object with no gap between beep events
|
||||
buzzer_t buzzer(GPIO_BUZZER, 0);
|
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;
|
467
main/guide-stepper.cpp
Normal file
@ -0,0 +1,467 @@
|
||||
extern "C"
|
||||
{
|
||||
#include <stdio.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_log.h"
|
||||
#include "driver/adc.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/semphr.h"
|
||||
}
|
||||
|
||||
#include "stepper.hpp"
|
||||
#include "config.h"
|
||||
#include "global.hpp"
|
||||
#include "guide-stepper.hpp"
|
||||
#include "encoder.hpp"
|
||||
#include "shutdown.hpp"
|
||||
|
||||
|
||||
//macro to get smaller value out of two
|
||||
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
|
||||
|
||||
//---------------------
|
||||
//--- configuration ---
|
||||
//---------------------
|
||||
//also see config.h
|
||||
//for pin definitions and guide parameters
|
||||
|
||||
// configure testing modes
|
||||
#define STEPPER_TEST_TRAVEL 65 // mm
|
||||
// speeds for testing with potentiometer (test task only)
|
||||
#define SPEED_MIN 2.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 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 ------
|
||||
//----------------------
|
||||
typedef enum axisDirection_t {AXIS_MOVING_LEFT = 0, AXIS_MOVING_RIGHT} axisDirection_t;
|
||||
|
||||
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){
|
||||
//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);
|
||||
|
||||
// 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){
|
||||
//--- currently moving right ---
|
||||
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
|
||||
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
|
||||
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 if (currentAxisDirection == AXIS_MOVING_LEFT){
|
||||
remaining = posNow - POS_MIN_STEPS;
|
||||
if (stepsToGo > remaining){
|
||||
stepper_setTargetPosSteps(POS_MIN_STEPS);
|
||||
stepper_waitForStop(1000);
|
||||
posNow = POS_MIN_STEPS;
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
|
||||
//----------------------
|
||||
//---- init_stepper ----
|
||||
//----------------------
|
||||
//initialize/configure stepper instance
|
||||
void init_stepper() {
|
||||
//TODO unnecessary wrapper?
|
||||
ESP_LOGW(TAG, "initializing stepper...");
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
//--------------------------
|
||||
//--- 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;
|
||||
stepper_setSpeed(speed);
|
||||
ESP_LOGW(TAG, "poti: %d (%.2lf%%), set speed to: %d", potiRead, poti*100, speed);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//============================
|
||||
//==== TASK stepper_test =====
|
||||
//============================
|
||||
//test axis without using encoder input
|
||||
#ifndef STEPPER_SIMULATE_ENCODER
|
||||
void task_stepper_test(void *pvParameter)
|
||||
{
|
||||
stepper_init();
|
||||
while(1){
|
||||
vTaskDelay(20 / portTICK_PERIOD_MS);
|
||||
|
||||
//------ handle switches ------
|
||||
//run handle functions for all switches
|
||||
SW_START.handle();
|
||||
SW_RESET.handle();
|
||||
SW_SET.handle();
|
||||
SW_PRESET1.handle();
|
||||
SW_PRESET2.handle();
|
||||
SW_PRESET3.handle();
|
||||
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) {
|
||||
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) {
|
||||
buzzer.beep(1, 200, 100);
|
||||
stepper_setTargetPosMm(50);
|
||||
}
|
||||
if (SW_PRESET2.risingEdge) {
|
||||
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 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 --
|
||||
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
|
||||
int travelStepsFull = 0;
|
||||
double travelMm = 0;
|
||||
double turns = 0;
|
||||
float currentDiameter;
|
||||
|
||||
|
||||
|
||||
//initialize stepper at task start
|
||||
init_stepper();
|
||||
//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;
|
||||
//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
|
||||
//float potiModifier = (float) gpio_readAdc(ADC_CHANNEL_POTI) / 4095; //0-4095 -> 0-1
|
||||
//ESP_LOGI(TAG, "current poti-modifier = %f", potiModifier);
|
||||
|
||||
//calculate steps to move
|
||||
cableLen = (double)encStepsDelta * 1000 / ENCODER_STEPS_PER_METER;
|
||||
//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 full step
|
||||
if (abs(travelStepsFull) > 1){
|
||||
travelStepsPartial = fmod(travelStepsExact, 1); //save remaining partial steps to be added in the next iteration
|
||||
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(5);
|
||||
}
|
||||
vTaskDelay(5 / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
30
main/guide-stepper.hpp
Normal file
@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
//task that initializes and controls the stepper motor
|
||||
//current functionality:
|
||||
// - automatically auto-homes
|
||||
// - moves left and right repeatedly
|
||||
// - updates speed from potentiometer each cycle
|
||||
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);
|