Skip to content

Instantly share code, notes, and snippets.

@peterneorr
Created June 24, 2021 15:21
Show Gist options
  • Save peterneorr/5f81abb35f1846df504d40c7e28a1416 to your computer and use it in GitHub Desktop.
Save peterneorr/5f81abb35f1846df504d40c7e28a1416 to your computer and use it in GitHub Desktop.
Arduino concurrency
/*
Adapted from https://create.arduino.cc/projecthub/debanshudas23/getting-started-with-stepper-motor-28byj-48-3de8c9
and the arduino "sweep" example
*/
#include <Servo.h>
#define A 2
#define B 3
#define C 4
#define D 5
#define NUMBER_OF_STEPS_PER_REV 512
Servo myServo;
void setup(){
pinMode(A,OUTPUT);
pinMode(B,OUTPUT);
pinMode(C,OUTPUT);
pinMode(D,OUTPUT);
myServo.attach(9);
}
void write(int a,int b,int c,int d){
digitalWrite(A,a);
digitalWrite(B,b);
digitalWrite(C,c);
digitalWrite(D,d);
}
int stepperTick = 1;
int servoTick = 10;
void sweepServo(){
static bool flag = true;
static int pos = 0;
static unsigned long last = millis();
unsigned long currentTime = millis();
if (currentTime-last < servoTick){
return;
}
last = millis();
myServo.write(pos);
if (flag){
pos++;
}
else{
pos--;
}
if ((pos>180) || (pos<0)){
flag=!flag;
}
}
void spinStepMotor(){
static unsigned long last = millis();
unsigned long currentTime = millis();
int delta = currentTime - last;
if (delta > (stepperTick*8)) // step 8
{
write(1,0,0,1); //8
last = currentTime;
}else if (delta > stepperTick*7){
write(0,0,0,1); //7
}else if (delta > stepperTick*6){
write(0,0,1,1); //6
}else if (delta > stepperTick*5){
write(0,0,1,0); //5
}else if (delta > stepperTick*4){
write(0,1,1,0); //4
}else if (delta > stepperTick*3){
write(0,1,0,0); //3
}else if (delta > stepperTick*2){
write(1,1,0,0); //2
}else if (delta > stepperTick){
write(1,0,0,0); //1
}
/*
* coils energized in counter clockwise order below
write(1,0,0,0); //1
write(1,1,0,0); //2
write(0,1,0,0); //3
write(0,1,1,0); //4
write(0,0,1,0); //5
write(0,0,1,1); //6
write(0,0,0,1); //7
write(1,0,0,1); //8
*/
}
void loop(){
spinStepMotor();
sweepServo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment