Monday, January 3, 2011

n-gon

So this weekend I wanted to use the ST7565 display with the arduino to draw a rotating cube, but decided to start in 2D first. So I did a rotating n-gon, which just showed how distracted and out of practice I am with C. None the less, it works, for the most part. Here is the source, pictures to follow later.

point.h:

typedef struct{
int x;
int y;
} Point;


arduino sketch:

#include
#include
#include "point.h"

#define BACKLIGHT 10
#define n 4
//n as in n-gon

ST7565 glcd(9, 8, 7, 6, 5);

static Point p[n];
static Point center;
float theta=30;
//due to error the smallest usable theta appears to be
//10 degrees, 15 is even better. anything lower and the steps are uneven due to
//rounding.
float c_t; //cos of theta
float s_t; //sin theta
boolean persist = true;
float distance;


void setup(){
Serial.begin(9600);
pinMode(BACKLIGHT, OUTPUT);
digitalWrite(BACKLIGHT, HIGH);
p[0]= (Point) {40, 10};
p[1]= (Point) {80, 10};
p[2]= (Point) {80, 50};
p[3]= (Point) {40, 50};
center= (Point) {60, 30};

glcd.st7565_init();
glcd.st7565_command(CMD_DISPLAY_ON);
glcd.st7565_command(CMD_SET_ALLPTS_NORMAL);
glcd.st7565_set_brightness(0x18);
theta = theta*(3.1415/180);
s_t=sin(theta);
c_t=cos(theta);

glcd.clear();
}

void loop(){
distance = sqrt(pow(p[1].x-p[0].x, 2)+pow(p[1].y-p[0].y, 2));
Serial.println(distance);

if(persist==false){
glcd.clear();
}
for(int i=0; i glcd.drawline(p[i].x, p[i].y,
p[i+1].x, p[i+1].y, BLACK);
}
glcd.drawline(p[n-1].x, p[n-1].y,
round(p[0].x), p[0].y, BLACK);
glcd.display();

for(int i=0; i p[i]=rotate_point(p[i], true);
}
delay(500);
}

Point rotate_point(Point _p, boolean clockwise){
//c_t is cos(theta) as a global to reduce computation
//s_t is sin(theat) as a global to reduce computation
//center is a Point, which represents the local origin the point
// will rotate around
float x = _p.x-center.x;
float y = _p.y-center.y;
if(clockwise==true){
_p.x = round((c_t*x)-(s_t*y)+center.x);
_p.y = round((s_t*x)+(c_t*y)+center.y);
}else{
_p.x = round((c_t*x)+(s_t*y)+center.x);
_p.y = round((c_t*y)-(s_t*x)+center.y);
}

return _p;
}