Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
It receives the serial signals to control the switches.
#include <Servo.h>
#define BUTTON1_PIN 7
#define BUTTON2_PIN 8
#define SERVO1_PIN 9
#define SERVO2_PIN 10
#define ACTION_NUM 4
//servo set
#define RIGHT 135
#define DEFO 100
#define LEFT 65
//#define RIGHT 111
//#define DEFO 97
//#define LEFT 78
//Instance
Servo servo1;
Servo servo2;
void setup() {
Serial.begin(9600);
servo1.attach(SERVO1_PIN);
servo2.attach(SERVO2_PIN);
//Button
digitalWrite(BUTTON1_PIN,INPUT_PULLUP);
digitalWrite(BUTTON2_PIN,INPUT_PULLUP);
Serial.print("Setup OK\n");
}
//Servo action map
typedef struct _Action{
char no;
char name[20];
int servoNo;
int order; //right => 0 left => 1
}Action;
Action action[] = {
{ '1', "stand on", 1 , 0 },
{ '2', "stand off", 1 , 1 },
{ '3', "light on", 2 , 1 },
{ '4', "light off", 2 , 0 }
};
//Button map
typedef struct _Button{
int no;
char name[20];
int actionNum;
}Button;
Button button[] = {
{1, "light", 0},
{2, "stand", 2}
};
void loop() {
//Seral Read
if (Serial.available()) {
char c = Serial.read();
//Loop Action Map
for (int i = 0; i < ACTION_NUM; i++) {
if (action[i].no == c) {
Serial.print("send ");
Serial.print(action[i].name);
servoMove(action[i].servoNo, action[i].order);
//Defo
servoMove(action[i].servoNo, 2);
}
}
}
//Button Read
buttons();
}
void buttons() {
static int lastStatus[] = {0, 0};
//static int buttonList[] = {BUTTON1_PIN, BUTTON2_PIN};
static int buttonList[] = {BUTTON2_PIN};
static int buttonListSize = sizeof(buttonList) / sizeof(buttonList[0]);
//Loop Buttons
for(int i=0; i<buttonListSize; i++){
if (digitalRead(buttonList[i]) == LOW){
if (lastStatus[i] == 0) {
Serial.print("push ");
Serial.print(action[button[i].actionNum].name);
//on
servoMove(action[button[i].actionNum].servoNo, action[button[i].actionNum].order);
lastStatus[i] = 1;
} else {
Serial.print("push ");
Serial.print(action[button[i].actionNum + 1].name);
//off
servoMove(action[button[i].actionNum + 1].servoNo, action[button[i].actionNum + 1].order);
lastStatus[i] = 0;
}
}
}
}
void servoMove(int servoNo, int order){
if (order == 0 ) left(servoNo);
if (order == 1 ) right(servoNo);
if (order == 2 ) defo(servoNo);
}
//Servo Motion
void right(int servoNo){
Serial.print("\tright...\t");
if (servoNo == 1 ) for (int i=DEFO; i<=RIGHT; i++){ servo1.write(i); }
if (servoNo == 2 ) for (int i=DEFO; i<=RIGHT; i++){ servo2.write(i); }
delay(300);
//defo(servoNo);
Serial.print("[Done]\n");
}
void left(int servoNo){
Serial.print("\tleft...\t\t");
if (servoNo == 1 ) for (int i=DEFO; i>=LEFT; i--){ servo1.write(i); }
if (servoNo == 2 ) for (int i=DEFO; i>=LEFT; i--){ servo2.write(i); }
delay(300);
//defo(servoNo);
Serial.print("[Done]\n");
}
void defo(int servoNo){
if (servoNo == 1 ) servo1.write(DEFO);
if (servoNo == 2 ) servo2.write(DEFO);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment