Simple program to test a steppermotor. Min/maxspeed, accelleration, distance and steps/m can be changed while the program is running for quick adjustment.

Dependencies:   mbed-rtos mbed

Fork of cmsis_rtos_queue by mbed official

main.cpp

Committer:
tuxic
Date:
2014-06-15
Revision:
4:09c35ecb3218
Parent:
3:08c16b8a78bf
Child:
5:63fe92075b71

File content as of revision 4:09c35ecb3218:

#include "mbed.h"
#include "cmsis_os.h"

DigitalOut StepLED(LED1);
DigitalOut CmdLED(LED2);
DigitalOut DirLED(LED3);

typedef struct {
    int steps;  // number of steps to take
    int speed;  // speed in steps/sec
    int accel;  // accelleration in steps/sec^2
    int maxspeed; // maximum speed in steps/sec
    int minspeed; // minimum speed in steps/sec
    bool dir;    // direction
} stepcmd;

osPoolDef(cmdpool, 16, stepcmd);
osPoolId cmdpool;

osMessageQDef(queue, 16, stepcmd);
osMessageQId  queue;
int qcnt = 0;

void read_thread (void const *args)
{
    while (true) {
        osEvent evt = osMessageGet(queue, 0);
        if (evt.status == osEventMessage) {
            stepcmd *cmd = (stepcmd*)evt.value.p;
            DirLED = cmd->dir;
            StepLED = 1;
            osDelay(100);
            StepLED = 0;
            osPoolFree(cmdpool, cmd);
            qcnt--;
        } else { // assume no info available
            osDelay(100);
        }
        osDelay(2000);
    }
}

osThreadDef(read_thread, osPriorityNormal, DEFAULT_STACK_SIZE);

int main (void)
{
    cmdpool = osPoolCreate(osPool(cmdpool));
    queue = osMessageCreate(osMessageQ(queue), NULL);

    osThreadCreate(osThread(read_thread), NULL);
    bool mydir = true;

    while (true) {
        const float startspeed = 0.05;  // speed in m/s
        const float maxspeed = 2; // speed in m/s
        const float accel = 2; // accelleration in m/s^2
        const float distance = 1.26; // maximum distance on the rod in m
        const int steps = 36000; // steps per meter
        if (qcnt < 15) {
            stepcmd *cmd = (stepcmd*)osPoolAlloc(cmdpool);
            cmd -> minspeed = int(startspeed * steps);
            cmd -> maxspeed = int(maxspeed * steps);
            cmd -> accel = int(accel * steps);
            cmd -> steps = int(distance * steps);
            cmd -> speed = cmd -> minspeed;
            cmd -> dir = mydir;
            mydir = !mydir;

            osStatus res = osMessagePut(queue, (uint32_t)cmd, 0);
            while (res != osOK) {
                osDelay(500);
                res = osMessagePut(queue, (uint32_t)cmd, 0);
            }
            printf("Storage succeeded %d\n\r", ++qcnt);
        } else {
            printf("Storage full\n\r");
        }
        osDelay(1000);
        CmdLED = ! CmdLED;
    }
}