// 
//arduino uno + mas-001 + DMD-150 test project--
//
// Copyright(c)2025 by motorBank. All rights reserved. 

#include <SoftwareSerial.h>
#include "Arduino.h"
//portD 0~7: arduino 0~7
//portB 0~7: arduino 8~13
//portA 0~7: arduino 14~19


#define IN1_PIN	5
#define IN2_PIN	6
#define PWM_PIN	9

#define RS485_RX	10
#define RS485_TX	2
#define RS485_DE	3

#define MAS_BTN1	13
#define MAS_BTN2	12
#define MAS_POT	A0

//------------------------------------------
class MAS001{
public:
	MAS001();

	bool button1Clicked();
	bool button2Clicked();
	uint16_t getPot();
};
MAS001::MAS001(){
	pinMode(MAS_BTN1, INPUT);
	pinMode(MAS_BTN2, INPUT);
}
bool MAS001::button1Clicked(){
	if(digitalRead(MAS_BTN1) == LOW) return true;
	return false;
}
bool MAS001::button2Clicked(){
	if(digitalRead(MAS_BTN2) == LOW) return true;
	return false;
}
uint16_t MAS001::getPot(){
	return analogRead(MAS_POT);
}
//------------------------------------------
class DMD150{
public:
	DMD150();

	void brake();
	void floating();
	void rotation(int16_t spd);
};
DMD150::DMD150(){
	pinMode(IN1_PIN, OUTPUT);
	pinMode(IN2_PIN, OUTPUT);
	pinMode(PWM_PIN, OUTPUT);
}
void DMD150::brake(){
	digitalWrite(IN1_PIN, LOW);
	digitalWrite(IN2_PIN, LOW);
	analogWrite(PWM_PIN, 0);
}
void DMD150::floating(){
	digitalWrite(IN1_PIN, HIGH);
	digitalWrite(IN2_PIN, HIGH);
	analogWrite(PWM_PIN, 0);	
}
void DMD150::rotation(int16_t spd){
	if(spd > 255) spd = 255;
	else if(spd < -255) spd = -255;

	if(spd > 0){
		digitalWrite(IN1_PIN, HIGH);
		digitalWrite(IN2_PIN, LOW);
		analogWrite(PWM_PIN, spd);
	}else{
		digitalWrite(IN1_PIN, LOW);
		digitalWrite(IN2_PIN, HIGH);
		analogWrite(PWM_PIN, -spd);		
	}
	
}
//------------------------------------------

MAS001 myShield;
DMD150 myMotor;

void setup() 
{
  Serial.begin(115200);
}

int val;
void loop() 
{
  val = myShield.getPot() / 4;      // rotation funtion takes input from -255 ~ 255
  Serial.println(val);
  
  if(myShield.button1Clicked())
  {
  	myMotor.floating(); // Use floating function to soft stop
  	// myMotor.brake(); // Use brake function to hard stop
  }
  else if(myShield.button2Clicked())
  {
  	myMotor.rotation(-val);
  }
  else
  {
  	myMotor.rotation(val);
  }
}
//-----------------code-end-------------------------

