/*==========================================================================
  //  Author      : Handson Technology
  //  Project     : BTD7960 Motor Control Board driven by Arduino.
  //  Description : Geschwindigkeit und Richtung werden durch ein angeschlossenes Potentiometer gesteuert
  //  Poti an Plus und Minus, mittelabrif auf A0
  //  Source-Code : BTS7960.ino
  //  Program: Steuerung fuer DC Motor mit BTS7960 H-Bridge Treiber.
  //==========================================================================
  //  Connection to the BTS7960 board:
  //  BTS7960 Pin 1 (RPWM) to Arduino pin 11(PWM)
  //  BTS7960 Pin 2 (LPWM) to Arduino pin 12(PWM)
  //  BTS7960 Pin 3 (R_EN), 4 (L_EN), 7 (VCC) to Arduino 5V pin
  //  BTS7960 Pin 8 (GND) to Arduino GND
  //  BTS7960 Pin 5 (R_IS) and 6 (L_IS) not connected
*/
#include <LiquidCrystal_I2C.h> // LCD Display
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

int SENSOR_PIN = A0; // center pin of the potentiometer
int RPWM_Output = 11; // Arduino PWM output pin 11 connect to IBT-2 pin 1 (RPWM)
int LPWM_Output = 12; // Arduino PWM output pin 12 connect to IBT-2 pin 2 (LPWM)
void setup()
{
  lcd.begin(20, 4);
  lcd.backlight();
  lcd.clear();

  // ----------PWM Tackt fuer Pin 11&12 auf 3900Hz geaendert---------------
  TCCR1B = TCCR1B & 0b11111000 | 0x02;

  pinMode(RPWM_Output, OUTPUT);
  pinMode(LPWM_Output, OUTPUT);
}
void loop()
{
  int sensorValue = analogRead(SENSOR_PIN);
  // sensor value is in the range 0 to 1023
  // the lower half of it we use for reverse rotation the upper half for forward rotation
  if (sensorValue < 512)
  {
    // reverse rotation
    int reversePWM = -(sensorValue - 511) / 2;
    analogWrite(LPWM_Output, 0);
    analogWrite(RPWM_Output, reversePWM);
    lcd.setCursor (0, 1);
    lcd.print (F("PWM Rueck = "));
    lcd.setCursor (13, 1);
    lcd.print("    ");
    lcd.setCursor (13, 1);
    lcd.print(reversePWM);
  }
  else
  {
    // forward rotation
    int forwardPWM = (sensorValue - 512) / 2;
    analogWrite(LPWM_Output, forwardPWM);
    analogWrite(RPWM_Output, 0);
    lcd.setCursor (0, 2);
    lcd.print (F("PWM Vor   = "));
    lcd.setCursor (13, 2);
    lcd.print("    ");
    lcd.setCursor (13, 2);
    lcd.print(forwardPWM);
  }
}