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

#include <SoftwareSerial.h>

//portD 0~7: arduino 0~7
//portB 0~7: arduino 8~13
//portA 0~7: arduino 14~19

#define RS485_RX	10
#define RS485_TX	2
#define RS485_DE	3
#define EN_PIN	6
#define DIR_PIN	5
#define PWM_PIN	9

#define MAS_BTN1	13
#define MAS_BTN2	12
#define MAS_PORT	A0

class MAS001
{
public:
	MAS001();
	bool button1Clicked();
	bool button2Clicked();
	uint16_t getPort();
};
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::getPort(){
	return analogRead(MAS_PORT);
}


MAS001 myShield;

// RX=10번 핀, TX=2번 핀으로 설정
SoftwareSerial Serial1(10, 2); 

int nDelay;

void setup() {
  Serial.begin(9600); //아두이노의 기본 시리얼 속도 (PC 모니터용)
  Serial1.begin(9600); // RS-485 모듈과 통신할 시리얼 (S/W)
  pinMode(RS485_DE, OUTPUT);


	pinMode(EN_PIN, OUTPUT);
	pinMode(DIR_PIN, OUTPUT);

	//for pluse out at D9
	pinMode(PWM_PIN, OUTPUT);

	nDelay=1; 
}

void loop() 
{

  if (Serial.available() > 0) { // PC에서 데이터가 수신되면
    char data = Serial.read();  // 데이터 읽기
    Serial.print("Received: ");
    Serial.println(data);       // 받은 데이터 출력
    if( data=='4' )
		{ 
			Serial.print("Received:4 ");

      // 데이터 송신 (예: 100ms 마다 "Hello RS485" 송신)
      digitalWrite(RS485_DE, HIGH); // 송신 모드 활성화
      delay(10);
      Serial1.println("Hello RS485"); // RS-485 모듈로 데이터 전송
      delay(10);
      digitalWrite(RS485_DE, LOW); // 송신 종료, 수신 모드로 전환
      delay(100);

		}

  }
  // 485데이터 수신 (데이터가 오면 PC 시리얼로 출력)
  if (Serial1.available()) {
    char data = Serial1.read();
    Serial.print(data);
  }


  if(!myShield.button1Clicked()) Serial.println("Btn 1 push");
  if(!myShield.button2Clicked())
	{ 
		//Serial.print("Btn 2 pushed: ");	
		nDelay=myShield.getPort();
		//Serial.println(nDelay);	

    //pwm
    //analogWrite(9,nDelay/4);  //256

    //pluse gen
    digitalWrite(PWM_PIN, HIGH);
	  delayMicroseconds(nDelay);
	  digitalWrite(PWM_PIN, LOW);
	  delayMicroseconds(nDelay);
	}else{ nDelay=0;}

  /*
	bitSet(PORTB,1);  //D9
	if( nDelay )delayMicroseconds(nDelay);
	bitClear(PORTB,1);
	if( nDelay )delayMicroseconds(nDelay);
	*/
  //delay(100);
}

//---end_code-------------------------

