From ddc39175198158c4f1e8d7baa50f4f2a1d981588 Mon Sep 17 00:00:00 2001 From: Asbelos Date: Fri, 14 Aug 2020 22:54:12 +0100 Subject: [PATCH 1/4] stash incomplete --- DCCWaveform.cpp | 51 +++++++++++++++++--------------- MotorDriver.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++++++++ MotorDriver.h | 35 ++++++++++++++++++++++ 3 files changed, 140 insertions(+), 23 deletions(-) create mode 100644 MotorDriver.cpp create mode 100644 MotorDriver.h diff --git a/DCCWaveform.cpp b/DCCWaveform.cpp index 20c5205..aba716b 100644 --- a/DCCWaveform.cpp +++ b/DCCWaveform.cpp @@ -20,19 +20,26 @@ #include "Hardware.h" #include "DCCWaveform.h" #include "DIAG.h" +#include // use IDE menu Tools..Manage Libraries to locate and install TimerOne -DCCWaveform DCCWaveform::mainTrack(PREAMBLE_BITS_MAIN, true, (int)(MAIN_MAX_MILLIAMPS / MAIN_SENSE_FACTOR)); -DCCWaveform DCCWaveform::progTrack(PREAMBLE_BITS_PROG, false, (int)(PROG_MAX_MILLIAMPS / PROG_SENSE_FACTOR)); + +DCCWaveform DCCWaveform::mainTrack=NULL; +DCCWaveform DCCWaveform::progTrack=NULL; const int ACK_MIN_PULSE_RAW=65 / PROG_SENSE_FACTOR; bool DCCWaveform::progTrackSyncMain=false; -void DCCWaveform::begin() { - Hardware::init(); - Hardware::setCallback(58, interruptHandler); - mainTrack.beginTrack(); - progTrack.beginTrack(); +void DCCWaveform::begin(MotorDriver mainDriver, MotorDriver progDriver) { + + mainTrack=new DCCWaveform(PREAMBLE_BITS_MAIN, true, mainDriver); + progTrack=new DCCWaveform(PREAMBLE_BITS_PROG, false, progDriver); + progTrack.beginTrack(progDriver); + TimerA.initialize(); + TimerA.setPeriod(58); + TimerA.attachInterrupt(interruptHandler); + TimerA.start(); + } void DCCWaveform::loop() { @@ -66,8 +73,9 @@ void DCCWaveform::interruptHandler() { const byte bitMask[] = {0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; -DCCWaveform::DCCWaveform( byte preambleBits, bool isMain, int rawCurrentTrip) { +DCCWaveform::DCCWaveform( byte preambleBits, bool isMain, MotorDriver driver) { // establish appropriate pins + motorDriver=driver; rawCurrentTripValue=rawCurrentTrip; isMainTrack = isMain; packetPending = false; @@ -80,11 +88,8 @@ DCCWaveform::DCCWaveform( byte preambleBits, bool isMain, int rawCurrentTrip) { bits_sent = 0; sampleDelay = 0; lastSampleTaken = millis(); - ackPending=false; -} -void DCCWaveform::beginTrack() { - setPowerMode(POWERMODE::ON); - + ackPending=false; + setPowerMode(POWERMODE::ON); } POWERMODE DCCWaveform::getPowerMode() { @@ -94,8 +99,7 @@ POWERMODE DCCWaveform::getPowerMode() { void DCCWaveform::setPowerMode(POWERMODE mode) { powerMode = mode; bool ison = (mode == POWERMODE::ON); - Hardware::setPower(isMainTrack, ison); - Hardware::setBrake(isMainTrack, !ison); + driver.setPower( ison); if (mode == POWERMODE::ON) delay(200); } @@ -104,7 +108,7 @@ void DCCWaveform::checkPowerOverload() { if (millis() - lastSampleTaken < sampleDelay) return; lastSampleTaken = millis(); - int tripValue= rawCurrentTripValue; + int tripValue= driver.rawCurrentTripValue; if (!isMainTrack && (ackPending || progTrackSyncMain)) tripValue=ACK_CURRENT_TRIP; switch (powerMode) { @@ -113,7 +117,7 @@ void DCCWaveform::checkPowerOverload() { break; case POWERMODE::ON: // Check current - lastCurrent = Hardware::getCurrentRaw(isMainTrack); + lastCurrent = driver.getCurrentRaw(); if (lastCurrent <= tripValue) { sampleDelay = POWER_SAMPLE_ON_WAIT; if(power_good_counter<100) @@ -122,8 +126,8 @@ void DCCWaveform::checkPowerOverload() { if (power_sample_overload_wait>POWER_SAMPLE_OVERLOAD_WAIT) power_sample_overload_wait=POWER_SAMPLE_OVERLOAD_WAIT; } else { setPowerMode(POWERMODE::OVERLOAD); - unsigned int mA=Hardware::getCurrentMilliamps(isMainTrack,lastCurrent); - unsigned int maxmA=Hardware::getCurrentMilliamps(isMainTrack,tripValue); + unsigned int mA=driver.convertRawToMilliamps(lastCurrent); + unsigned int maxmA=driver.convertRawToMilliamps(tripValue); DIAG(F("\n*** %S TRACK POWER OVERLOAD current=%d max=%d offtime=%l ***\n"), isMainTrack ? F("MAIN") : F("PROG"), mA, maxmA, power_sample_overload_wait); power_good_counter=0; sampleDelay = power_sample_overload_wait; @@ -183,10 +187,11 @@ void DCCWaveform::setSignal(bool high) { if (progTrackSyncMain) { if (!isMainTrack) return; // ignore PROG track waveform while in sync // set both tracks to same signal - Hardware::setSyncSignal(high); + driver.setSyncSignal(high); + progTrack.driver.setSignal(high); return; } - Hardware::setSignal(isMainTrack,high); + driver.setSignal(high); } void DCCWaveform::interrupt2() { @@ -264,8 +269,8 @@ int DCCWaveform::getLastCurrent() { void DCCWaveform::setAckBaseline(bool debug) { if (isMainTrack) return; - ackThreshold=Hardware::getCurrentRaw(false) + ACK_MIN_PULSE_RAW; - if (debug) DIAG(F("\nACK-BASELINE %d/%dmA"),ackThreshold,Hardware::getCurrentMilliamps(false,ackThreshold)); + ackThreshold=driver.getCurrentRaw() + ACK_MIN_PULSE_RAW; + if (debug) DIAG(F("\nACK-BASELINE %d/%dmA"),ackThreshold,driver.convertRawToMilliamps(ackThreshold)); } void DCCWaveform::setAckPending(bool debug) { diff --git a/MotorDriver.cpp b/MotorDriver.cpp new file mode 100644 index 0000000..d521248 --- /dev/null +++ b/MotorDriver.cpp @@ -0,0 +1,77 @@ +/* + * © 2020, Chris Harlow. All rights reserved. + * + * This file is part of Asbelos DCC API + * + * This is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * It is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CommandStation. If not, see . + */ +#include +#include "MotorDriver.h" +#include "AnalogReadFast.h" +#include "DIAG.h" + + +#if defined(ARDUINO_ARCH_AVR) + #include // use IDE menu Tools..Manage Libraries to locate and install DIO2 + #define WritePin digitalWrite2 + #define ReadPin digitalRead2 +#else + #define WritePin digitalWrite + #define ReadPin digitalRead +#endif + +MotorDriver::MotorDriver(byte power_pin, int signal_pin, int signal_pin2, int brake_pin, int current_pin, float sense_factor, int fault_pin) { + powerPin=power_pin; + signalPin=signal_pin; + signalPin2=signal_pin2; + brakePin=brake_pin; + currentPin=current_pin; + senseFactor=sense_factor; + faultPin=fault_pin; + I32=(int) (32000 / sensefactor); + + pinMode(powerPin, OUTPUT); + pinMode(brakePin, OUTPUT); + pinMode(signalPin, OUTPUT); + if (signalPin2 != UNUSED_PIN) pinMode(signalPin2, OUTPUT); + pinMode(currentPin, INPUT); + if (faultPin != UNUSED_PIN) pinMode(faultPin, INPUT); +} + +void MotorDriver::setPower(bool on) { + WritePin(powerPin, on ? HIGH : LOW); +} +void MotorDriver::setBrake( bool on) { + WritePin(brakePin, on ? HIGH : LOW); +} + +void MotorDriver::setSignal( bool high) { + WritePin(signalPin, high ? HIGH : LOW); + if (signalPin2 != UNUSED_PIN) WritePin(signalPin2, high ? LOW : HIGH); +} + + +int MotorDriver::getCurrentRaw() { + if (faultPin != UNUSED_PIN && ReadPin(faultPin) == LOW && ReadPin(powerPin) == HIGH) + return I32: + + // IMPORTANT: This function can be called in Interrupt() time within the 56uS timer + // The default analogRead takes ~100uS which is catastrphic + // so analogReadFast is used here. (-2uS) + return analogReadFast(sensePin); +} + +unsigned int MortorDriver::convertRawToMilliamps( int raw) { + return (unsigned int)(raw * senseFactor); +} diff --git a/MotorDriver.h b/MotorDriver.h new file mode 100644 index 0000000..6fc6261 --- /dev/null +++ b/MotorDriver.h @@ -0,0 +1,35 @@ +/* + * © 2020, Chris Harlow. All rights reserved. + * + * This file is part of Asbelos DCC API + * + * This is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * It is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with CommandStation. If not, see . + */ +#ifndef MotorDriver_h +#define MotorDriver_h +// Virtualised Motor shield 1-track hardware Interface +class MotorDriver { + public: + MotorDriver(byte power_pin, byte signal_pin, byte signal_pin2, byte brake_pin, byte current_pin, float senseFactor, byte faultPin); + void setPower( bool on); + void setSignal( bool high); + void setBrake( bool on); + int getCurrentRaw(); + unsigned int convertToMilliamps( int rawValue); + private: + byte powerPin, signalPin, signalPin2, brakePin,currentPin,faultPin; + float senseFactor; + +}; +#endif From cdcb01d300a3cbfe4ae4079f8c49cd38fb3c5da9 Mon Sep 17 00:00:00 2001 From: Asbelos Date: Sat, 15 Aug 2020 11:32:32 +0100 Subject: [PATCH 2/4] Compiled motorDriver New motorDriver design... --- CVReader.ino | 10 +++- DCC.cpp | 6 +-- DCC.h | 3 +- DCCWaveform.cpp | 44 ++++++++--------- DCCWaveform.h | 8 ++-- Hardware.cpp | 124 ------------------------------------------------ Hardware.h | 36 -------------- MotorDriver.cpp | 13 ++--- MotorDriver.h | 10 ++-- Outputs.cpp | 8 ++-- Sensors.cpp | 4 +- Turnouts.cpp | 2 +- 12 files changed, 58 insertions(+), 210 deletions(-) delete mode 100644 Hardware.cpp delete mode 100644 Hardware.h diff --git a/CVReader.ino b/CVReader.ino index 144d07b..ab3c458 100644 --- a/CVReader.ino +++ b/CVReader.ino @@ -77,8 +77,14 @@ void setup() { DIAGSERIAL.begin(115200); while(!DIAGSERIAL); - // Responsibility 2: Start the DCC engine. - DCC::begin(); + // Responsibility 2: Start the DCC engine. + // Note: this provides DCC with two motor drivers, main and prog, which handle the motor shield(s) + // Standard supported devices have pre-configured macros but custome hardware installations require + // detailed pin mappings and may also require modified subclasses of the MotorDriver to implement specialist logic. + + DCC::begin(new MotorDriver(MAIN_POWER_PIN,MAIN_SIGNAL_PIN,MAIN_SIGNAL_PIN_ALT,MAIN_BRAKE_PIN,MAIN_SENSE_PIN,MAIN_SENSE_FACTOR, MAIN_MAX_MILLIAMPS,MAIN_FAULT_PIN), + new MotorDriver(PROG_POWER_PIN,PROG_SIGNAL_PIN,PROG_SIGNAL_PIN_ALT,PROG_BRAKE_PIN,PROG_SENSE_PIN,PROG_SENSE_FACTOR, PROG_MAX_MILLIAMPS,PROG_FAULT_PIN)); + // Responsibility 3: Optionally Start the WiFi interface if required. // NOTE: On a Uno you will have to provide a SoftwareSerial diff --git a/DCC.cpp b/DCC.cpp index 6d47188..67af012 100644 --- a/DCC.cpp +++ b/DCC.cpp @@ -20,7 +20,7 @@ #include "DCC.h" #include "DCCWaveform.h" #include "DIAG.h" -#include "Hardware.h" + // This module is responsible for converting API calls into // messages to be sent to the waveform generator. @@ -42,9 +42,9 @@ const byte FN_GROUP_4=0x08; const byte FN_GROUP_5=0x10; -void DCC::begin() { +void DCC::begin(MotorDriver * mainDriver, MotorDriver* progDriver) { debugMode=false; - DCCWaveform::begin(); + DCCWaveform::begin(mainDriver,progDriver); } void DCC::setThrottle( uint16_t cab, uint8_t tSpeed, bool tDirection) { diff --git a/DCC.h b/DCC.h index d549490..8a5934c 100644 --- a/DCC.h +++ b/DCC.h @@ -20,6 +20,7 @@ #define DCC_h #include #include "Config.h" +#include "MotorDriver.h" typedef void (*ACK_CALLBACK)(int result); @@ -49,7 +50,7 @@ SKIPTARGET=0xFF // jump to target class DCC { public: - static void begin(); + static void begin(MotorDriver * mainDriver, MotorDriver * progDriver); static void loop(); // Public DCC API functions diff --git a/DCCWaveform.cpp b/DCCWaveform.cpp index aba716b..890d33c 100644 --- a/DCCWaveform.cpp +++ b/DCCWaveform.cpp @@ -17,24 +17,22 @@ * along with CommandStation. If not, see . */ #include -#include "Hardware.h" + #include "DCCWaveform.h" #include "DIAG.h" +#include "MotorDriver.h" #include // use IDE menu Tools..Manage Libraries to locate and install TimerOne - -DCCWaveform DCCWaveform::mainTrack=NULL; -DCCWaveform DCCWaveform::progTrack=NULL; +DCCWaveform DCCWaveform::mainTrack(PREAMBLE_BITS_MAIN, true); +DCCWaveform DCCWaveform::progTrack(PREAMBLE_BITS_PROG, false); const int ACK_MIN_PULSE_RAW=65 / PROG_SENSE_FACTOR; bool DCCWaveform::progTrackSyncMain=false; -void DCCWaveform::begin(MotorDriver mainDriver, MotorDriver progDriver) { - - mainTrack=new DCCWaveform(PREAMBLE_BITS_MAIN, true, mainDriver); - progTrack=new DCCWaveform(PREAMBLE_BITS_PROG, false, progDriver); - progTrack.beginTrack(progDriver); +void DCCWaveform::begin(MotorDriver * mainDriver, MotorDriver * progDriver) { + mainTrack.motorDriver=mainDriver; + progTrack.motorDriver=progDriver; TimerA.initialize(); TimerA.setPeriod(58); TimerA.attachInterrupt(interruptHandler); @@ -73,10 +71,8 @@ void DCCWaveform::interruptHandler() { const byte bitMask[] = {0x00, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; -DCCWaveform::DCCWaveform( byte preambleBits, bool isMain, MotorDriver driver) { +DCCWaveform::DCCWaveform( byte preambleBits, bool isMain) { // establish appropriate pins - motorDriver=driver; - rawCurrentTripValue=rawCurrentTrip; isMainTrack = isMain; packetPending = false; memcpy(transmitPacket, idlePacket, sizeof(idlePacket)); @@ -99,7 +95,7 @@ POWERMODE DCCWaveform::getPowerMode() { void DCCWaveform::setPowerMode(POWERMODE mode) { powerMode = mode; bool ison = (mode == POWERMODE::ON); - driver.setPower( ison); + motorDriver->setPower( ison); if (mode == POWERMODE::ON) delay(200); } @@ -108,7 +104,7 @@ void DCCWaveform::checkPowerOverload() { if (millis() - lastSampleTaken < sampleDelay) return; lastSampleTaken = millis(); - int tripValue= driver.rawCurrentTripValue; + int tripValue= motorDriver->rawCurrentTripValue; if (!isMainTrack && (ackPending || progTrackSyncMain)) tripValue=ACK_CURRENT_TRIP; switch (powerMode) { @@ -117,7 +113,7 @@ void DCCWaveform::checkPowerOverload() { break; case POWERMODE::ON: // Check current - lastCurrent = driver.getCurrentRaw(); + lastCurrent = motorDriver->getCurrentRaw(); if (lastCurrent <= tripValue) { sampleDelay = POWER_SAMPLE_ON_WAIT; if(power_good_counter<100) @@ -126,8 +122,8 @@ void DCCWaveform::checkPowerOverload() { if (power_sample_overload_wait>POWER_SAMPLE_OVERLOAD_WAIT) power_sample_overload_wait=POWER_SAMPLE_OVERLOAD_WAIT; } else { setPowerMode(POWERMODE::OVERLOAD); - unsigned int mA=driver.convertRawToMilliamps(lastCurrent); - unsigned int maxmA=driver.convertRawToMilliamps(tripValue); + unsigned int mA=motorDriver->convertToMilliamps(lastCurrent); + unsigned int maxmA=motorDriver->convertToMilliamps(tripValue); DIAG(F("\n*** %S TRACK POWER OVERLOAD current=%d max=%d offtime=%l ***\n"), isMainTrack ? F("MAIN") : F("PROG"), mA, maxmA, power_sample_overload_wait); power_good_counter=0; sampleDelay = power_sample_overload_wait; @@ -187,11 +183,11 @@ void DCCWaveform::setSignal(bool high) { if (progTrackSyncMain) { if (!isMainTrack) return; // ignore PROG track waveform while in sync // set both tracks to same signal - driver.setSyncSignal(high); - progTrack.driver.setSignal(high); + motorDriver->setSignal(high); + progTrack.motorDriver->setSignal(high); return; } - driver.setSignal(high); + motorDriver->setSignal(high); } void DCCWaveform::interrupt2() { @@ -269,8 +265,8 @@ int DCCWaveform::getLastCurrent() { void DCCWaveform::setAckBaseline(bool debug) { if (isMainTrack) return; - ackThreshold=driver.getCurrentRaw() + ACK_MIN_PULSE_RAW; - if (debug) DIAG(F("\nACK-BASELINE %d/%dmA"),ackThreshold,driver.convertRawToMilliamps(ackThreshold)); + ackThreshold=motorDriver->getCurrentRaw() + ACK_MIN_PULSE_RAW; + if (debug) DIAG(F("\nACK-BASELINE %d/%dmA"),ackThreshold,motorDriver->convertToMilliamps(ackThreshold)); } void DCCWaveform::setAckPending(bool debug) { @@ -287,7 +283,7 @@ void DCCWaveform::setAckPending(bool debug) { byte DCCWaveform::getAck(bool debug) { if (ackPending) return (2); // still waiting if (debug) DIAG(F("\nACK-%S after %dmS max=%d/%dmA pulse=%duS"),ackDetected?F("OK"):F("FAIL"), ackCheckDuration, - ackMaxCurrent,Hardware::getCurrentMilliamps(false,ackMaxCurrent), ackPulseDuration); + ackMaxCurrent,motorDriver->convertToMilliamps(ackMaxCurrent), ackPulseDuration); if (ackDetected) return (1); // Yes we had an ack return(0); // pending set off but not detected means no ACK. } @@ -301,7 +297,7 @@ void DCCWaveform::checkAck() { return; } - lastCurrent=Hardware::getCurrentRaw(false); + lastCurrent=motorDriver->getCurrentRaw(); if (lastCurrent > ackMaxCurrent) ackMaxCurrent=lastCurrent; // An ACK is a pulse lasting between MIN_ACK_PULSE_DURATION and MAX_ACK_PULSE_DURATION uSecs (refer @haba) diff --git a/DCCWaveform.h b/DCCWaveform.h index f97c388..cd25106 100644 --- a/DCCWaveform.h +++ b/DCCWaveform.h @@ -19,6 +19,7 @@ #ifndef DCCWaveform_h #define DCCWaveform_h #include "Config.h" +#include "MotorDriver.h" const int POWER_SAMPLE_ON_WAIT = 100; const int POWER_SAMPLE_OFF_WAIT = 1000; @@ -45,8 +46,8 @@ const byte resetPacket[] = {0x00, 0x00, 0x00}; class DCCWaveform { public: - DCCWaveform( byte preambleBits, bool isMain, int maxRawCurrent); - static void begin(); + DCCWaveform( byte preambleBits, bool isMain); + static void begin(MotorDriver * mainDriver, MotorDriver * progDriver); static void loop(); static DCCWaveform mainTrack; static DCCWaveform progTrack; @@ -73,7 +74,7 @@ class DCCWaveform { void setSignal(bool high); bool isMainTrack; - + MotorDriver* motorDriver; // Transmission controller byte transmitPacket[MAX_PACKET_SIZE]; // packet being transmitted byte transmitLength; @@ -95,7 +96,6 @@ class DCCWaveform { POWERMODE powerMode; unsigned long lastSampleTaken; unsigned int sampleDelay; - int rawCurrentTripValue; static const int ACK_CURRENT_TRIP=1000; // During ACK processing limit can be higher unsigned long power_sample_overload_wait = POWER_SAMPLE_OVERLOAD_WAIT; unsigned int power_good_counter = 0; diff --git a/Hardware.cpp b/Hardware.cpp deleted file mode 100644 index 51a1e68..0000000 --- a/Hardware.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* - * © 2020, Chris Harlow. All rights reserved. - * - * This file is part of Asbelos DCC API - * - * This is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * It is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CommandStation. If not, see . - */ -#include -//#include // use IDE menu Tools..Manage Libraries to locate and install TimerOne -#include // use IDE menu Tools..Manage Libraries to locate and install TimerOne -#include "AnalogReadFast.h" -#include "Hardware.h" -#include "Config.h" -#include "DIAG.h" - - -#if defined(ARDUINO_ARCH_AVR) - #include // use IDE menu Tools..Manage Libraries to locate and install DIO2 - #define WritePin digitalWrite2 - #define ReadPin digitalRead2 -#else - #define WritePin digitalWrite - #define ReadPin digitalRead -#endif - -void Hardware::init() { - pinMode(MAIN_POWER_PIN, OUTPUT); - pinMode(MAIN_BRAKE_PIN, OUTPUT); - pinMode(MAIN_SIGNAL_PIN, OUTPUT); - if (MAIN_SIGNAL_PIN_ALT != UNUSED_PIN) pinMode(MAIN_SIGNAL_PIN_ALT, OUTPUT); - pinMode(MAIN_SENSE_PIN, INPUT); - if (MAIN_FAULT_PIN != UNUSED_PIN) pinMode(MAIN_FAULT_PIN, INPUT); - - pinMode(PROG_POWER_PIN, OUTPUT); - pinMode(PROG_BRAKE_PIN, OUTPUT); - pinMode(PROG_SIGNAL_PIN, OUTPUT); - if (PROG_SIGNAL_PIN_ALT != UNUSED_PIN) pinMode(PROG_SIGNAL_PIN_ALT, OUTPUT); - pinMode(PROG_SENSE_PIN, INPUT); - if (PROG_FAULT_PIN != UNUSED_PIN) pinMode(PROG_FAULT_PIN, INPUT); -} - -void Hardware::setPower(bool isMainTrack, bool on) { - WritePin(isMainTrack ? MAIN_POWER_PIN : PROG_POWER_PIN, on ? HIGH : LOW); -} -void Hardware::setBrake(bool isMainTrack, bool on) { - WritePin(isMainTrack ? MAIN_BRAKE_PIN : PROG_BRAKE_PIN, on ? HIGH : LOW); -} - -void Hardware::setSignal(bool isMainTrack, bool high) { - byte pin = isMainTrack ? MAIN_SIGNAL_PIN : PROG_SIGNAL_PIN; - byte pin2 = isMainTrack ? MAIN_SIGNAL_PIN_ALT : PROG_SIGNAL_PIN_ALT; - WritePin(pin, high ? HIGH : LOW); - if (pin2 != UNUSED_PIN) WritePin(pin2, high ? LOW : HIGH); -} - -void Hardware::setSyncSignal(bool high) { - // This sets the same signal down both tracks at the same time. - // Speed notes.... - // Objective is to get the two track signals to change as close as possible - // the high ? HIGH:LOW will only be evaluated once - // The UNUSED_PIN check will be done at compile time. - // If even more speed is required, its possible (not SAMD) to pre-prepare the - // DIO pinnumber->pincode translation so the WritePin (digitalWrite2) does not - // have to calculate the register and bit numbers every time. - - WritePin(MAIN_SIGNAL_PIN, high ? HIGH : LOW); - WritePin(PROG_SIGNAL_PIN, high ? HIGH : LOW); - if (MAIN_SIGNAL_PIN_ALT != UNUSED_PIN) WritePin(MAIN_SIGNAL_PIN_ALT, high ? LOW : HIGH); - if (PROG_SIGNAL_PIN_ALT != UNUSED_PIN) WritePin(PROG_SIGNAL_PIN_ALT, high ? LOW : HIGH); -} - -int Hardware::getCurrentRaw(bool isMainTrack) { - // tooo much crap for a interrupt routine. Will see how that goes. - byte faultpin = isMainTrack ? MAIN_FAULT_PIN : PROG_FAULT_PIN; - byte powerpin = isMainTrack ? MAIN_POWER_PIN : PROG_POWER_PIN; - - if (faultpin != UNUSED_PIN && ReadPin(faultpin) == LOW && ReadPin(powerpin) == HIGH) - return (int) (32000 / (isMainTrack ? MAIN_SENSE_FACTOR : PROG_SENSE_FACTOR)); // 32A should be enough - // IMPORTANT: This function can be called in Interrupt() time within the 56uS timer - // The default analogRead takes ~100uS which is catastrphic - // so analogReadFast is used here. (-2uS) - return analogReadFast(isMainTrack ? MAIN_SENSE_PIN : PROG_SENSE_PIN); - -} - -unsigned int Hardware::getCurrentMilliamps(bool isMainTrack, int raw) { - return (unsigned int)(raw * (isMainTrack ? MAIN_SENSE_FACTOR : PROG_SENSE_FACTOR)); -} - -void Hardware::setCallback(int duration, void (*isr)()) { - TimerA.initialize(); - TimerA.setPeriod(duration); - TimerA.attachInterrupt(isr); - TimerA.start(); -} - -// shortcut to cpu dependent high speed write -void Hardware::pinWrite(int pin, bool high) { - WritePin(pin,high); -} - -// Railcom support functions, not yet implemented -//void Hardware::setSingleCallback(int duration, void (*isr)()) { -// Timer2.initialize(duration); -// Timer2.disablePwm(TIMER1_A_PIN); -// Timer2.disablePwm(TIMER1_B_PIN); -// Timer2.attachInterrupt(isr); -//} - -//void Hardware::resetSingleCallback(int duration) { -// if (duration==0) Timer2.stop(); -// else Timer2.initialize(duration); -//} diff --git a/Hardware.h b/Hardware.h deleted file mode 100644 index 2362741..0000000 --- a/Hardware.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * © 2020, Chris Harlow. All rights reserved. - * - * This file is part of Asbelos DCC API - * - * This is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * It is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with CommandStation. If not, see . - */ -#ifndef Hardware_h -#define Hardware_h -// Virtualised hardware Interface -class Hardware { - public: - static void init(); - static void setPower(bool isMainTrack, bool on); - static void setSignal(bool isMainTrack, bool high); - static void setSyncSignal( bool high); - static unsigned int getCurrentMilliamps(bool isMainTrack, int rawValue); - static int getCurrentRaw(bool isMainTrack); - static void setBrake(bool isMainTrack, bool on); - static void setCallback(int duration, void (*isr)()); - static void pinWrite(int pin, bool high); // gets better perf and less code than arduino digitalWrite -// static void setSingleCallback(int duration, void (*isr)()); -// static void resetSingleCallback(int duration); -}; -#endif diff --git a/MotorDriver.cpp b/MotorDriver.cpp index d521248..1e06fc2 100644 --- a/MotorDriver.cpp +++ b/MotorDriver.cpp @@ -31,7 +31,8 @@ #define ReadPin digitalRead #endif -MotorDriver::MotorDriver(byte power_pin, int signal_pin, int signal_pin2, int brake_pin, int current_pin, float sense_factor, int fault_pin) { +MotorDriver::MotorDriver(byte power_pin, byte signal_pin, byte signal_pin2, byte brake_pin, + byte current_pin, float sense_factor, unsigned int trip_milliamps, byte fault_pin) { powerPin=power_pin; signalPin=signal_pin; signalPin2=signal_pin2; @@ -39,8 +40,8 @@ MotorDriver::MotorDriver(byte power_pin, int signal_pin, int signal_pin2, int br currentPin=current_pin; senseFactor=sense_factor; faultPin=fault_pin; - I32=(int) (32000 / sensefactor); - + tripMilliamps=trip_milliamps; + rawCurrentTripValue=(int)(trip_milliamps / sense_factor); pinMode(powerPin, OUTPUT); pinMode(brakePin, OUTPUT); pinMode(signalPin, OUTPUT); @@ -64,14 +65,14 @@ void MotorDriver::setSignal( bool high) { int MotorDriver::getCurrentRaw() { if (faultPin != UNUSED_PIN && ReadPin(faultPin) == LOW && ReadPin(powerPin) == HIGH) - return I32: + return (int)(32000/senseFactor); // IMPORTANT: This function can be called in Interrupt() time within the 56uS timer // The default analogRead takes ~100uS which is catastrphic // so analogReadFast is used here. (-2uS) - return analogReadFast(sensePin); + return analogReadFast(currentPin); } -unsigned int MortorDriver::convertRawToMilliamps( int raw) { +unsigned int MotorDriver::convertToMilliamps( int raw) { return (unsigned int)(raw * senseFactor); } diff --git a/MotorDriver.h b/MotorDriver.h index 6fc6261..ed88c6a 100644 --- a/MotorDriver.h +++ b/MotorDriver.h @@ -19,17 +19,21 @@ #ifndef MotorDriver_h #define MotorDriver_h // Virtualised Motor shield 1-track hardware Interface + class MotorDriver { public: - MotorDriver(byte power_pin, byte signal_pin, byte signal_pin2, byte brake_pin, byte current_pin, float senseFactor, byte faultPin); + MotorDriver(byte power_pin, byte signal_pin, byte signal_pin2, byte brake_pin, byte current_pin, float senseFactor, unsigned int tripMilliamps, byte faultPin); void setPower( bool on); void setSignal( bool high); void setBrake( bool on); int getCurrentRaw(); unsigned int convertToMilliamps( int rawValue); - private: - byte powerPin, signalPin, signalPin2, brakePin,currentPin,faultPin; + + byte powerPin, signalPin, signalPin2, brakePin,currentPin,faultPin; float senseFactor; + unsigned int tripMilliamps; + int rawCurrentTripValue; + const byte UNUSED_PIN = 255; }; #endif diff --git a/Outputs.cpp b/Outputs.cpp index d608cd9..3064b43 100644 --- a/Outputs.cpp +++ b/Outputs.cpp @@ -84,10 +84,10 @@ the state of any outputs being monitored or controlled by a separate interface o #include "Outputs.h" #include "EEStore.h" #include "StringFormatter.h" -#include "Hardware.h" + void Output::activate(int s){ data.oStatus=(s>0); // if s>0, set status to active, else inactive - Hardware::pinWrite(data.pin,data.oStatus ^ bitRead(data.iFlag,0)); // set state of output pin to HIGH or LOW depending on whether bit zero of iFlag is set to 0 (ACTIVE=HIGH) or 1 (ACTIVE=LOW) + digitalWrite(data.pin,data.oStatus ^ bitRead(data.iFlag,0)); // set state of output pin to HIGH or LOW depending on whether bit zero of iFlag is set to 0 (ACTIVE=HIGH) or 1 (ACTIVE=LOW) if(num>0) EEPROM.put(num,data.oStatus); @@ -146,7 +146,7 @@ void Output::load(){ EEPROM.get(EEStore::pointer(),data); tt=create(data.id,data.pin,data.iFlag); tt->data.oStatus=bitRead(tt->data.iFlag,1)?bitRead(tt->data.iFlag,2):data.oStatus; // restore status to EEPROM value is bit 1 of iFlag=0, otherwise set to value of bit 2 of iFlag - Hardware::pinWrite(tt->data.pin,tt->data.oStatus ^ bitRead(tt->data.iFlag,0)); + digitalWrite(tt->data.pin,tt->data.oStatus ^ bitRead(tt->data.iFlag,0)); pinMode(tt->data.pin,OUTPUT); tt->num=EEStore::pointer(); EEStore::advance(sizeof(tt->data)); @@ -195,7 +195,7 @@ Output *Output::create(int id, int pin, int iFlag, int v){ if(v==1){ tt->data.oStatus=bitRead(tt->data.iFlag,1)?bitRead(tt->data.iFlag,2):0; // sets status to 0 (INACTIVE) is bit 1 of iFlag=0, otherwise set to value of bit 2 of iFlag - Hardware::pinWrite(tt->data.pin,tt->data.oStatus ^ bitRead(tt->data.iFlag,0)); + digitalWrite(tt->data.pin,tt->data.oStatus ^ bitRead(tt->data.iFlag,0)); pinMode(tt->data.pin,OUTPUT); } diff --git a/Sensors.cpp b/Sensors.cpp index 320813e..2cdcae3 100644 --- a/Sensors.cpp +++ b/Sensors.cpp @@ -69,7 +69,7 @@ decide to ignore the return and only react to triggers. #include "Sensors.h" #include "EEStore.h" #include "StringFormatter.h" -#include "Hardware.h" + /////////////////////////////////////////////////////////////////////////////// @@ -114,7 +114,7 @@ Sensor *Sensor::create(int snum, int pin, int pullUp){ tt->active=false; tt->signal=1; pinMode(pin,INPUT); // set mode to input - Hardware::pinWrite(pin,pullUp); // don't use Arduino's internal pull-up resistors for external infrared sensors --- each sensor must have its own 1K external pull-up resistor + digitalWrite(pin,pullUp); // don't use Arduino's internal pull-up resistors for external infrared sensors --- each sensor must have its own 1K external pull-up resistor return tt; diff --git a/Turnouts.cpp b/Turnouts.cpp index 4e57e9b..0343168 100644 --- a/Turnouts.cpp +++ b/Turnouts.cpp @@ -19,7 +19,7 @@ #include "Turnouts.h" #include "EEStore.h" #include "StringFormatter.h" -#include "Hardware.h" + #include "PWMServoDriver.h" //#include "DIAG.h" // uncomment if you need DIAG below From 7a4fcd228d86d038797835eba4af6037b59ca10b Mon Sep 17 00:00:00 2001 From: Asbelos Date: Sat, 15 Aug 2020 14:10:56 +0100 Subject: [PATCH 3/4] gradually improving config --- CVReader.ino | 4 +--- Config.h | 34 ++++++++++++++-------------------- DCCWaveform.cpp | 4 ++-- 3 files changed, 17 insertions(+), 25 deletions(-) diff --git a/CVReader.ino b/CVReader.ino index ab3c458..9925386 100644 --- a/CVReader.ino +++ b/CVReader.ino @@ -82,9 +82,7 @@ void setup() { // Standard supported devices have pre-configured macros but custome hardware installations require // detailed pin mappings and may also require modified subclasses of the MotorDriver to implement specialist logic. - DCC::begin(new MotorDriver(MAIN_POWER_PIN,MAIN_SIGNAL_PIN,MAIN_SIGNAL_PIN_ALT,MAIN_BRAKE_PIN,MAIN_SENSE_PIN,MAIN_SENSE_FACTOR, MAIN_MAX_MILLIAMPS,MAIN_FAULT_PIN), - new MotorDriver(PROG_POWER_PIN,PROG_SIGNAL_PIN,PROG_SIGNAL_PIN_ALT,PROG_BRAKE_PIN,PROG_SENSE_PIN,PROG_SENSE_FACTOR, PROG_MAX_MILLIAMPS,PROG_FAULT_PIN)); - + DCC::begin(STANDARD_MOTOR_SHIELD); // Responsibility 3: Optionally Start the WiFi interface if required. // NOTE: On a Uno you will have to provide a SoftwareSerial diff --git a/Config.h b/Config.h index 1a495bc..20705c4 100644 --- a/Config.h +++ b/Config.h @@ -1,34 +1,28 @@ #ifndef Config_h #define Config_h +// *** PLEASE NOTE *** THIS FILE IS **NOT** INTENDED TO BE EDITED WHEN CONFIGURING A SYSTEM. +// It will be overwritten if the library is updated. + +// This file contains configurations for known/supported motor shields. +// A configuration defined by macro here can be used in your sketch. +// A custom hardware setup will require your sketch to create MotorDriver instances +// similar to those defined here, WITHOUT editing this file. + // Define these if you have a WiFi board on Serial1 #define WIFI #define WIFI_CONNECT_TO_SSID "RPi-JMRI" #define WIFI_CONNECT_PASSWORD "rpI-jmri" -// This hardware configuration would normally be setup using a bunch of #ifdefs. - const byte UNUSED_PIN = 255; -const byte MAIN_POWER_PIN = 3; -const byte MAIN_SIGNAL_PIN = 12; -const byte MAIN_SIGNAL_PIN_ALT = UNUSED_PIN; // for hardware that flipflops signal pins -const byte MAIN_SENSE_PIN = A0; -const byte MAIN_BRAKE_PIN = 9; -const byte MAIN_FAULT_PIN = UNUSED_PIN; +// MotorDriver(byte power_pin, byte signal_pin, byte signal_pin2, byte brake_pin, byte current_pin, float senseFactor, unsigned int tripMilliamps, byte faultPin); + +// Arduino standard Motor Shield +#define STANDARD_MOTOR_SHIELD \ + new MotorDriver(3 , 12, UNUSED_PIN, 9, A0, 2.99, 2000, UNUSED_PIN), \ + new MotorDriver(11, 13, UNUSED_PIN, 8, A1, 2.99, 250 , UNUSED_PIN) -const int MAIN_MAX_MILLIAMPS=2000; -const float MAIN_SENSE_FACTOR=2.99; // analgRead(MAIN_SENSE_PIN) * MAIN_SENSE_FACTOR = milliamps - -const byte PROG_POWER_PIN = 11; -const byte PROG_SIGNAL_PIN = 13; -const byte PROG_SIGNAL_PIN_ALT = UNUSED_PIN; // for hardware that flipflops signal pins -const byte PROG_SENSE_PIN = A1; -const byte PROG_BRAKE_PIN = 8; -const byte PROG_FAULT_PIN = UNUSED_PIN; - -const int PROG_MAX_MILLIAMPS=250; -const float PROG_SENSE_FACTOR=2.99; // analgRead(PROG_SENSE_PIN) * PROG_SENSE_FACTOR = milliamps // Allocations with memory implications..! // Base system takes approx 900 bytes + 8 per loco. Turnouts, Sensors etc are dynamically created diff --git a/DCCWaveform.cpp b/DCCWaveform.cpp index 890d33c..03bb776 100644 --- a/DCCWaveform.cpp +++ b/DCCWaveform.cpp @@ -26,7 +26,7 @@ DCCWaveform DCCWaveform::mainTrack(PREAMBLE_BITS_MAIN, true); DCCWaveform DCCWaveform::progTrack(PREAMBLE_BITS_PROG, false); -const int ACK_MIN_PULSE_RAW=65 / PROG_SENSE_FACTOR; +//const int ACK_MIN_PULSE_RAW=65 / PROG_SENSE_FACTOR; bool DCCWaveform::progTrackSyncMain=false; @@ -265,7 +265,7 @@ int DCCWaveform::getLastCurrent() { void DCCWaveform::setAckBaseline(bool debug) { if (isMainTrack) return; - ackThreshold=motorDriver->getCurrentRaw() + ACK_MIN_PULSE_RAW; + ackThreshold=motorDriver->getCurrentRaw() + (int)(65 / motorDriver->senseFactor); if (debug) DIAG(F("\nACK-BASELINE %d/%dmA"),ackThreshold,motorDriver->convertToMilliamps(ackThreshold)); } From da7275d9a43c67f845ba4dca187b2e40ea12f971 Mon Sep 17 00:00:00 2001 From: Asbelos Date: Mon, 17 Aug 2020 15:30:25 +0100 Subject: [PATCH 4/4] Motor drivers tested --- AnalogReadFast.h | 11 +++++++++++ CVReader.ino | 34 ++++++++++++++++++++-------------- Config.h | 21 +++++++++++++-------- DCC.cpp | 2 +- DCCWaveform.cpp | 5 +++-- DCCWaveform.h | 2 +- MotorDriver.cpp | 11 +++++++---- StringFormatter.h | 3 +++ 8 files changed, 59 insertions(+), 30 deletions(-) diff --git a/AnalogReadFast.h b/AnalogReadFast.h index 3cd6041..d2c14ec 100644 --- a/AnalogReadFast.h +++ b/AnalogReadFast.h @@ -89,7 +89,18 @@ int inline analogReadFast(uint8_t ADCpin) return adc; } +#elif defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_AVR_NANO_EVERY) + +int inline analogReadFast(uint8_t ADCpin) +{ byte ADC0CTRLCoriginal = ADC0.CTRLC; + ADC0.CTRLC = (ADC0CTRLCoriginal & 0b00110000) + 0b01000011; + int adc = analogRead(ADCpin); + ADC0.CTRLC = ADC0CTRLCoriginal; + return adc; +} + #else + int inline analogReadFast(uint8_t ADCpin) { byte ADCSRAoriginal = ADCSRA; ADCSRA = (ADCSRA & B11111000) | 4; diff --git a/CVReader.ino b/CVReader.ino index 9925386..96ac9b1 100644 --- a/CVReader.ino +++ b/CVReader.ino @@ -24,6 +24,14 @@ #include "DCCEXParser.h" #include "WifiInterface.h" +#ifdef ARDUINO_AVR_UNO + #include + SoftwareSerial Serial1(15,16); // YOU must get thee pins correct to use Wifi on a UNO + #define WIFI_BAUD 9600 +#else + #define WIFI_BAUD 115200 +#endif + // this code is here to demonstrate use of the DCC API and other techniques // myFilter is an example of an OPTIONAL command filter used to intercept < > commands from @@ -74,9 +82,9 @@ void setup() { // Responsibility 1: Start the usb connection for diagnostics and possible JMRI input // DIAGSERAL is normally Serial but uses SerialUSB on a SAMD processor - DIAGSERIAL.begin(115200); - while(!DIAGSERIAL); - + DIAGSERIAL.begin(115200); + while(!DIAGSERIAL); + // Responsibility 2: Start the DCC engine. // Note: this provides DCC with two motor drivers, main and prog, which handle the motor shield(s) // Standard supported devices have pre-configured macros but custome hardware installations require @@ -84,16 +92,16 @@ void setup() { DCC::begin(STANDARD_MOTOR_SHIELD); - // Responsibility 3: Optionally Start the WiFi interface if required. + // Responsibility 3: **Optionally** Start the WiFi interface if required. // NOTE: On a Uno you will have to provide a SoftwareSerial // configured for the pins connected to the Wifi card // and a 9600 baud rate. // setup(serial, F(router name), F(password) , port) - // -#ifdef WIFI - Serial1.begin(115200); - WifiInterface::setup(Serial1, F(WIFI_CONNECT_TO_SSID), F(WIFI_CONNECT_PASSWORD),F("DCCEX"),F("CVReader"),3532); // (3532 is 0xDCC decimal... ) -#endif + // (port 3532 is 0xDCC decimal.) + + + Serial1.begin(WIFI_BAUD); + WifiInterface::setup(Serial1, F("BTHub5-M6PT"), F("49de8d4862"),F("DCCEX"),F("CVReader"),3532); // This is just for demonstration purposes DIAG(F("\n===== CVReader demonstrating DCC::getLocoId() call ==========\n")); @@ -102,7 +110,7 @@ void setup() { // Optionally tell the command parser to use my example filter. // This will intercept JMRI commands from both USB and Wifi - DCCEXParser::setFilter(myFilter); + DCCEXParser::setFilter(myFilter); DIAG(F("\nReady for JMRI commands\n")); @@ -119,13 +127,11 @@ void loop() { serialParser.loop(DIAGSERIAL); // Responsibility 3: Optionally handle any incoming WiFi traffic -#ifdef WIFI WifiInterface::loop(); -#endif - // Your additional code + // Your additional loop code - // OPtionally report any decrease in memory (will automatically trigger on first call) + // Optionally report any decrease in memory (will automatically trigger on first call) int freeNow=freeMemory(); if (freeNow // use IDE menu Tools..Manage Libraries to locate and install DIO2 #define WritePin digitalWrite2 #define ReadPin digitalRead2 -#else - #define WritePin digitalWrite - #define ReadPin digitalRead #endif MotorDriver::MotorDriver(byte power_pin, byte signal_pin, byte signal_pin2, byte brake_pin, diff --git a/StringFormatter.h b/StringFormatter.h index a93dcc2..f750eec 100644 --- a/StringFormatter.h +++ b/StringFormatter.h @@ -26,6 +26,9 @@ #define DIAGSERIAL SerialUSB #elif defined(ARDUINO_ARCH_AVR) #define DIAGSERIAL Serial +#elif defined(ARDUINO_ARCH_MEGAAVR) + #define DIAGSERIAL Serial + #define __FlashStringHelper char #endif class StringFormatter