Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Servo.h>
- #include <math.h>
- #define MOTOR_SPEED 1161 //RPM: took 310ms to rotate 6 times
- #define CIRCLE 2*M_PI/360
- #define PERIOD 50 //how many milliseconds pass before calling main
- #define MAX_SPEED 0 //if 1, will go as fast as possible
- #define MOTOR_SPEED 5 //how quickly the motor moves through its motions //also dependant on period
- #define FUNC_SWITCH_PERIOD 5000 //in milliseconds
- #define DIRECTION_SWITCH_PERIOD 10000
- #define FUNC_SWITCH_SHIFT 2500 //the shift forward of the function switcher so that it doesn't switch at thr same time as the direction switch
- int motor_angle = 0; //the motor angle can point between 0 (pointing directly down) and about 45 (pointing midway down to the horizontal plane)
- int servo_pin = 11; //digital
- int laser_pin = 10; //digital
- double x = 360;
- double millis_time = millis();
- int laser_on = 0;
- int dir = 0;
- int function_type = 0;
- double switch_func_timer = FUNC_SWITCH_SHIFT;
- double switch_dir_timer = 0;
- Servo servo;
- void laser_switch() {
- if (laser_on) {
- digitalWrite(laser_pin, 0);
- laser_on = 0;
- }
- else {
- digitalWrite(laser_pin, 1);
- laser_on = 1;
- }
- }
- //### functions
- double sine_waveform(double x) {
- double angle = 22.5+22.5*sin(x); //need to generate a sin wave with peak to peak amplitude of 45 and a vertical shift of 22.5 degrees
- return(angle);
- }
- double square_waveform(double x) {
- double angle = 0;
- angle += 45*(((int)x % 360) % 2);
- return(angle);
- }
- double stepwise_waveform(double x) {
- double angle = 0;
- angle += 15*(((int)x % 360) % 4);
- return(angle);
- }
- //###
- void function_switch() {
- function_type++;
- function_type = function_type % 3;
- }
- void dir_switch() {
- dir += 1;
- dir = dir % 2;
- }
- void setup() {
- // put your setup code here, to run once:
- pinMode(laser_pin, OUTPUT);
- Serial.begin(9600);
- servo.attach(servo_pin);
- servo.write(0); //starting angle is pointing midway between max and min angle
- delay(100);
- laser_switch();
- }
- void loop() {
- // put your main code here, to run repeatedly:
- if (MAX_SPEED || (millis()-millis_time) > PERIOD) {
- millis_time = millis();
- //direction change using y
- if (dir = 0) {
- x += MOTOR_SPEED * CIRCLE;
- }
- else {
- x -= MOTOR_SPEED * CIRCLE;
- }
- //function call based on current function type
- if (function_type == 0) {
- motor_angle = sine_waveform(x);
- } else if (function_type == 1) {
- motor_angle = square_waveform(x);
- } else if (function_type == 2) {
- motor_angle = stepwise_waveform(x);
- }
- servo.write(motor_angle);
- }
- if (millis()-switch_func_timer > FUNC_SWITCH_PERIOD) {
- function_switch();
- switch_func_timer = millis();
- }
- if (millis() - switch_dir_timer > DIRECTION_SWITCH_PERIOD) {
- dir_switch();
- switch_dir_timer = millis();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment