Skip to content

Instantly share code, notes, and snippets.

Created July 31, 2010 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/502252 to your computer and use it in GitHub Desktop.
Save anonymous/502252 to your computer and use it in GitHub Desktop.
#include <AFMotor.h>
int LASER=9;
int SPEED=4; //5 seems to be ok
long x,y,in;
AF_Stepper mX(48, 2);
AF_Stepper mY(48, 1);
int nextchar() {
long m=millis();
while(Serial.available()==0) {
if(millis()-m>5000) {mX.release(); mY.release(); }
} // wait till next char is available
int ch=Serial.read();
//Serial.print(ch,DEC);
return ch;
}
void step_x(long i) {
do {
if(i>0) mX.onestep(BACKWARD,MICROSTEP); //mX.step(i,BACKWARD, MICROSTEP);
else mX.onestep(FORWARD,MICROSTEP); //mX.step(-i,FORWARD, MICROSTEP);
if (i>1 or i<-1) delayMicroseconds(500); else delay(SPEED*6);
if (i>0) i--;
else i++;
}
while(i!=0);
}
void step_y(long i) {
do {
if(i>0) mY.onestep(BACKWARD,MICROSTEP); //mY.step(i,BACKWARD, MICROSTEP);
else mY.onestep(FORWARD,MICROSTEP); //mY.step(-i,FORWARD, MICROSTEP);
if (i>1 or i<-1) delayMicroseconds(200); else delay(SPEED);
if (i>0) i--;
else i++;
}
while(i!=0);
}
void trace() {
Serial.print("> ");
Serial.print(x, DEC);
Serial.print(" ");
Serial.println( y, DEC);
}
void slow() {
mX.setSpeed(1);
mY.setSpeed(4);
}
void fast() {
mX.setSpeed(400);
mY.setSpeed(650);
}
void setup() {
Serial.begin(9600);
slow();
analogWrite(LASER,5);
//while(true) nextchar();
// step_x(50); step_y(50);
}
void loop() {
int x,y;
// loop enters for each line of text
int ox=-1,oy=0;
do {
int x=y=0;
in=nextchar(); // first letter of command
while(in!=32) {
x=x*10+(in-48);
in=nextchar();
}
in=nextchar();
while(in!=32 && in!=13) {
y=y*10+(in-48);
in=nextchar();
}
// Serial.print(x, DEC);
// Serial.print(" ");
// Serial.println( y, DEC);
if(ox>-1) line(ox,6.1*oy,x,6.1*y);
ox=x;
oy=y;
}
while(in!=13);
// end of drawn line: pen up?
//Serial.println("OK");
}
// contrary to some Bresenham implementations, here
// we need to start painting from x0,y0
int line(long x0, long y0, long x1, long y1) {
long stpX,stpY,i,err,dx,dy;
if(y1>y0) stpY=1;
else stpY=-1;
if(x1>x0) stpX=1;
else stpX=-1;
// move to start of drawing
fast();
if(x!=x0) step_x(x0-x);
if(y!=y0) step_y(y0-y);
slow();
analogWrite(LASER,255);
x=x0;
y=y0; // let's move form here on
dx=abs(x1-x0);
dy=abs(y1-y0);
if(abs(y1-y0)>abs(x1-x0)) { // let's move along Y axis
err=dy/2;
while(y!=y1) {
//Serial.println(stpY);
//trace();
step_y(stpY);
y+=stpY;
err-=dx;
if (err<0) {
step_x(stpX);
x+=stpX;
err+=dy;
}
}
}
else { //let's move along X axis
err=dx/2;
while(x!=x1) {
//Serial.println(stpX);
//trace();
step_x(stpX);
x+=stpX;
err-=dy;
if (err<0) {
step_y(stpY);
y+=stpY;
err+=dx;
}
}
}
analogWrite(LASER,5);
Serial.println("..");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment