├── README.md ├── BaseStation-1.2.1 ├── PinAssignment.xls ├── PinAssignment.xlsx ├── DCC++ Arduino Sketch.pdf ├── DCCpp_Uno │ ├── SerialCommand.h │ ├── LNetCmdStation.h │ ├── Config.h │ ├── CurrentMonitor.h │ ├── PacketRegister.h │ ├── CurrentMonitor.cpp │ ├── DCCpp_Uno.h │ ├── PacketRegister.cpp │ ├── LNetCmdStation.cpp │ ├── SerialCommand.cpp │ └── DCCpp_Uno.ino └── README.md ├── comandos.txt ├── protocololoconet.txt └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # LNetDCCpp 2 | DCC++ command station with added Loconet support 3 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/PinAssignment.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ClubNCaldes/LNetDCCpp/HEAD/BaseStation-1.2.1/PinAssignment.xls -------------------------------------------------------------------------------- /BaseStation-1.2.1/PinAssignment.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ClubNCaldes/LNetDCCpp/HEAD/BaseStation-1.2.1/PinAssignment.xlsx -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCC++ Arduino Sketch.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ClubNCaldes/LNetDCCpp/HEAD/BaseStation-1.2.1/DCC++ Arduino Sketch.pdf -------------------------------------------------------------------------------- /comandos.txt: -------------------------------------------------------------------------------- 1 | encender 2 | <1> 3 | apagar 4 | <0> 5 | Registrar eh500 sin velocidad 6 | 7 | 8 | encender f0 9 | 10 | encender f0 y f2 11 | 12 | apagar todas 13 | 14 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/SerialCommand.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | SerialCommand.h 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | #ifndef SerialCommand_h 11 | #define SerialCommand_h 12 | 13 | #include "PacketRegister.h" 14 | #include "CurrentMonitor.h" 15 | #include "LNetCmdStation.h" 16 | 17 | #define MAX_COMMAND_LENGTH 30 18 | 19 | struct SerialCommand{ 20 | static char commandString[MAX_COMMAND_LENGTH+1]; 21 | static volatile RegisterList *mRegs, *pRegs; 22 | static CurrentMonitor *mMonitor; 23 | static LNetCmdStation *LNetCmdStation; 24 | static void init(volatile RegisterList *, volatile RegisterList *, CurrentMonitor *); 25 | static void parse(char *); 26 | static void process(); 27 | }; // SerialCommand 28 | 29 | #endif 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/LNetCmdStation.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | LNetCmdStation.h 4 | COPYRIGHT (c) 2016 Dani Guisado 5 | 6 | Command Station Loconet implementation 7 | 8 | **********************************************************************/ 9 | 10 | #ifndef LNetCmdStation_h 11 | #define LNetCmdStation_h 12 | 13 | #include "Config.h" 14 | #include "PacketRegister.h" 15 | #include "CurrentMonitor.h" 16 | #include 17 | #include 18 | 19 | 20 | struct LNetCmdStation{ 21 | lnMsg *LnPacket; 22 | // DGS Loconet Slot table for locomotives 23 | rwSlotDataMsg locoNetSlots[MAX_MAIN_REGISTERS]; 24 | static volatile RegisterList *mRegs, *pRegs; 25 | static CurrentMonitor *mMonitor; 26 | void init(volatile RegisterList *, volatile RegisterList *, CurrentMonitor *, LiquidCrystal *); 27 | void checkPacket(); 28 | void sendOPC_GP(byte); 29 | void processIncomingLoconetCommand(); 30 | }; 31 | 32 | #endif 33 | 34 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/Config.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | Config.h 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | ///////////////////////////////////////////////////////////////////////////////////// 11 | // 12 | // DEFINE MOTOR_SHIELD_TYPE ACCORDING TO THE FOLLOWING TABLE: 13 | // 14 | // 0 = ARDUINO MOTOR SHIELD (MAX 18V/2A PER CHANNEL) 15 | // 1 = POLOLU MC33926 MOTOR SHIELD (MAX 28V/3A PER CHANNEL) 16 | 17 | #define MOTOR_SHIELD_TYPE 0 18 | 19 | // SET THIS TO 1 IF THE MOTOR SHIELD HAS CURRENT FEEDBACK 20 | // SET THIS TO 0 IF THE MOTOR SHIELD DOES NOT HAVE CURRENT FEEDBACK 21 | #define MOTOR_SHIELD_SUPPORTS_FEEDBACK 0 22 | 23 | // SET TO ANYTHING OTHER THAN 0 TO RUN WITHOUT BUTTONS 24 | #define NO_BUTTONS 0 25 | 26 | ///////////////////////////////////////////////////////////////////////////////////// 27 | // 28 | // DEFINE NUMBER OF MAIN TRACK REGISTER 29 | 30 | #define MAX_MAIN_REGISTERS 50 31 | 32 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/CurrentMonitor.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | CurrentMonitor.h 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | #ifndef CurrentMonitor_h 11 | #define CurrentMonitor_h 12 | 13 | #include "Arduino.h" 14 | 15 | #define CURRENT_SAMPLE_SMOOTHING 0.01 16 | #define CURRENT_SAMPLE_MAX 300 17 | 18 | #define CURRENT_SAMPLE_TIME 1 19 | 20 | // defines for GlobalPowerON 21 | #define OFF 0 22 | #define ON 1 23 | #define EMERGENCY 2 24 | 25 | #define PWON_BUTTON_PIN 30 // power on push button 26 | #define PWOFF_BUTTON_PIN 31 // power off push button 27 | #define EMERGENCY_STOP_PIN 32 // external emergency stop 28 | #define PWON_LED_PIN 34 // green led for POWER ON 29 | #define PWOFF_LED_PIN 35 // red led for POWER OFF 30 | #define EMERGENCY_LED_PIN 33 31 | #define PROG_RELAY1 36 32 | #define PROG_RELAY2 37 33 | 34 | struct CurrentMonitor{ 35 | static long int sampleTime; 36 | static byte globalPowerON; 37 | int pin; 38 | float current; 39 | char *msg; 40 | CurrentMonitor(int, const char *); 41 | static boolean checkTime(); 42 | boolean check(); 43 | void setGlobalPower(uint8_t); 44 | }; 45 | 46 | #endif 47 | 48 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/README.md: -------------------------------------------------------------------------------- 1 | What’s DCC++ 2 | ------------ 3 | 4 | DCC++ is an open-source hardware and software system for the operation of DCC-equipped model railroads. 5 | 6 | The system consists of two parts, the DCC++ Base Station and the DCC++ Controller. 7 | 8 | The DCC++ Base Station consists of an Arduino micro controller fitted with an Arduino Motor Shield that can be connected directly to the tracks of a model railroad. 9 | 10 | The DCC++ Controller provides operators with a customizable GUI to control their model railroad. It is written in Java using the Processing graphics library and IDE and communicates with the DCC++ Base Station via a standard serial connection over a USB cable or wireless over BlueTooth. 11 | 12 | What’s in this Repository 13 | ------------------------- 14 | 15 | This repository, BaseStation-Uno, contains a complete DCC++ Base Station sketch designed for compiling and uploading into an Arduino Uno. All sketch files are in the folder named DCCpp_Uno. More information about the sketch can be found in the included PDF file. 16 | 17 | To utilize this sketch, simply download a zip file of this repository and open the file DCCpp_Uno.ino within the DCCpp_Uno folder using your Arduino IDE. Please do not rename the folder containing the sketch code, nor add any files to that folder. The Arduino IDE relies on the structure and name of the folder to properly display and compile the code. 18 | 19 | For more information on the overall DCC++ system, please follow the links in the PDF file. 20 | 21 | 22 | -------------------------------------------------------------------------------- /protocololoconet.txt: -------------------------------------------------------------------------------- 1 | Loco 3 a velocidad 8 2 | 3 | Locobuffer TCP started 4 | Received a message of 4 Bytes from loconet, 5 | RX: BF 00 03 43 6 | Dumping TX TCP Packet 7 | 0: 0x:52 0x:45 0x:43 0x:45 0x:49 0x:56 0x:45 0x:20 0x:62 0x:66 8 | 10 0x:20 0x:30 0x:30 0x:20 0x:30 0x:33 0x:20 0x:34 0x:33 0x:0D 9 | 20 0x:0A 10 | 11 | Received a message of 14 Bytes from loconet, 12 | RX: E7 0E 01 23 03 00 00 07 00 00 00 00 00 30 13 | Dumping TX TCP Packet 14 | 0: 0x:52 0x:45 0x:43 0x:45 0x:49 0x:56 0x:45 0x:20 0x:65 0x:37 15 | 10 0x:20 0x:30 0x:65 0x:20 0x:30 0x:31 0x:20 0x:32 0x:33 0x:20 16 | 20 0x:30 0x:33 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 0x:20 0x:30 17 | 30 0x:37 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 18 | 40 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 0x:20 0x:33 0x:30 0x:0D 19 | 50 0x:0A 20 | 21 | Received a message of 4 Bytes from loconet, 22 | RX: BA 01 01 45 23 | Dumping TX TCP Packet 24 | 0: 0x:52 0x:45 0x:43 0x:45 0x:49 0x:56 0x:45 0x:20 0x:62 0x:61 25 | 10 0x:20 0x:30 0x:31 0x:20 0x:30 0x:31 0x:20 0x:34 0x:35 0x:0D 26 | 20 0x:0A 27 | 28 | Received a message of 14 Bytes from loconet, 29 | RX: E7 0E 01 33 03 00 00 07 00 00 00 00 00 20 30 | Dumping TX TCP Packet 31 | 0: 0x:52 0x:45 0x:43 0x:45 0x:49 0x:56 0x:45 0x:20 0x:65 0x:37 32 | 10 0x:20 0x:30 0x:65 0x:20 0x:30 0x:31 0x:20 0x:33 0x:33 0x:20 33 | 20 0x:30 0x:33 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 0x:20 0x:30 34 | 30 0x:37 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 35 | 40 0x:20 0x:30 0x:30 0x:20 0x:30 0x:30 0x:20 0x:32 0x:30 0x:0D 36 | 50 0x:0A 37 | 38 | Received a message of 4 Bytes from loconet, 39 | RX: A0 01 0A 54 40 | Dumping TX TCP Packet 41 | 0: 0x:52 0x:45 0x:43 0x:45 0x:49 0x:56 0x:45 0x:20 0x:61 0x:30 42 | 10 0x:20 0x:30 0x:31 0x:20 0x:30 0x:61 0x:20 0x:35 0x:34 0x:0D 43 | 20 0x:0A 44 | 45 | Received a message of 4 Bytes from loconet, 46 | RX: A1 01 30 6F 47 | Dumping TX TCP Packet 48 | 0: 0x:52 0x:45 0x:43 0x:45 0x:49 0x:56 0x:45 0x:20 0x:61 0x:31 49 | 10 0x:20 0x:30 0x:31 0x:20 0x:33 0x:30 0x:20 0x:36 0x:66 0x:0D 50 | 20 0x:0A 51 | 52 | Received a message of 4 Bytes from loconet, 53 | RX: A2 01 00 5C 54 | Dumping TX TCP Packet 55 | 0: 0x:52 0x:45 0x:43 0x:45 0x:49 0x:56 0x:45 0x:20 0x:61 0x:32 56 | 10 0x:20 0x:30 0x:31 0x:20 0x:30 0x:30 0x:20 0x:35 0x:63 0x:0D 57 | 20 0x:0A 58 | 59 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/PacketRegister.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | PacketRegister.h 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | #ifndef PacketRegister_h 11 | #define PacketRegister_h 12 | 13 | #include "Arduino.h" 14 | 15 | // Define constants used for reading CVs from the Programming Track 16 | 17 | #define ACK_BASE_COUNT 100 // number of analogRead samples to take before each CV verify to establish a baseline current 18 | #define ACK_SAMPLE_COUNT 500 // number of analogRead samples to take when monitoring current after a CV verify (bit or byte) has been sent 19 | #define ACK_SAMPLE_SMOOTHING 0.2 // exponential smoothing to use in processing the analogRead samples after a CV verify (bit or byte) has been sent 20 | #define ACK_SAMPLE_THRESHOLD 30 // the threshold that the exponentially-smoothed analogRead samples (after subtracting the baseline current) must cross to establish ACKNOWLEDGEMENT 21 | 22 | // Define a series of registers that can be sequentially accessed over a loop to generate a repeating series of DCC Packets 23 | 24 | struct Packet{ 25 | byte buf[10]; 26 | byte nBits; 27 | }; // Packet 28 | 29 | struct Register{ 30 | Packet packet[2]; 31 | Packet *activePacket; 32 | Packet *updatePacket; 33 | void initPackets(); 34 | }; // Register 35 | 36 | struct RegisterList{ 37 | int maxNumRegs; 38 | Register *reg; 39 | Register **regMap; 40 | Register *currentReg; 41 | Register *maxLoadedReg; 42 | Register *nextReg; 43 | Packet *tempPacket; 44 | byte currentBit; 45 | byte nRepeat; 46 | int *speedTable; 47 | static byte idlePacket[]; 48 | static byte resetPacket[]; 49 | static byte bitMask[]; 50 | RegisterList(int); 51 | void loadPacket(int, byte *, int, int, int=0) volatile; 52 | void setThrottle(char *) volatile; 53 | void setFunction(char *) volatile; 54 | void setAccessory(char *) volatile; 55 | void writeTextPacket(char *) volatile; 56 | int readCV(char *) volatile; 57 | void writeCVByte(char *) volatile; 58 | void writeCVBit(char *) volatile; 59 | void writeCVByteMain(char *) volatile; 60 | void writeCVBitMain(char *s) volatile; 61 | void printPacket(int, byte *, int, int) volatile; 62 | }; 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/CurrentMonitor.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | CurrentMonitor.cpp 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | #include "DCCpp_Uno.h" 11 | #include "CurrentMonitor.h" 12 | 13 | /////////////////////////////////////////////////////////////////////////////// 14 | 15 | CurrentMonitor::CurrentMonitor(int pin, const char *msg){ 16 | this->pin=pin; 17 | this->msg=msg; 18 | current=0; 19 | setGlobalPower(OFF); 20 | } // CurrentMonitor::CurrentMonitor 21 | 22 | boolean CurrentMonitor::checkTime(){ 23 | if(millis()-sampleTimeCURRENT_SAMPLE_MAX && digitalRead(SIGNAL_ENABLE_PIN_PROG)==HIGH){ // current overload and Prog Signal is on (or could have checked Main Signal, since both are always on or off together) 32 | setGlobalPower(EMERGENCY); 33 | return(true); 34 | } 35 | return(false); 36 | } // CurrentMonitor::check 37 | 38 | void CurrentMonitor::setGlobalPower(uint8_t pPower) 39 | { 40 | if (pPower==ON) 41 | { 42 | digitalWrite(SIGNAL_ENABLE_PIN_PROG,HIGH); 43 | digitalWrite(SIGNAL_ENABLE_PIN_MAIN,HIGH); 44 | digitalWrite(PWON_LED_PIN, HIGH); 45 | digitalWrite(PWOFF_LED_PIN, LOW); 46 | digitalWrite(EMERGENCY_LED_PIN, LOW); 47 | this->globalPowerON=ON; 48 | INTERFACE.println(""); 49 | } 50 | else if (pPower==OFF) 51 | { 52 | digitalWrite(SIGNAL_ENABLE_PIN_PROG,LOW); 53 | digitalWrite(SIGNAL_ENABLE_PIN_MAIN,LOW); 54 | digitalWrite(PWON_LED_PIN, LOW); 55 | digitalWrite(PWOFF_LED_PIN, HIGH); 56 | digitalWrite(EMERGENCY_LED_PIN, LOW); 57 | this->globalPowerON=OFF; 58 | INTERFACE.println(""); 59 | } 60 | else if (pPower==EMERGENCY) 61 | { 62 | digitalWrite(SIGNAL_ENABLE_PIN_PROG,LOW); 63 | digitalWrite(SIGNAL_ENABLE_PIN_MAIN,LOW); 64 | digitalWrite(PWON_LED_PIN, LOW); 65 | digitalWrite(PWOFF_LED_PIN, LOW); 66 | digitalWrite(EMERGENCY_LED_PIN, HIGH); 67 | this->globalPowerON=EMERGENCY; 68 | INTERFACE.println(""); 69 | } 70 | } 71 | 72 | long int CurrentMonitor::sampleTime=0; 73 | byte CurrentMonitor::globalPowerON=OFF; 74 | 75 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/DCCpp_Uno.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | DCCpp_Uno.h 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | #include "Config.h" 11 | 12 | #ifndef DCCpp_Uno_h 13 | #define DCCpp_Uno_h 14 | 15 | ///////////////////////////////////////////////////////////////////////////////////// 16 | // AUTO-SELECT ARDUINO BOARD 17 | ///////////////////////////////////////////////////////////////////////////////////// 18 | 19 | #ifdef ARDUINO_AVR_MEGA // is using Mega 1280, define as Mega 2560 (pinouts and functionality are identical) 20 | #define ARDUINO_AVR_MEGA2560 21 | #endif 22 | 23 | /*--------------------------------------------------------------- 24 | * PINS D3, D8, D9, D11, D12, D13, A0, A1 used by Motor Shield 25 | * PINS D47, D48 used by Loconet Shield 26 | * PINS D50, D51, D52, D53, D10, D4 used by Ethernet Shield 27 | ----------------------------------------------------------------*/ 28 | #if defined ARDUINO_AVR_MEGA2560 29 | 30 | #define ARDUINO_TYPE "MEGA" 31 | 32 | #define DCC_SIGNAL_PIN_MAIN 12 // Arduino Mega - uses OC1B 33 | #define DCC_SIGNAL_PIN_PROG 2 // Arduino Mega - uses OC3B 34 | 35 | 36 | #else 37 | 38 | #error CANNOT COMPILE - DCC++ ONLY WORKS WITH AN ARDUINO MEGA 1280/2560 39 | 40 | #endif 41 | 42 | ///////////////////////////////////////////////////////////////////////////////////// 43 | // SELECT MOTOR SHIELD 44 | ///////////////////////////////////////////////////////////////////////////////////// 45 | 46 | #if MOTOR_SHIELD_TYPE == 0 47 | 48 | #define MOTOR_SHIELD_NAME "ARDUINO MOTOR SHIELD" 49 | 50 | #define SIGNAL_ENABLE_PIN_MAIN 3 51 | #define SIGNAL_ENABLE_PIN_PROG 11 52 | 53 | #define CURRENT_MONITOR_PIN_MAIN A0 54 | #define CURRENT_MONITOR_PIN_PROG A1 55 | 56 | #define DIRECTION_MOTOR_CHANNEL_PIN_A 12 57 | #define DIRECTION_MOTOR_CHANNEL_PIN_B 13 58 | 59 | #elif MOTOR_SHIELD_TYPE == 1 60 | 61 | #define MOTOR_SHIELD_NAME "POLOLU MC33926 MOTOR SHIELD" 62 | 63 | #define SIGNAL_ENABLE_PIN_MAIN 9 64 | #define SIGNAL_ENABLE_PIN_PROG 11 65 | 66 | #define CURRENT_MONITOR_PIN_MAIN A0 67 | #define CURRENT_MONITOR_PIN_PROG A1 68 | 69 | #define DIRECTION_MOTOR_CHANNEL_PIN_A 7 70 | #define DIRECTION_MOTOR_CHANNEL_PIN_B 8 71 | 72 | #else 73 | 74 | #error CANNOT COMPILE - PLEASE SELECT A PROPER MOTOR SHIELD TYPE 75 | 76 | #endif 77 | 78 | ///////////////////////////////////////////////////////////////////////////////////// 79 | // SELECT COMMUNICATION INTERFACE 80 | ///////////////////////////////////////////////////////////////////////////////////// 81 | 82 | #if COMM_TYPE == 0 83 | 84 | #define INTERFACE Serial 85 | 86 | #elif COMM_TYPE == 1 87 | 88 | #define INTERFACE eServer 89 | #define SDCARD_CS 4 90 | 91 | #else 92 | 93 | #error CANNOT COMPILE - PLEASE SELECT A PROPER COMMUNICATIONS INTERFACE TYPE 94 | 95 | #endif 96 | 97 | ///////////////////////////////////////////////////////////////////////////////////// 98 | // SET WHETHER TO SHOW PACKETS - DIAGNOSTIC MODE ONLY 99 | ///////////////////////////////////////////////////////////////////////////////////// 100 | 101 | // If SHOW_PACKETS is set to 1, then for select main operations track commands that modify an internal DCC packet register, 102 | // if printFlag for that command is also set to 1, DCC++ BASE STATION will additionally return the 103 | // DCC packet contents of the modified register in the following format: 104 | 105 | // <* REG: B1 B2 ... Bn CSUM / REPEAT> 106 | // 107 | // REG: the number of the main operations track packet register that was modified 108 | // B1: the first hexidecimal byte of the DCC packet 109 | // B2: the second hexidecimal byte of the DCC packet 110 | // Bn: the nth hexidecimal byte of the DCC packet 111 | // CSUM: a checksum byte that is required to be the final byte in any DCC packet 112 | // REPEAT: the number of times the DCC packet was re-transmitted to the tracks after its iniital transmission 113 | 114 | #define SHOW_PACKETS 0 // set to zero to disable printing of every packet for select main operations track commands 115 | 116 | ///////////////////////////////////////////////////////////////////////////////////// 117 | 118 | #endif 119 | 120 | 121 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/PacketRegister.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | PacketRegister.cpp 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | #include "DCCpp_Uno.h" 11 | #include "PacketRegister.h" 12 | 13 | /////////////////////////////////////////////////////////////////////////////// 14 | 15 | void Register::initPackets(){ 16 | activePacket=packet; 17 | updatePacket=packet+1; 18 | } // Register::initPackets 19 | 20 | /////////////////////////////////////////////////////////////////////////////// 21 | 22 | RegisterList::RegisterList(int maxNumRegs){ 23 | this->maxNumRegs=maxNumRegs; 24 | reg=(Register *)calloc((maxNumRegs+1),sizeof(Register)); 25 | for(int i=0;i<=maxNumRegs;i++) 26 | reg[i].initPackets(); 27 | regMap=(Register **)calloc((maxNumRegs+1),sizeof(Register *)); 28 | speedTable=(int *)calloc((maxNumRegs+1),sizeof(int *)); 29 | currentReg=reg; 30 | regMap[0]=reg; 31 | maxLoadedReg=reg; 32 | nextReg=NULL; 33 | currentBit=0; 34 | nRepeat=0; 35 | } // RegisterList::RegisterList 36 | 37 | /////////////////////////////////////////////////////////////////////////////// 38 | 39 | // LOAD DCC PACKET INTO TEMPORARY REGISTER 0, OR PERMANENT REGISTERS 1 THROUGH DCC_PACKET_QUEUE_MAX (INCLUSIVE) 40 | // CONVERTS 2, 3, 4, OR 5 BYTES INTO A DCC BIT STREAM WITH PREAMBLE, CHECKSUM, AND PROPER BYTE SEPARATORS 41 | // BITSTREAM IS STORED IN UP TO A 10-BYTE ARRAY (USING AT MOST 76 OF 80 BITS) 42 | 43 | void RegisterList::loadPacket(int nReg, byte *b, int nBytes, int nRepeat, int printFlag) volatile { 44 | 45 | nReg=nReg%((maxNumRegs+1)); // force nReg to be between 0 and maxNumRegs, inclusive 46 | 47 | while(nextReg!=NULL); // pause while there is a Register already waiting to be updated -- nextReg will be reset to NULL by interrupt when prior Register updated fully processed 48 | 49 | if(regMap[nReg]==NULL) // first time this Register Number has been called 50 | regMap[nReg]=maxLoadedReg+1; // set Register Pointer for this Register Number to next available Register 51 | 52 | Register *r=regMap[nReg]; // set Register to be updated 53 | Packet *p=r->updatePacket; // set Packet in the Register to be updated 54 | byte *buf=p->buf; // set byte buffer in the Packet to be updated 55 | 56 | b[nBytes]=b[0]; // copy first byte into what will become the checksum byte 57 | for(int i=1;i>1; // b[2], bits 7-1 67 | buf[6]=b[2]<<7; // b[2], bit 0 68 | 69 | if(nBytes==3){ 70 | p->nBits=49; 71 | } else{ 72 | buf[6]+=b[3]>>2; // b[3], bits 7-2 73 | buf[7]=b[3]<<6; // b[3], bit 1-0 74 | if(nBytes==4){ 75 | p->nBits=58; 76 | } else{ 77 | buf[7]+=b[4]>>3; // b[4], bits 7-3 78 | buf[8]=b[4]<<5; // b[4], bits 2-0 79 | if(nBytes==5){ 80 | p->nBits=67; 81 | } else{ 82 | buf[8]+=b[5]>>4; // b[5], bits 7-4 83 | buf[9]=b[5]<<4; // b[5], bits 3-0 84 | p->nBits=76; 85 | } // >5 bytes 86 | } // >4 bytes 87 | } // >3 bytes 88 | 89 | nextReg=r; 90 | this->nRepeat=nRepeat; 91 | maxLoadedReg=max(maxLoadedReg,nextReg); 92 | 93 | if(printFlag && SHOW_PACKETS) // for debugging purposes 94 | printPacket(nReg,b,nBytes,nRepeat); 95 | 96 | } // RegisterList::loadPacket 97 | 98 | /////////////////////////////////////////////////////////////////////////////// 99 | 100 | void RegisterList::setThrottle(char *s) volatile{ 101 | byte b[5]; // save space for checksum byte 102 | int nReg; 103 | int cab; 104 | int tSpeed; 105 | int tDirection; 106 | byte nB=0; 107 | 108 | if(sscanf(s,"%d %d %d %d",&nReg,&cab,&tSpeed,&tDirection)!=4) 109 | return; 110 | 111 | if(nReg<1 || nReg>maxNumRegs) 112 | return; 113 | 114 | if(cab>127) 115 | b[nB++]=highByte(cab) | 0xC0; // convert train number into a two-byte address 116 | 117 | b[nB++]=lowByte(cab); 118 | b[nB++]=0x3F; // 128-step speed control byte 119 | if(tSpeed>=0) 120 | b[nB++]=tSpeed+(tSpeed>0)+tDirection*128; // max speed is 126, but speed codes range from 2-127 (0=stop, 1=emergency stop) 121 | else{ 122 | b[nB++]=1; 123 | tSpeed=0; 124 | } 125 | 126 | loadPacket(nReg,b,nB,0,1); 127 | 128 | INTERFACE.print(""); 134 | 135 | speedTable[nReg]=tDirection==1?tSpeed:-tSpeed; 136 | 137 | } // RegisterList::setThrottle() 138 | 139 | /////////////////////////////////////////////////////////////////////////////// 140 | 141 | void RegisterList::setFunction(char *s) volatile{ 142 | byte b[5]; // save space for checksum byte 143 | int cab; 144 | int fByte, eByte; 145 | int nParams; 146 | byte nB=0; 147 | 148 | nParams=sscanf(s,"%d %d %d",&cab,&fByte,&eByte); 149 | 150 | if(nParams<2) 151 | return; 152 | 153 | if(cab>127) 154 | b[nB++]=highByte(cab) | 0xC0; // convert train number into a two-byte address 155 | 156 | b[nB++]=lowByte(cab); 157 | 158 | if(nParams==2){ // this is a request for functions FL,F1-F12 159 | b[nB++]=(fByte | 0x80) & 0xBF; // for safety this guarantees that first nibble of function byte will always be of binary form 10XX which should always be the case for FL,F1-F12 160 | } else { // this is a request for functions F13-F28 161 | b[nB++]=(fByte | 0xDE) & 0xDF; // for safety this guarantees that first byte will either be 0xDE (for F13-F20) or 0xDF (for F21-F28) 162 | b[nB++]=eByte; 163 | } 164 | 165 | INTERFACE.print(""); 170 | 171 | loadPacket(0,b,nB,4,1); 172 | 173 | } // RegisterList::setFunction() 174 | 175 | /////////////////////////////////////////////////////////////////////////////// 176 | 177 | void RegisterList::setAccessory(char *s) volatile{ 178 | byte b[3]; // save space for checksum byte 179 | int aAdd; // the accessory address (0-511 = 9 bits) 180 | int aNum; // the accessory number within that address (0-3) 181 | int activate; // flag indicated whether accessory should be activated (1) or deactivated (0) following NMRA recommended convention 182 | 183 | if(sscanf(s,"%d %d %d",&aAdd,&aNum,&activate)!=3) 184 | return; 185 | 186 | b[0]=aAdd%64+128; // first byte is of the form 10AAAAAA, where AAAAAA represent 6 least signifcant bits of accessory address 187 | b[1]=((((aAdd/64)%8)<<4) + (aNum%4<<1) + activate%2) ^ 0xF8; // second byte is of the form 1AAACDDD, where C should be 1, and the least significant D represent activate/deactivate 188 | 189 | loadPacket(0,b,2,4,1); 190 | 191 | } // RegisterList::setAccessory() 192 | 193 | /////////////////////////////////////////////////////////////////////////////// 194 | 195 | void RegisterList::writeTextPacket(char *s) volatile{ 196 | 197 | int nReg; 198 | byte b[6]; 199 | int nBytes; 200 | volatile RegisterList *regs; 201 | 202 | nBytes=sscanf(s,"%d %x %x %x %x %x",&nReg,b,b+1,b+2,b+3,b+4)-1; 203 | 204 | if(nBytes<2 || nBytes>5){ // invalid valid packet 205 | INTERFACE.print(""); 206 | return; 207 | } 208 | 209 | loadPacket(nReg,b,nBytes,0,1); 210 | 211 | } // RegisterList::writeTextPacket() 212 | 213 | /////////////////////////////////////////////////////////////////////////////// 214 | 215 | int RegisterList::readCV(char *s) volatile{ 216 | byte bRead[4]; 217 | int bValue; 218 | int c,d,base; 219 | int cv, callBack, callBackSub; 220 | 221 | if(sscanf(s,"%d %d %d",&cv,&callBack,&callBackSub)!=3) // cv = 1-1024 222 | return(-1); 223 | cv--; // actual CV addresses are cv-1 (0-1023) 224 | 225 | bRead[0]=0x78+(highByte(cv)&0x03); // any CV>1023 will become modulus(1024) due to bit-mask of 0x03 226 | bRead[1]=lowByte(cv); 227 | 228 | bValue=0; 229 | 230 | for(int i=0;i<8;i++){ 231 | 232 | c=0; 233 | d=0; 234 | base=0; 235 | 236 | for(int j=0;jACK_SAMPLE_THRESHOLD) 249 | d=1; 250 | } 251 | 252 | bitWrite(bValue,i,d); 253 | } 254 | 255 | c=0; 256 | d=0; 257 | base=0; 258 | 259 | for(int j=0;jACK_SAMPLE_THRESHOLD) 273 | d=1; 274 | } 275 | 276 | if(d==0) // verify unsuccessful 277 | bValue=-1; 278 | 279 | INTERFACE.print(""); 288 | 289 | return(bValue); 290 | } // RegisterList::readCV() 291 | 292 | /////////////////////////////////////////////////////////////////////////////// 293 | 294 | void RegisterList::writeCVByte(char *s) volatile{ 295 | byte bWrite[4]; 296 | int bValue; 297 | int c,d,base; 298 | int cv, callBack, callBackSub; 299 | 300 | if(sscanf(s,"%d %d %d %d",&cv,&bValue,&callBack,&callBackSub)!=4) // cv = 1-1024 301 | return; 302 | cv--; // actual CV addresses are cv-1 (0-1023) 303 | 304 | bWrite[0]=0x7C+(highByte(cv)&0x03); // any CV>1023 will become modulus(1024) due to bit-mask of 0x03 305 | bWrite[1]=lowByte(cv); 306 | bWrite[2]=bValue; 307 | 308 | loadPacket(0,resetPacket,2,1); 309 | loadPacket(0,bWrite,3,4); 310 | loadPacket(0,resetPacket,2,1); 311 | loadPacket(0,idlePacket,2,10); 312 | 313 | c=0; 314 | d=0; 315 | base=0; 316 | 317 | for(int j=0;jACK_SAMPLE_THRESHOLD) 330 | d=1; 331 | } 332 | 333 | if (MOTOR_SHIELD_SUPPORTS_FEEDBACK > 0) 334 | { 335 | if(d==0) { // verify unsuccessful 336 | bValue=-1; 337 | } else { 338 | bValue=-2; 339 | } 340 | } 341 | 342 | INTERFACE.print(""); 351 | 352 | } // RegisterList::writeCVByte() 353 | 354 | /////////////////////////////////////////////////////////////////////////////// 355 | 356 | void RegisterList::writeCVBit(char *s) volatile{ 357 | byte bWrite[4]; 358 | int bNum,bValue; 359 | int c,d,base; 360 | int cv, callBack, callBackSub; 361 | 362 | if(sscanf(s,"%d %d %d %d %d",&cv,&bNum,&bValue,&callBack,&callBackSub)!=5) // cv = 1-1024 363 | return; 364 | cv--; // actual CV addresses are cv-1 (0-1023) 365 | bValue=bValue%2; 366 | bNum=bNum%8; 367 | 368 | bWrite[0]=0x78+(highByte(cv)&0x03); // any CV>1023 will become modulus(1024) due to bit-mask of 0x03 369 | bWrite[1]=lowByte(cv); 370 | bWrite[2]=0xF0+bValue*8+bNum; 371 | 372 | loadPacket(0,resetPacket,2,1); 373 | loadPacket(0,bWrite,3,4); 374 | loadPacket(0,resetPacket,2,1); 375 | loadPacket(0,idlePacket,2,10); 376 | 377 | c=0; 378 | d=0; 379 | base=0; 380 | 381 | for(int j=0;jACK_SAMPLE_THRESHOLD) 394 | d=1; 395 | } 396 | 397 | if (MOTOR_SHIELD_SUPPORTS_FEEDBACK > 0) 398 | { 399 | if(d==0) { // verify unsuccessful 400 | bValue=-1; 401 | } else { 402 | bValue=-2; 403 | } 404 | } 405 | 406 | INTERFACE.print(""); 417 | 418 | } // RegisterList::writeCVBit() 419 | 420 | /////////////////////////////////////////////////////////////////////////////// 421 | 422 | void RegisterList::writeCVByteMain(char *s) volatile{ 423 | byte b[6]; // save space for checksum byte 424 | int cab; 425 | int cv; 426 | int bValue; 427 | byte nB=0; 428 | 429 | if(sscanf(s,"%d %d %d",&cab,&cv,&bValue)!=3) 430 | return; 431 | cv--; 432 | 433 | if(cab>127) 434 | b[nB++]=highByte(cab) | 0xC0; // convert train number into a two-byte address 435 | 436 | b[nB++]=lowByte(cab); 437 | b[nB++]=0xEC+(highByte(cv)&0x03); // any CV>1023 will become modulus(1024) due to bit-mask of 0x03 438 | b[nB++]=lowByte(cv); 439 | b[nB++]=bValue; 440 | 441 | loadPacket(0,b,nB,4); 442 | 443 | } // RegisterList::writeCVByteMain() 444 | 445 | /////////////////////////////////////////////////////////////////////////////// 446 | 447 | void RegisterList::writeCVBitMain(char *s) volatile{ 448 | byte b[6]; // save space for checksum byte 449 | int cab; 450 | int cv; 451 | int bNum; 452 | int bValue; 453 | byte nB=0; 454 | 455 | if(sscanf(s,"%d %d %d %d",&cab,&cv,&bNum,&bValue)!=4) 456 | return; 457 | cv--; 458 | 459 | bValue=bValue%2; 460 | bNum=bNum%8; 461 | 462 | if(cab>127) 463 | b[nB++]=highByte(cab) | 0xC0; // convert train number into a two-byte address 464 | 465 | b[nB++]=lowByte(cab); 466 | b[nB++]=0xE8+(highByte(cv)&0x03); // any CV>1023 will become modulus(1024) due to bit-mask of 0x03 467 | b[nB++]=lowByte(cv); 468 | b[nB++]=0xF0+bValue*8+bNum; 469 | 470 | loadPacket(0,b,nB,4); 471 | 472 | } // RegisterList::writeCVBitMain() 473 | 474 | /////////////////////////////////////////////////////////////////////////////// 475 | 476 | void RegisterList::printPacket(int nReg, byte *b, int nBytes, int nRepeat) volatile { 477 | 478 | INTERFACE.print("<*"); 479 | INTERFACE.print(nReg); 480 | INTERFACE.print(":"); 481 | for(int i=0;i"); 488 | } // RegisterList::printPacket() 489 | 490 | /////////////////////////////////////////////////////////////////////////////// 491 | 492 | byte RegisterList::idlePacket[3]={0xFF,0x00,0}; // always leave extra byte for checksum computation 493 | byte RegisterList::resetPacket[3]={0x00,0x00,0}; 494 | 495 | byte RegisterList::bitMask[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01}; // masks used in interrupt routine to speed the query of a single bit in a Packet 496 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/LNetCmdStation.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | CurrentMonitor.cpp 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | #include "LNetCmdStation.h" 11 | #include "DCCpp_Uno.h" 12 | 13 | #define DEBUG 14 | 15 | /////////////////////////////////////////////////////////////////////////////// 16 | 17 | volatile RegisterList *LNetCmdStation::mRegs; 18 | volatile RegisterList *LNetCmdStation::pRegs; 19 | CurrentMonitor *LNetCmdStation::mMonitor; 20 | LiquidCrystal *mLcd; 21 | 22 | void LNetCmdStation::init(volatile RegisterList *_mRegs, volatile RegisterList *_pRegs, CurrentMonitor *_mMonitor, LiquidCrystal *_mLcd) 23 | { 24 | mRegs=_mRegs; 25 | pRegs=_pRegs; 26 | mMonitor=_mMonitor; 27 | mLcd=_mLcd; 28 | 29 | // DGS initialize slots to FREE 30 | int n; 31 | for (n=0;nsz.command; 83 | char s[20]; 84 | byte myByte; 85 | int myAddress; 86 | int cvnum=0; 87 | int cvvalue=0; 88 | 89 | #ifdef DEBUG 90 | Serial.print("RX: "); 91 | uint8_t msgLen = getLnMsgSize(LnPacket); 92 | for (uint8_t x = 0; x < msgLen; x++) 93 | { 94 | uint8_t val = LnPacket->data[x]; 95 | // Print a leading 0 if less than 16 to make 2 HEX digits 96 | if(val < 16) 97 | Serial.print('0'); 98 | 99 | Serial.print(val, HEX); 100 | Serial.print(' '); 101 | } 102 | Serial.println(" <"); 103 | #endif 104 | 105 | switch (opcode) 106 | { 107 | case OPC_GPON: // Global ON command 108 | #ifdef DEBUG 109 | Serial.println("# GLOBAL ON #"); 110 | #endif 111 | mLcd->setCursor(0,0); // set the LCD cursor position 112 | mLcd->print("Status: ON "); 113 | mMonitor->setGlobalPower(ON); 114 | break; 115 | 116 | case OPC_GPOFF: // Global OFF command 117 | #ifdef DEBUG 118 | Serial.println("# GLOBAL OFF #"); 119 | #endif 120 | mMonitor->setGlobalPower(OFF); 121 | mLcd->setCursor(0,0); // set the LCD cursor position 122 | mLcd->print("Status: OFF "); 123 | break; 124 | 125 | case OPC_IDLE: // Stop emergency 126 | #ifdef DEBUG 127 | Serial.println("# EMERGENCY STOP #"); 128 | #endif 129 | mMonitor->setGlobalPower(EMERGENCY); 130 | mLcd->setCursor(0,0); // set the LCD cursor position 131 | mLcd->print("!! EMERGENCY !!"); 132 | break; 133 | 134 | case OPC_LOCO_ADR: // Request of Loco 135 | #ifdef DEBUG 136 | Serial.println("# OPC_LOCO_ADR Request of Loco #"); 137 | #endif 138 | // Check if it is in slot already and also gets the first possible free slot 139 | // Slot 0 is not examined as it is used as BT2 slot (TODO not implemented) 140 | 141 | for (n=1;nla.adr_lo && locoNetSlots[n].adr2==LnPacket->la.adr_hi) 146 | break; 147 | } 148 | 149 | // Loco not found and no free slots 150 | if (n==MAX_MAIN_REGISTERS && freeslot==MAX_MAIN_REGISTERS) 151 | { 152 | #ifdef DEBUG 153 | Serial.println("# !LONGACK! No free slots for loco #"); 154 | #endif 155 | LocoNet.sendLongAck(0); 156 | break; 157 | } 158 | // Loco not found, add to the first free slot speed 0, direction front, F0 ON 159 | if (n==MAX_MAIN_REGISTERS) 160 | { 161 | n=freeslot; 162 | locoNetSlots[n].command=0xE7; 163 | locoNetSlots[n].mesg_size=0x0E; 164 | locoNetSlots[n].slot=n; 165 | locoNetSlots[n].stat=LOCO_IDLE | DEC_MODE_128; 166 | locoNetSlots[n].adr=LnPacket->la.adr_lo; 167 | locoNetSlots[n].spd=0; 168 | locoNetSlots[n].dirf=DIRF_F0; 169 | locoNetSlots[n].trk &= GTRK_POWER & GTRK_MLOK1; // POWER ON & Loconet 1.1 by default 170 | locoNetSlots[n].ss2=0; 171 | locoNetSlots[n].adr2=LnPacket->la.adr_hi; 172 | locoNetSlots[n].snd=0; 173 | locoNetSlots[n].id1=0; 174 | locoNetSlots[n].id2=0; 175 | } 176 | #ifdef DEBUG 177 | Serial.println("# SLOT SENT #"); 178 | #endif 179 | LocoNet.send ((lnMsg*)&locoNetSlots[n]); 180 | break; 181 | 182 | case OPC_MOVE_SLOTS: 183 | #ifdef DEBUG 184 | Serial.println("# OPC_MOVE_SLOTS #"); 185 | #endif 186 | // Check slot range (0 DISPATCH NOT SUPPORTED, DIFFERENT NOT SUPPORTED) 187 | if (LnPacket->sm.dest>=MAX_MAIN_REGISTERS || LnPacket->sm.src>=MAX_MAIN_REGISTERS || LnPacket->sm.dest!=LnPacket->sm.src || LnPacket->sm.dest<1 || LnPacket->sm.src<1) 188 | { 189 | LocoNet.sendLongAck(0); 190 | return; 191 | } 192 | 193 | locoNetSlots[LnPacket->sm.dest].stat|=LOCO_IN_USE; 194 | LocoNet.send ((lnMsg*)&locoNetSlots[LnPacket->sm.dest]); 195 | // 196 | myAddress=locoNetSlots[LnPacket->sm.dest].adr+(locoNetSlots[LnPacket->sm.dest].adr2<<7); 197 | sprintf(s,"%d %d %d %d",LnPacket->sm.dest,myAddress,locoNetSlots[LnPacket->sm.dest].spd,bitRead(locoNetSlots[LnPacket->sm.dest].dirf,5)); 198 | 199 | mRegs->setThrottle(s); 200 | // 201 | // To set functions F0-F4 on (=1) or off (=0): 202 | // BYTE1: 128 + F1*1 + F2*2 + F3*4 + F4*8 + F0*16 203 | // BYTE2: omitted 204 | myByte=128; 205 | bitWrite(myByte,4,bitRead(locoNetSlots[LnPacket->sm.dest].dirf,4)); //F0 206 | bitWrite(myByte,0,bitRead(locoNetSlots[LnPacket->sm.dest].dirf,0)); //F1 207 | bitWrite(myByte,1,bitRead(locoNetSlots[LnPacket->sm.dest].dirf,1)); //F2 208 | bitWrite(myByte,2,bitRead(locoNetSlots[LnPacket->sm.dest].dirf,2)); //F3 209 | bitWrite(myByte,3,bitRead(locoNetSlots[LnPacket->sm.dest].dirf,3)); //F4 210 | sprintf(s,"%d %d",myAddress,myByte); 211 | mRegs->setFunction(s); 212 | break; 213 | 214 | case OPC_SLOT_STAT1: 215 | #ifdef DEBUG 216 | Serial.println("# OPC_SLOT_STAT1 #"); 217 | #endif 218 | locoNetSlots[LnPacket->ss.slot].stat = LnPacket->ss.stat; 219 | // 220 | // char s[20]; 221 | // sprintf(s,"%d %d %d %d",LnPacket->ss.slot,locoNetSlots[LnPacket->ss.slot].adr,locoNetSlots[LnPacket->ss.slot].spd,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,5)); 222 | // mainRegs.setThrottle(s); 223 | break; 224 | 225 | case OPC_LOCO_SPD: 226 | #ifdef DEBUG 227 | Serial.println("# OPC_LOCO_SPD #"); 228 | #endif 229 | locoNetSlots[LnPacket->lsp.slot].spd = LnPacket->lsp.spd; 230 | // 231 | myAddress=locoNetSlots[LnPacket->lsp.slot].adr+(locoNetSlots[LnPacket->lsp.slot].adr2<<7); 232 | sprintf(s,"%d %d %d %d",LnPacket->lsp.slot,myAddress,locoNetSlots[LnPacket->lsp.slot].spd,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,5)); 233 | mRegs->setThrottle(s); 234 | break; 235 | 236 | case OPC_LOCO_DIRF: 237 | #ifdef DEBUG 238 | Serial.print("# OPC_LOCO_DIRF # Diretion and F0 - F4 # "); 239 | Serial.println(locoNetSlots[LnPacket->ldf.slot].dirf,BIN); 240 | #endif 241 | locoNetSlots[LnPacket->ldf.slot].dirf = LnPacket->ldf.dirf; 242 | // 243 | myAddress=locoNetSlots[LnPacket->lsp.slot].adr+(locoNetSlots[LnPacket->lsp.slot].adr2<<7); 244 | sprintf(s,"%d %d %d %d",LnPacket->ldf.slot,myAddress,locoNetSlots[LnPacket->ldf.slot].spd,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,5)); 245 | mRegs->setThrottle(s); 246 | // 247 | // To set functions F0-F4 on (=1) or off (=0): 248 | // BYTE1: 128 + F1*1 + F2*2 + F3*4 + F4*8 + F0*16 249 | // BYTE2: omitted 250 | myByte=128; 251 | bitWrite(myByte,0,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,0)); // F1 252 | bitWrite(myByte,1,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,1)); // F2 253 | bitWrite(myByte,2,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,2)); // F3 254 | bitWrite(myByte,3,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,3)); // F4 255 | bitWrite(myByte,4,bitRead(locoNetSlots[LnPacket->ldf.slot].dirf,4)); // F0 256 | sprintf(s,"%d %d",myAddress,myByte); 257 | mRegs->setFunction(s); 258 | break; 259 | 260 | case OPC_LOCO_SND: 261 | #ifdef DEBUG 262 | Serial.println("# OPC_LOCO_SND #"); 263 | #endif 264 | locoNetSlots[LnPacket->ls.slot].snd = LnPacket->ls.snd; 265 | 266 | //* To set functions F5-F8 on (=1) or off (=0): 267 | //* 268 | //* BYTE1: 176 + F5*1 + F6*2 + F7*4 + F8*8 269 | //* BYTE2: omitted 270 | myAddress=locoNetSlots[LnPacket->lsp.slot].adr+(locoNetSlots[LnPacket->lsp.slot].adr2<<7); 271 | myByte=176; 272 | bitWrite(myByte,0,bitRead(locoNetSlots[LnPacket->ls.slot].snd,0)); // F5 273 | bitWrite(myByte,1,bitRead(locoNetSlots[LnPacket->ls.slot].snd,1)); // F6 274 | bitWrite(myByte,2,bitRead(locoNetSlots[LnPacket->ls.slot].snd,2)); // F7 275 | bitWrite(myByte,3,bitRead(locoNetSlots[LnPacket->ls.slot].snd,3)); // F8 276 | sprintf(s,"%d %d",myAddress,myByte); 277 | mRegs->setFunction(s); 278 | 279 | break; 280 | 281 | case OPC_WR_SL_DATA: //Programming track 282 | /*------------------------------------------------------------------------ 283 | This OPC leads to immediate LACK codes: 284 | ,<7F>,<7F>, Function NOT implemented, no reply. 285 | ,<7F>,<0>, Programmer BUSY , task aborted, no reply. 286 | ,<7F>,<1>, Task accepted , reply at completion. 287 | ,<7F>,<0x40>, Task accepted blind NO reply at completion. 288 | 289 | typedef struct progtask_t { 290 | uint8_t command; 291 | uint8_t mesg_size; ummmmm, size of the message in bytes? 292 | uint8_t slot; slot number for this request - slot 124 is programmer 293 | uint8_t pcmd; programmer command 294 | uint8_t pstat; programmer status error flags in reply message 295 | uint8_t hopsa; Ops mode - 7 high address bits of loco to program 296 | uint8_t lopsa; Ops mode - 7 low address bits of loco to program 297 | uint8_t trk; track status. Note: bit 3 shows if prog track is busy 298 | uint8_t cvh; hi 3 bits of CV# and msb of data7 299 | uint8_t cvl; lo 7 bits of CV# 300 | uint8_t data7; 7 bits of data to program, msb is in cvh above 301 | uint8_t pad2; 302 | uint8_t pad3; 303 | uint8_t chksum; exclusive-or checksum for the message 304 | } progTaskMsg; 305 | 306 | #define PRG_SLOT 0x7c This slot communicates with the programming track 307 | 308 | values and macros to decode programming messages 309 | #define PCMD_RW 0x40 1 = write, 0 = read 310 | #define PCMD_BYTE_MODE 0x20 1 = byte operation, 0 = bit operation (if possible) 311 | #define PCMD_TY1 0x10 TY1 Programming type select bit 312 | #define PCMD_TY0 0x08 TY0 Programming type select bit 313 | #define PCMD_OPS_MODE 0x04 1 = Ops mode, 0 = Service Mode 314 | #define PCMD_RSVRD1 0x02 reserved 315 | #define PCMD_RSVRD0 0x01 reserved 316 | 317 | programming mode mask 318 | #define PCMD_MODE_MASK (PCMD_BYTE_MODE | PCMD_OPS_MODE | PCMD_TY1 | PCMD_TY0) 319 | 320 | programming modes 321 | ----------------- 322 | Paged mode byte R/W on Service Track 323 | #define PAGED_ON_SRVC_TRK (PCMD_BYTE_MODE) 324 | Direct mode byte R/W on Service Track 325 | #define DIR_BYTE_ON_SRVC_TRK (PCMD_BYTE_MODE | PCMD_TY0) 326 | Direct mode bit R/W on Service Track 327 | #define DIR_BIT_ON_SRVC_TRK (PCMD_TY0) 328 | Physical Register byte R/W on Service Track 329 | #define REG_BYTE_RW_ON_SRVC_TRK (PCMD_TY1) 330 | Service Track Reserved function 331 | #define SRVC_TRK_RESERVED (PCMD_TY1 | PCMD_TY0) 332 | Ops mode byte program - no feedback 333 | #define OPS_BYTE_NO_FEEDBACK (PCMD_BYTE_MODE | PCMD_OPS_MODE) 334 | Ops mode byte program - feedback 335 | #define OPS_BYTE_FEEDBACK (OPS_BYTE_NO_FEEDBACK | PCMD_TY0) 336 | Ops mode bit program - no feedback 337 | #define OPS_BIT_NO_FEEDBACK (PCMD_OPS_MODE) 338 | Ops mode bit program - feedback 339 | #define OPS_BIT_FEEDBACK (OPS_BIT_NO_FEEDBACK | PCMD_TY0) 340 | 341 | Programmer Status error flags 342 | #define PSTAT_USER_ABORTED 0x08 /* User aborted this command 343 | #define PSTAT_READ_FAIL 0x04 /* Failed to detect Read Compare Acknowledge from decoder 344 | #define PSTAT_WRITE_FAIL 0x02 /* No Write acknowledge from decoder 345 | #define PSTAT_NO_DECODER 0x01 /* Service mode programming track empty 346 | 347 | bit masks for CVH 348 | #define CVH_CV8_CV9 0x30 /* mask for CV# bits 8 and 9 349 | #define CVH_CV7 0x01 /* mask for CV# bit 7 350 | #define CVH_D7 0x02 /* MSbit for data value 351 | 352 | build data byte from programmer message 353 | #define PROG_DATA(ptr) (((ptr->cvh & CVH_D7) << 6) | (ptr->data7 & 0x7f)) 354 | 355 | build CV # from programmer message 356 | #define PROG_CV_NUM(ptr) (((((ptr->cvh & CVH_CV8_CV9) >> 3) | (ptr->cvh & CVH_CV7)) * 128) + (ptr->cvl & 0x7f)) 357 | ------------------------------------------------------------------------*/ 358 | 359 | // Check for programming slot 360 | if (LnPacket->pt.slot!=PRG_SLOT) 361 | break; 362 | 363 | // PCMD value of 00 aborts current SERVICE mode programming and echo RD 364 | if (LnPacket->pt.pcmd==0x00) 365 | break; 366 | 367 | // Bit operations not implemented 368 | if (((LnPacket->pt.pcmd&PCMD_BYTE_MODE)==0) || ((LnPacket->pt.pcmd&PCMD_RW)>0 && (LnPacket->pt.pcmd&PCMD_OPS_MODE)>0)) 369 | { 370 | LocoNet.send(OPC_LONG_ACK,0x7F,0x7F); 371 | break; 372 | } 373 | 374 | digitalWrite(PROG_RELAY1,HIGH); 375 | digitalWrite(PROG_RELAY2,HIGH); 376 | digitalWrite(PWOFF_LED_PIN, HIGH); 377 | 378 | cvnum=(((((LnPacket->pt.cvh & CVH_CV8_CV9) >> 3) | (LnPacket->pt.cvh & CVH_CV7)) * 128) + (LnPacket->pt.cvl & 0x7f)); 379 | cvnum++; 380 | cvvalue=(((LnPacket->pt.cvh & CVH_D7) << 6) | (LnPacket->pt.data7 & 0x7f)); 381 | 382 | // READ ON PROGRAMMING TRACK 383 | if ((LnPacket->pt.pcmd&PCMD_RW) == 0 && (LnPacket->pt.pcmd&PCMD_OPS_MODE)==0) 384 | { 385 | LocoNet.send(OPC_LONG_ACK,0x7F,1); 386 | #ifdef DEBUG 387 | Serial.print("Read on programming track CV "); Serial.println(cvnum); 388 | #endif 389 | /* 390 | * CV: the number of the Configuration Variable memory location in the decoder to read from (1-1024) 391 | * CALLBACKNUM: an arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs that call this function 392 | * CALLBACKSUB: a second arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs (e.g. DCC++ Interface) that call this function 393 | * 394 | * returns: readCV(s); 400 | // <0xEF>,<0E>,<7C>,,<0> ,,,,,,,<0>,<0>, 401 | // <0xE7>,<0E>,<7C>,,,,,,,,,<0>,<0>, 402 | LnPacket->pt.command=OPC_SL_RD_DATA; 403 | LnPacket->pt.pstat=0; 404 | LnPacket->pt.data7=cvvalue; 405 | LocoNet.send(LnPacket); 406 | 407 | mLcd->setCursor(0,0); // set the LCD cursor position 408 | mLcd->print("GET CV"); mLcd->print(cvnum); mLcd->print(" = "); mLcd->print(cvvalue); 409 | } 410 | //WRITE ON PROGRAMMING TRACK 411 | if ((LnPacket->pt.pcmd&PCMD_RW)>0 && (LnPacket->pt.pcmd&PCMD_OPS_MODE)==0) 412 | { 413 | LocoNet.send(OPC_LONG_ACK,0x7F,1); 414 | #ifdef DEBUG 415 | Serial.print("Write on programming track CV ");Serial.print(cvnum);Serial.print(" VALUE ");Serial.println(cvvalue); 416 | #endif 417 | /* 418 | * CV: the number of the Configuration Variable memory location in the decoder to write to (1-1024) 419 | * VALUE: the value to be written to the Configuration Variable memory location (0-255) 420 | * CALLBACKNUM: an arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs that call this function 421 | * CALLBACKSUB: a second arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs (e.g. DCC++ Interface) that call this function 422 | * 423 | * returns: writeCVByte(s); 428 | cvvalue=pRegs->readCV(s); 429 | LnPacket->pt.command=OPC_SL_RD_DATA; 430 | LnPacket->pt.pstat=0; 431 | LnPacket->pt.data7=cvvalue; 432 | LocoNet.send(LnPacket); 433 | mLcd->setCursor(0,0); // set the LCD cursor position 434 | mLcd->print("SET CV"); mLcd->print(cvnum); mLcd->print(" = "); mLcd->print(cvvalue); 435 | } 436 | 437 | digitalWrite(PROG_RELAY1,LOW); 438 | digitalWrite(PROG_RELAY2,LOW); 439 | digitalWrite(PWOFF_LED_PIN, LOW); 440 | 441 | break; 442 | 443 | default: 444 | // ignore the message... 445 | #ifdef DEBUG 446 | Serial.println("# !! IGNORE MESSAGE !! #"); 447 | #endif 448 | } 449 | 450 | } // LNetCmdStation::processIncomingLoconetCommand 451 | 452 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/SerialCommand.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | SerialCommand.cpp 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | 6 | Part of DCC++ BASE STATION for the Arduino 7 | 8 | **********************************************************************/ 9 | 10 | // DCC++ BASE STATION COMMUNICATES VIA THE SERIAL PORT USING SINGLE-CHARACTER TEXT COMMANDS 11 | // WITH OPTIONAL PARAMTERS, AND BRACKETED BY < AND > SYMBOLS. SPACES BETWEEN PARAMETERS 12 | // ARE REQUIRED. SPACES ANYWHERE ELSE ARE IGNORED. A SPACE BETWEEN THE SINGLE-CHARACTER 13 | // COMMAND AND THE FIRST PARAMETER IS ALSO NOT REQUIRED. 14 | 15 | // See SerialCommand::parse() below for defined text commands. 16 | 17 | #include "SerialCommand.h" 18 | #include "LNetCmdStation.h" 19 | #include "DCCpp_Uno.h" 20 | 21 | extern int __heap_start, *__brkval; 22 | 23 | /////////////////////////////////////////////////////////////////////////////// 24 | 25 | char SerialCommand::commandString[MAX_COMMAND_LENGTH+1]; 26 | volatile RegisterList *SerialCommand::mRegs; 27 | volatile RegisterList *SerialCommand::pRegs; 28 | CurrentMonitor *SerialCommand::mMonitor; 29 | LNetCmdStation *LNetCmdStation; 30 | 31 | /////////////////////////////////////////////////////////////////////////////// 32 | 33 | void SerialCommand::init(volatile RegisterList *_mRegs, volatile RegisterList *_pRegs, CurrentMonitor *_mMonitor){ 34 | mRegs=_mRegs; 35 | pRegs=_pRegs; 36 | mMonitor=_mMonitor; 37 | sprintf(commandString,""); 38 | } // SerialCommand:SerialCommand 39 | 40 | /////////////////////////////////////////////////////////////////////////////// 41 | 42 | void SerialCommand::process() 43 | { 44 | char c; 45 | 46 | while(INTERFACE.available()>0){ // while there is data on the serial line 47 | c=INTERFACE.read(); 48 | if(c=='<') // start of new command 49 | sprintf(commandString,""); 50 | else if(c=='>') // end of new command 51 | parse(commandString); 52 | else if(strlen(commandString)') 54 | } 55 | } // SerialCommand:process 56 | 57 | /////////////////////////////////////////////////////////////////////////////// 58 | 59 | void SerialCommand::parse(char *com){ 60 | 61 | switch(com[0]){ 62 | 63 | /***** SET ENGINE THROTTLES USING 128-STEP SPEED CONTROL ****/ 64 | 65 | case 't': // 66 | /* 67 | * sets the throttle for a given register/cab combination 68 | * 69 | * REGISTER: an internal register number, from 1 through MAX_MAIN_REGISTERS (inclusive), to store the DCC packet used to control this throttle setting 70 | * CAB: the short (1-127) or long (128-10293) address of the engine decoder 71 | * SPEED: throttle speed from 0-126, or -1 for emergency stop (resets SPEED to 0) 72 | * DIRECTION: 1=forward, 0=reverse. Setting direction when speed=0 or speed=-1 only effects directionality of cab lighting for a stopped train 73 | * 74 | * returns: 75 | * 76 | */ 77 | mRegs->setThrottle(com+1); 78 | break; 79 | 80 | /***** OPERATE ENGINE DECODER FUNCTIONS F0-F28 ****/ 81 | 82 | case 'f': // 83 | /* 84 | * turns on and off engine decoder functions F0-F28 (F0 is sometimes called FL) 85 | * NOTE: setting requests transmitted directly to mobile engine decoder --- current state of engine functions is not stored by this program 86 | * 87 | * CAB: the short (1-127) or long (128-10293) address of the engine decoder 88 | * 89 | * To set functions F0-F4 on (=1) or off (=0): 90 | * 91 | * BYTE1: 128 + F1*1 + F2*2 + F3*4 + F4*8 + F0*16 92 | * BYTE2: omitted 93 | * 94 | * To set functions F5-F8 on (=1) or off (=0): 95 | * 96 | * BYTE1: 176 + F5*1 + F6*2 + F7*4 + F8*8 97 | * BYTE2: omitted 98 | * 99 | * To set functions F9-F12 on (=1) or off (=0): 100 | * 101 | * BYTE1: 160 + F9*1 +F10*2 + F11*4 + F12*8 102 | * BYTE2: omitted 103 | * 104 | * To set functions F13-F20 on (=1) or off (=0): 105 | * 106 | * BYTE1: 222 107 | * BYTE2: F13*1 + F14*2 + F15*4 + F16*8 + F17*16 + F18*32 + F19*64 + F20*128 108 | * 109 | * To set functions F21-F28 on (=1) of off (=0): 110 | * 111 | * BYTE1: 223 112 | * BYTE2: F21*1 + F22*2 + F23*4 + F24*8 + F25*16 + F26*32 + F27*64 + F28*128 113 | * 114 | * returns: NONE 115 | * 116 | */ 117 | mRegs->setFunction(com+1); 118 | break; 119 | 120 | /***** OPERATE STATIONARY ACCESSORY DECODERS ****/ 121 | 122 | case 'a': // 123 | /* 124 | * turns an accessory (stationary) decoder on or off 125 | * 126 | * ADDRESS: the primary address of the decoder (0-511) 127 | * SUBADDRESS: the subaddress of the decoder (0-3) 128 | * ACTIVATE: 1=on (set), 0=off (clear) 129 | * 130 | * Note that many decoders and controllers combine the ADDRESS and SUBADDRESS into a single number, N, 131 | * from 1 through a max of 2044, where 132 | * 133 | * N = (ADDRESS - 1) * 4 + SUBADDRESS + 1, for all ADDRESS>0 134 | * 135 | * OR 136 | * 137 | * ADDRESS = INT((N - 1) / 4) + 1 138 | * SUBADDRESS = (N - 1) % 4 139 | * 140 | * returns: NONE 141 | */ 142 | mRegs->setAccessory(com+1); 143 | break; 144 | 145 | /***** CREATE/EDIT/REMOVE/SHOW & OPERATE A TURN-OUT ****/ 146 | 147 | case 'T': // 148 | /* 149 | * : sets turnout ID to either the "thrown" or "unthrown" position 150 | * 151 | * ID: the numeric ID (0-32767) of the turnout to control 152 | * THROW: 0 (unthrown) or 1 (thrown) 153 | * 154 | * returns: or if turnout ID does not exist 155 | * 156 | * *** SEE ACCESSORIES.CPP FOR COMPLETE INFO ON THE DIFFERENT VARIATIONS OF THE "T" COMMAND 157 | * USED TO CREATE/EDIT/REMOVE/SHOW TURNOUT DEFINITIONS 158 | */ 159 | /*Turnout::parse(com+1); TODO NOT IMPLEMENTED */ 160 | break; 161 | 162 | /***** CREATE/EDIT/REMOVE/SHOW & OPERATE AN OUTPUT PIN ****/ 163 | 164 | case 'Z': // 165 | /* 166 | * : sets output ID to either the "active" or "inactive" state 167 | * 168 | * ID: the numeric ID (0-32767) of the output to control 169 | * ACTIVATE: 0 (active) or 1 (inactive) 170 | * 171 | * returns: or if output ID does not exist 172 | * 173 | * *** SEE OUTPUTS.CPP FOR COMPLETE INFO ON THE DIFFERENT VARIATIONS OF THE "O" COMMAND 174 | * USED TO CREATE/EDIT/REMOVE/SHOW TURNOUT DEFINITIONS 175 | */ 176 | /*Output::parse(com+1); TODO NOT IMPLEMENTED */ 177 | break; 178 | 179 | /***** CREATE/EDIT/REMOVE/SHOW A SENSOR ****/ 180 | 181 | case 'S': 182 | /* 183 | * *** SEE SENSOR.CPP FOR COMPLETE INFO ON THE DIFFERENT VARIATIONS OF THE "S" COMMAND 184 | * USED TO CREATE/EDIT/REMOVE/SHOW SENSOR DEFINITIONS 185 | */ 186 | /* Sensor::parse(com+1); TODO NOT IMPLEMENTED */ 187 | break; 188 | 189 | /***** SHOW STATUS OF ALL SENSORS ****/ 190 | 191 | case 'Q': // 192 | /* 193 | * returns: the status of each sensor ID in the form (active) or (not active) 194 | */ 195 | /* Sensor::status(); TODO NOT IMPLEMENTED */ 196 | break; 197 | 198 | /***** WRITE CONFIGURATION VARIABLE BYTE TO ENGINE DECODER ON MAIN OPERATIONS TRACK ****/ 199 | 200 | case 'w': // 201 | /* 202 | * writes, without any verification, a Configuration Variable to the decoder of an engine on the main operations track 203 | * 204 | * CAB: the short (1-127) or long (128-10293) address of the engine decoder 205 | * CV: the number of the Configuration Variable memory location in the decoder to write to (1-1024) 206 | * VALUE: the value to be written to the Configuration Variable memory location (0-255) 207 | * 208 | * returns: NONE 209 | */ 210 | mRegs->writeCVByteMain(com+1); 211 | break; 212 | 213 | /***** WRITE CONFIGURATION VARIABLE BIT TO ENGINE DECODER ON MAIN OPERATIONS TRACK ****/ 214 | 215 | case 'b': // 216 | /* 217 | * writes, without any verification, a single bit within a Configuration Variable to the decoder of an engine on the main operations track 218 | * 219 | * CAB: the short (1-127) or long (128-10293) address of the engine decoder 220 | * CV: the number of the Configuration Variable memory location in the decoder to write to (1-1024) 221 | * BIT: the bit number of the Configurarion Variable regsiter to write (0-7) 222 | * VALUE: the value of the bit to be written (0-1) 223 | * 224 | * returns: NONE 225 | */ 226 | mRegs->writeCVBitMain(com+1); 227 | break; 228 | 229 | /***** WRITE CONFIGURATION VARIABLE BYTE TO ENGINE DECODER ON PROGRAMMING TRACK ****/ 230 | 231 | case 'W': // 232 | /* 233 | * writes, and then verifies, a Configuration Variable to the decoder of an engine on the programming track 234 | * 235 | * CV: the number of the Configuration Variable memory location in the decoder to write to (1-1024) 236 | * VALUE: the value to be written to the Configuration Variable memory location (0-255) 237 | * CALLBACKNUM: an arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs that call this function 238 | * CALLBACKSUB: a second arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs (e.g. DCC++ Interface) that call this function 239 | * 240 | * returns: writeCVByte(com+1); 244 | break; 245 | 246 | /***** WRITE CONFIGURATION VARIABLE BIT TO ENGINE DECODER ON PROGRAMMING TRACK ****/ 247 | 248 | case 'B': // 249 | /* 250 | * writes, and then verifies, a single bit within a Configuration Variable to the decoder of an engine on the programming track 251 | * 252 | * CV: the number of the Configuration Variable memory location in the decoder to write to (1-1024) 253 | * BIT: the bit number of the Configurarion Variable memory location to write (0-7) 254 | * VALUE: the value of the bit to be written (0-1) 255 | * CALLBACKNUM: an arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs that call this function 256 | * CALLBACKSUB: a second arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs (e.g. DCC++ Interface) that call this function 257 | * 258 | * returns: writeCVBit(com+1); 262 | break; 263 | 264 | /***** READ CONFIGURATION VARIABLE BYTE FROM ENGINE DECODER ON PROGRAMMING TRACK ****/ 265 | 266 | case 'R': // 267 | /* 268 | * reads a Configuration Variable from the decoder of an engine on the programming track 269 | * 270 | * CV: the number of the Configuration Variable memory location in the decoder to read from (1-1024) 271 | * CALLBACKNUM: an arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs that call this function 272 | * CALLBACKSUB: a second arbitrary integer (0-32767) that is ignored by the Base Station and is simply echoed back in the output - useful for external programs (e.g. DCC++ Interface) that call this function 273 | * 274 | * returns: readCV(com+1); 278 | break; 279 | 280 | /***** TURN ON POWER FROM MOTOR SHIELD TO TRACKS ****/ 281 | 282 | case '1': // <1> 283 | /* 284 | * enables power from the motor shield to the main operations and programming tracks 285 | * 286 | * returns: 287 | */ 288 | digitalWrite(SIGNAL_ENABLE_PIN_PROG,HIGH); 289 | digitalWrite(SIGNAL_ENABLE_PIN_MAIN,HIGH); 290 | INTERFACE.print(""); 291 | LNetCmdStation->sendOPC_GP(ON); 292 | break; 293 | 294 | /***** TURN OFF POWER FROM MOTOR SHIELD TO TRACKS ****/ 295 | 296 | case '0': // <0> 297 | /* 298 | * disables power from the motor shield to the main operations and programming tracks 299 | * 300 | * returns: 301 | */ 302 | digitalWrite(SIGNAL_ENABLE_PIN_PROG,LOW); 303 | digitalWrite(SIGNAL_ENABLE_PIN_MAIN,LOW); 304 | INTERFACE.print(""); 305 | LNetCmdStation->sendOPC_GP(OFF); 306 | break; 307 | 308 | /***** READ MAIN OPERATIONS TRACK CURRENT ****/ 309 | 310 | case 'c': // 311 | /* 312 | * reads current being drawn on main operations track 313 | * 314 | * returns: 315 | * where CURRENT = 0-1024, based on exponentially-smoothed weighting scheme 316 | */ 317 | INTERFACE.print("current)); 319 | INTERFACE.print(">"); 320 | break; 321 | 322 | /***** READ STATUS OF DCC++ BASE STATION ****/ 323 | 324 | case 's': // 325 | /* 326 | * returns status messages containing track power status, throttle status, turn-out status, and a version number 327 | * NOTE: this is very useful as a first command for an interface to send to this sketch in order to verify connectivity and update any GUI to reflect actual throttle and turn-out settings 328 | * 329 | * returns: series of status messages that can be read by an interface to determine status of DCC++ Base Station and important settings 330 | */ 331 | if(digitalRead(SIGNAL_ENABLE_PIN_PROG)==LOW) // could check either PROG or MAIN 332 | INTERFACE.print(""); 333 | else 334 | INTERFACE.print(""); 335 | 336 | for(int i=1;i<=MAX_MAIN_REGISTERS;i++){ 337 | if(mRegs->speedTable[i]==0) 338 | continue; 339 | INTERFACE.print("speedTable[i]>0){ 342 | INTERFACE.print(mRegs->speedTable[i]); 343 | INTERFACE.print(" 1>"); 344 | } else{ 345 | INTERFACE.print(-mRegs->speedTable[i]); 346 | INTERFACE.print(" 0>"); 347 | } 348 | } 349 | INTERFACE.print(""); 358 | 359 | INTERFACE.print(""); 361 | 362 | break; 363 | 364 | /***** STORE SETTINGS IN EEPROM ****/ 365 | 366 | case 'E': // 367 | /* 368 | * stores settings for turnouts and sensors EEPROM 369 | * 370 | * returns: 371 | */ 372 | 373 | /*EEStore::store(); TODO*/ 374 | break; 375 | 376 | /***** CLEAR SETTINGS IN EEPROM ****/ 377 | 378 | case 'e': // 379 | /* 380 | * clears settings for Turnouts in EEPROM 381 | * 382 | * returns: 383 | */ 384 | 385 | /*EEStore::clear(); TODO*/ 386 | INTERFACE.print(""); 387 | break; 388 | 389 | /***** PRINT CARRIAGE RETURN IN SERIAL MONITOR WINDOW ****/ 390 | 391 | case ' ': // < > 392 | /* 393 | * simply prints a carriage return - useful when interacting with Ardiuno through serial monitor window 394 | * 395 | * returns: a carriage return 396 | */ 397 | INTERFACE.println(""); 398 | break; 399 | 400 | /// 401 | /// THE FOLLOWING COMMANDS ARE NOT NEEDED TO NORMAL OPERATIONS AND ARE ONLY USED FOR TESTING AND DEBUGGING PURPOSES 402 | /// PLEASE SEE SPECIFIC WANRINGS IN EACH COMMAND BELOW 403 | /// 404 | 405 | /***** WRITE A DCC PACKET TO ONE OF THE REGISTERS DRIVING THE MAIN OPERATIONS TRACK ****/ 406 | 407 | case 'M': // 408 | /* 409 | * writes a DCC packet of two, three, four, or five hexidecimal bytes to a register driving the main operations track 410 | * FOR DEBUGGING AND TESTING PURPOSES ONLY. DO NOT USE UNLESS YOU KNOW HOW TO CONSTRUCT NMRA DCC PACKETS - YOU CAN INADVERTENTLY RE-PROGRAM YOUR ENGINE DECODER 411 | * 412 | * REGISTER: an internal register number, from 0 through MAX_MAIN_REGISTERS (inclusive), to write (if REGISTER=0) or write and store (if REGISTER>0) the packet 413 | * BYTE1: first hexidecimal byte in the packet 414 | * BYTE2: second hexidecimal byte in the packet 415 | * BYTE3: optional third hexidecimal byte in the packet 416 | * BYTE4: optional fourth hexidecimal byte in the packet 417 | * BYTE5: optional fifth hexidecimal byte in the packet 418 | * 419 | * returns: NONE 420 | */ 421 | mRegs->writeTextPacket(com+1); 422 | break; 423 | 424 | /***** WRITE A DCC PACKET TO ONE OF THE REGISTERS DRIVING THE PROGRAMMING TRACK ****/ 425 | 426 | case 'P': //

427 | /* 428 | * writes a DCC packet of two, three, four, or five hexidecimal bytes to a register driving the programming track 429 | * FOR DEBUGGING AND TESTING PURPOSES ONLY. DO NOT USE UNLESS YOU KNOW HOW TO CONSTRUCT NMRA DCC PACKETS - YOU CAN INADVERTENTLY RE-PROGRAM YOUR ENGINE DECODER 430 | * 431 | * REGISTER: an internal register number, from 0 through MAX_MAIN_REGISTERS (inclusive), to write (if REGISTER=0) or write and store (if REGISTER>0) the packet 432 | * BYTE1: first hexidecimal byte in the packet 433 | * BYTE2: second hexidecimal byte in the packet 434 | * BYTE3: optional third hexidecimal byte in the packet 435 | * BYTE4: optional fourth hexidecimal byte in the packet 436 | * BYTE5: optional fifth hexidecimal byte in the packet 437 | * 438 | * returns: NONE 439 | */ 440 | pRegs->writeTextPacket(com+1); 441 | break; 442 | 443 | /***** ATTEMPTS TO DETERMINE HOW MUCH FREE SRAM IS AVAILABLE IN ARDUINO ****/ 444 | 445 | case 'F': // 446 | /* 447 | * measure amount of free SRAM memory left on the Arduino based on trick found on the internet. 448 | * Useful when setting dynamic array sizes, considering the Uno only has 2048 bytes of dynamic SRAM. 449 | * Unfortunately not very reliable --- would be great to find a better method 450 | * 451 | * returns: 452 | * where MEM is the number of free bytes remaining in the Arduino's SRAM 453 | */ 454 | int v; 455 | INTERFACE.print(""); 458 | break; 459 | 460 | /***** LISTS BIT CONTENTS OF ALL INTERNAL DCC PACKET REGISTERS ****/ 461 | 462 | case 'L': // 463 | /* 464 | * lists the packet contents of the main operations track registers and the programming track registers 465 | * FOR DIAGNOSTIC AND TESTING USE ONLY 466 | */ 467 | INTERFACE.println(""); 468 | for(Register *p=mRegs->reg;p<=mRegs->maxLoadedReg;p++){ 469 | INTERFACE.print("M"); INTERFACE.print((int)(p-mRegs->reg)); INTERFACE.print(":\t"); 470 | INTERFACE.print((int)p); INTERFACE.print("\t"); 471 | INTERFACE.print((int)p->activePacket); INTERFACE.print("\t"); 472 | INTERFACE.print(p->activePacket->nBits); INTERFACE.print("\t"); 473 | for(int i=0;i<10;i++){ 474 | INTERFACE.print(p->activePacket->buf[i],HEX); INTERFACE.print("\t"); 475 | } 476 | INTERFACE.println(""); 477 | } 478 | for(Register *p=pRegs->reg;p<=pRegs->maxLoadedReg;p++){ 479 | INTERFACE.print("P"); INTERFACE.print((int)(p-pRegs->reg)); INTERFACE.print(":\t"); 480 | INTERFACE.print((int)p); INTERFACE.print("\t"); 481 | INTERFACE.print((int)p->activePacket); INTERFACE.print("\t"); 482 | INTERFACE.print(p->activePacket->nBits); INTERFACE.print("\t"); 483 | for(int i=0;i<10;i++){ 484 | INTERFACE.print(p->activePacket->buf[i],HEX); INTERFACE.print("\t"); 485 | } 486 | INTERFACE.println(""); 487 | } 488 | INTERFACE.println(""); 489 | break; 490 | 491 | } // switch 492 | }; // SerialCommand::parse 493 | 494 | /////////////////////////////////////////////////////////////////////////////// 495 | 496 | 497 | -------------------------------------------------------------------------------- /BaseStation-1.2.1/DCCpp_Uno/DCCpp_Uno.ino: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | 3 | DCC++ BASE STATION 4 | COPYRIGHT (c) 2013-2015 Gregg E. Berman 5 | Loconet implementation by Dani Guisado (c) 2016 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see http://www.gnu.org/licenses 19 | 20 | **********************************************************************/ 21 | /********************************************************************** 22 | 23 | DCC++ BASE STATION is a C++ program written for the Arduino Mega 24 | using the Arduino IDE 1.6.6. 25 | 26 | It allows a standard Arduino Mega with an Arduino Motor Shield (as well as others) 27 | to be used as a fully-functioning digital command and control (DCC) base station 28 | for controlling model train layouts that conform to current National Model 29 | Railroad Association (NMRA) DCC standards. Adding a Loconet Shield it can be 30 | integrated in a Loconet network receiving commands via this communication bus. 31 | It supports also the connection of a LCD KeyPad shield and a double relay board 32 | to change normal DCC current to programming current. Programming on main track 33 | has been intentionally disabled when communicating via Loconet. 34 | 35 | This version of DCC++ BASE STATION supports: 36 | 37 | * 2-byte and 4-byte locomotive addressing 38 | * Simultaneous control of multiple locomotives 39 | * 128-step speed throttling 40 | * Cab functions F0-F28 41 | * Activate/de-activate accessory functions using 512 addresses, each with 4 sub-addresses 42 | - includes optional functionality to monitor and store of the direction of any connected turnouts 43 | * Programming on the Programming Track 44 | - write configuration variable bytes 45 | - set/clear specific configuration variable bits 46 | - read configuration variable bytes 47 | 48 | If not using a Loconet shield, DCC++ BASE STATION is controlled with 49 | simple text commands received via the Arduino's serial interface. 50 | Users can type these commands directly into the Arduino IDE Serial Monitor, 51 | or can send such commands from another device or computer program. 52 | 53 | With the exception of a standard 15V power supply that can be purchased in 54 | any electronics store, no additional hardware is required. 55 | 56 | Neither DCC++ BASE STATION nor DCC++ CONTROLLER use any known proprietary or 57 | commercial hardware, software, interfaces, specifications, or methods related 58 | to the control of model trains using NMRA DCC standards. Both programs are wholly 59 | original, developed by the author, and are not derived from any known commercial, 60 | free, or open-source model railroad control packages by any other parties. 61 | 62 | However, DCC++ BASE STATION and DCC++ CONTROLLER do heavily rely on the IDEs and 63 | embedded libraries associated with Arduino and Processing. Tremendous thanks to those 64 | responsible for these terrific open-source initiatives that enable programs like 65 | DCC++ to be developed and distributed in the same fashion. 66 | 67 | REFERENCES: 68 | 69 | NMRA DCC Standards: http://www.nmra.org/index-nmra-standards-and-recommended-practices 70 | Arduino: http://www.arduino.cc/ 71 | Processing: http://processing.org/ 72 | GNU General Public License: http://opensource.org/licenses/GPL-3.0 73 | MRRWA Loconet libraries: http://mrrwa.org/ 74 | 75 | BRIEF NOTES ON THE THEORY AND OPERATION OF DCC++ BASE STATION: 76 | 77 | DCC++ BASE STATION for the Mega configures the OC3B interrupt pin associated with Timer 0, 78 | and the OC1B interupt pin associated with Timer 1, to generate separate 0-5V 79 | unipolar signals that each properly encode zero and one bits conforming with 80 | DCC timing standards. 81 | 82 | Series of DCC bit streams are bundled into Packets that each form the basis of 83 | a standard DCC instruction. Packets are stored in Packet Registers that contain 84 | methods for updating and queuing according to text commands sent by the user 85 | (or another program) over the serial interface. There is one set of registers that controls 86 | the main operations track and one that controls the programming track. 87 | 88 | For the main operations track, packets to store cab throttle settings are stored in 89 | registers numbered 1 through MAX_MAIN_REGISTERS (as defined in DCCpp_Uno.h). 90 | It is generally considered good practice to continuously send throttle control packets 91 | to every cab so that if an engine should momentarily lose electrical connectivity with the tracks, 92 | it will very quickly receive another throttle control signal as soon as connectivity is 93 | restored (such as when a train passes over rough portion of track or the frog of a turnout). 94 | 95 | DCC++ Base Station therefore sequentially loops through each main operations track packet regsiter 96 | that has been loaded with a throttle control setting for a given cab. For each register, it 97 | transmits the appropriate DCC packet bits to the track, then moves onto the next register 98 | without any pausing to ensure continuous bi-polar power is being provided to the tracks. 99 | Updates to the throttle setting stored in any given packet register are done in a double-buffered 100 | fashion and the sequencer is pointed to that register immediately after being changed so that updated DCC bits 101 | can be transmitted to the appropriate cab without delay or any interruption in the bi-polar power signal. 102 | The cabs identified in each stored throttle setting should be unique across registers. If two registers 103 | contain throttle setting for the same cab, the throttle in the engine will oscillate between the two, 104 | which is probably not a desirable outcome. 105 | 106 | For both the main operations track and the programming track there is also a special packet register with id=0 107 | that is used to store all other DCC packets that do not require continious transmittal to the tracks. 108 | This includes DCC packets to control decoder functions, set accessory decoders, and read and write Configuration Variables. 109 | It is common practice that transmittal of these one-time packets is usually repeated a few times to ensure 110 | proper receipt by the receiving decoder. DCC decoders are designed to listen for repeats of the same packet 111 | and provided there are no other packets received in between the repeats, the DCC decoder will not repeat the action itself. 112 | Some DCC decoders actually require receipt of sequential multiple identical one-time packets as a way of 113 | verifying proper transmittal before acting on the instructions contained in those packets 114 | 115 | An Arduino Motor Shield (or similar), powered by a standard 15V DC power supply and attached 116 | on top of the Arduino Mega, is used to transform the 0-5V DCC logic signals 117 | produced by the Uno's Timer interrupts into proper 0-15V bi-polar DCC signals. 118 | 119 | For the Mega, the OC1B output is produced directly on pin 12, so no jumper is needed to connect to the 120 | Motor Shield's DIRECTION A input. However, one small jumper wire is needed to connect the Mega's OC3B output (pin 2) 121 | to the Motor Shield's DIRECTION B input (pin 13). 122 | 123 | Other Motor Shields may require different sets of jumper or configurations (see Config.h and DCCpp_Uno.h for details). 124 | 125 | When configured as such, the CHANNEL A and CHANNEL B outputs of the Motor Shield may be 126 | connected directly to the tracks. This software assumes CHANNEL A is connected 127 | to the Main Operations Track, and CHANNEL B is connected to the Programming Track. 128 | 129 | DCC++ BASE STATION in split into multiple modules, each with its own header file: 130 | 131 | DCCpp_Uno: declares required global objects and contains initial Arduino setup() 132 | and Arduino loop() functions, as well as interrput code for OC0B and OC1B. 133 | Also includes declarations of optional array of Turn-Outs and optional array of Sensors 134 | 135 | SerialCommand: contains methods to read and interpret text commands from the serial line, 136 | process those instructions, and, if necessary call appropriate Packet RegisterList methods 137 | to update either the Main Track or Programming Track Packet Registers 138 | 139 | PacketRegister: contains methods to load, store, and update Packet Registers with DCC instructions 140 | 141 | CurrentMonitor: contains methods to separately monitor and report the current drawn from CHANNEL A and 142 | CHANNEL B of the Arduino Motor Shield's, and shut down power if a short-circuit overload 143 | is detected 144 | 145 | Accessories: contains methods to operate and store the status of any optionally-defined turnouts controlled 146 | by a DCC stationary accessory decoder. 147 | 148 | Sensor: contains methods to monitor and report on the status of optionally-defined infrared 149 | sensors embedded in the Main Track and connected to various pins on the Arudino Uno 150 | 151 | Outputs: contains methods to configure one or more Arduino pins as an output for your own custom use 152 | 153 | EEStore: contains methods to store, update, and load various DCC settings and status 154 | (e.g. the states of all defined turnouts) in the EEPROM for recall after power-up 155 | 156 | LNetCmdStation: contains all Loconet communication methods (programmed by Dani Guisado from ClubNCaldes) 157 | 158 | DCC++ BASE STATION is configured through the Config.h file that contains all user-definable parameters 159 | 160 | Predefined Pins for Arduino MEGA: 161 | 162 | Pins 0,1: Serial communication for debugging purposes 163 | Pin 30: Power ON push button 164 | Pin 31: Power OFF push button 165 | Pin 32: External emergency stop button 166 | Pin 33: Emergency led 167 | Pin 34: Power ON led 168 | Pin 35: Power OFF led 169 | Pin 36: Relay 1 to switch between normal and programming current 170 | Pin 37: Relay 2 to switch between normal and programming current 171 | 172 | Pins 40, 41, 42, 43, 44,45: Conection to LCD keypad shield 173 | 174 | Pin 47: Loconet TX 175 | Pin 48: Loconet RX 176 | 177 | **********************************************************************/ 178 | 179 | // BEGIN BY INCLUDING THE HEADER FILES FOR EACH MODULE 180 | 181 | #include 182 | #include "DCCpp_Uno.h" 183 | #include "PacketRegister.h" 184 | #include "CurrentMonitor.h" 185 | #include "SerialCommand.h" 186 | #include "Config.h" 187 | #include "LNetCmdStation.h" 188 | #include 189 | 190 | #define DEBUG 191 | 192 | LiquidCrystal lcd(44, 45, 40, 41, 42, 43); // select the pins used on the LCD panel 193 | // define some values used by the panel and buttons 194 | int lcd_key = 0; 195 | int adc_key_in = 0; 196 | #define btnRIGHT 0 197 | #define btnUP 1 198 | #define btnDOWN 2 199 | #define btnLEFT 3 200 | #define btnSELECT 4 201 | #define btnNONE 5 202 | 203 | // NEXT DECLARE GLOBAL OBJECTS TO PROCESS AND STORE DCC PACKETS AND MONITOR TRACK CURRENTS. 204 | // NOTE REGISTER LISTS MUST BE DECLARED WITH "VOLATILE" QUALIFIER TO ENSURE THEY ARE PROPERLY UPDATED BY INTERRUPT ROUTINES 205 | 206 | volatile RegisterList mainRegs(MAX_MAIN_REGISTERS); // create list of registers for MAX_MAIN_REGISTER Main Track Packets 207 | volatile RegisterList progRegs(2); // create a shorter list of only two registers for Program Track Packets 208 | 209 | CurrentMonitor mainMonitor(CURRENT_MONITOR_PIN_MAIN,(char*)""); // create monitor for current on Main Track 210 | CurrentMonitor progMonitor(CURRENT_MONITOR_PIN_PROG,(char*)""); // create monitor for current on Program Track 211 | 212 | LNetCmdStation locoNetCmdStation; // create class for command station loconet processing 213 | 214 | int timestoshow=0; 215 | 216 | /////////////////////////////////////////////////////////////////////////////// 217 | // MAIN ARDUINO LOOP 218 | /////////////////////////////////////////////////////////////////////////////// 219 | 220 | void loop(){ 221 | 222 | locoNetCmdStation.checkPacket(); // check for incomming Loconet packets 223 | 224 | SerialCommand::process(); // check for, and process, and new serial commands 225 | 226 | if(CurrentMonitor::checkTime()){ // if sufficient time has elapsed since last update, check current draw on Main and Program Tracks 227 | if (mainMonitor.check() || progMonitor.check()) 228 | { 229 | locoNetCmdStation.sendOPC_GP(EMERGENCY); 230 | lcd.setCursor(0,0); // set the LCD cursor position 231 | lcd.print(" EMERGENCY STOP "); 232 | } 233 | 234 | timestoshow++; 235 | if (timestoshow>2000) 236 | { 237 | lcd.setCursor(0,1); // set the LCD cursor position 238 | lcd.print("Main:"); lcd.print(map(mainMonitor.current,0, CURRENT_SAMPLE_MAX, 0, 100)); 239 | lcd.print("% Pr:"); lcd.print(map(progMonitor.current,0, CURRENT_SAMPLE_MAX, 0, 100)); lcd.print("% "); 240 | timestoshow=0; 241 | } 242 | 243 | } 244 | 245 | if (NO_BUTTONS == 0) 246 | { 247 | lcd_key = read_LCD_buttons(); // read the buttons 248 | 249 | if (digitalRead(EMERGENCY_STOP_PIN)==LOW) 250 | { 251 | mainMonitor.setGlobalPower(EMERGENCY); 252 | locoNetCmdStation.sendOPC_GP(EMERGENCY); 253 | lcd.setCursor(0,0); // set the LCD cursor position 254 | lcd.print(" EMERGENCY STOP "); 255 | } 256 | else if ((mainMonitor.globalPowerON!=ON) && (digitalRead(PWON_BUTTON_PIN)==LOW || lcd_key==btnLEFT)) 257 | { 258 | mainMonitor.setGlobalPower(ON); 259 | locoNetCmdStation.sendOPC_GP(ON); 260 | lcd.setCursor(0,0); // set the LCD cursor position 261 | lcd.print(" POWER ON "); 262 | } 263 | else if ((mainMonitor.globalPowerON!=OFF) && (digitalRead(PWOFF_BUTTON_PIN)==LOW || lcd_key==btnRIGHT)) 264 | { 265 | mainMonitor.setGlobalPower(OFF); 266 | locoNetCmdStation.sendOPC_GP(OFF); 267 | lcd.setCursor(0,0); // set the LCD cursor position 268 | lcd.print(" POWER OFF "); 269 | } 270 | } 271 | 272 | } // loop 273 | 274 | /////////////////////////////////////////////////////////////////////////////// 275 | // INITIAL SETUP 276 | /////////////////////////////////////////////////////////////////////////////// 277 | 278 | void setup(){ 279 | 280 | lcd.begin(16, 2); // start the library 281 | lcd.setCursor(0,0); // set the LCD cursor position 282 | lcd.print("DCC++ Loconet"); // print a simple message on the LCD 283 | lcd.setCursor(0,1); // set the LCD cursor position 284 | lcd.print("ClubNCaldes (c)"); // print a simple message on the LCD 285 | 286 | //Indication pins 287 | pinMode(PROG_RELAY1, OUTPUT); 288 | digitalWrite(PROG_RELAY1,HIGH); 289 | pinMode(PROG_RELAY2, OUTPUT); 290 | digitalWrite(PROG_RELAY2,HIGH); 291 | 292 | pinMode(PWON_LED_PIN, OUTPUT); 293 | digitalWrite(PWON_LED_PIN,HIGH); 294 | pinMode(PWOFF_LED_PIN, OUTPUT); 295 | digitalWrite(PWOFF_LED_PIN,HIGH); 296 | pinMode(EMERGENCY_LED_PIN, OUTPUT); 297 | digitalWrite(EMERGENCY_LED_PIN,HIGH); 298 | pinMode(PWON_BUTTON_PIN,INPUT_PULLUP); 299 | pinMode(PWOFF_BUTTON_PIN, INPUT_PULLUP); 300 | pinMode(EMERGENCY_STOP_PIN, INPUT_PULLUP); 301 | 302 | LocoNet.init(47); 303 | 304 | Serial.begin(115200); // configure serial interface 305 | Serial.flush(); 306 | 307 | Serial.print(""); 316 | 317 | SerialCommand::init(&mainRegs, &progRegs, &mainMonitor); // create structure to read and parse commands from serial line 318 | 319 | locoNetCmdStation.init(&mainRegs, &progRegs, &mainMonitor, &lcd); // create structure to read and parse commands from Loconet 320 | 321 | // CONFIGURE TIMER_1 TO OUTPUT 50% DUTY CYCLE DCC SIGNALS ON OC1B INTERRUPT PINS 322 | 323 | // Direction Pin for Motor Shield Channel A - MAIN OPERATIONS TRACK 324 | // Controlled by Arduino 16-bit TIMER 1 / OC1B Interrupt Pin 325 | // Values for 16-bit OCR1A and OCR1B registers calibrated for 1:1 prescale at 16 MHz clock frequency 326 | // Resulting waveforms are 200 microseconds for a ZERO bit and 116 microseconds for a ONE bit with exactly 50% duty cycle 327 | 328 | #define DCC_ZERO_BIT_TOTAL_DURATION_TIMER1 3199 329 | #define DCC_ZERO_BIT_PULSE_DURATION_TIMER1 1599 330 | 331 | #define DCC_ONE_BIT_TOTAL_DURATION_TIMER1 1855 332 | #define DCC_ONE_BIT_PULSE_DURATION_TIMER1 927 333 | 334 | pinMode(DIRECTION_MOTOR_CHANNEL_PIN_A,INPUT); // ensure this pin is not active! Direction will be controlled by DCC SIGNAL instead (below) 335 | digitalWrite(DIRECTION_MOTOR_CHANNEL_PIN_A,LOW); 336 | 337 | pinMode(DCC_SIGNAL_PIN_MAIN, OUTPUT); // THIS ARDUINO OUTPUT PIN MUST BE PHYSICALLY CONNECTED TO THE PIN FOR DIRECTION-A OF MOTOR CHANNEL-A 338 | 339 | bitSet(TCCR1A,WGM10); // set Timer 1 to FAST PWM, with TOP=OCR1A 340 | bitSet(TCCR1A,WGM11); 341 | bitSet(TCCR1B,WGM12); 342 | bitSet(TCCR1B,WGM13); 343 | 344 | bitSet(TCCR1A,COM1B1); // set Timer 1, OC1B (pin 10/UNO, pin 12/MEGA) to inverting toggle (actual direction is arbitrary) 345 | bitSet(TCCR1A,COM1B0); 346 | 347 | bitClear(TCCR1B,CS12); // set Timer 1 prescale=1 348 | bitClear(TCCR1B,CS11); 349 | bitSet(TCCR1B,CS10); 350 | 351 | OCR1A=DCC_ONE_BIT_TOTAL_DURATION_TIMER1; 352 | OCR1B=DCC_ONE_BIT_PULSE_DURATION_TIMER1; 353 | 354 | pinMode(SIGNAL_ENABLE_PIN_MAIN,OUTPUT); // master enable for motor channel A 355 | 356 | mainRegs.loadPacket(1,RegisterList::idlePacket,2,0); // load idle packet into register 1 357 | 358 | bitSet(TIMSK1,OCIE1B); // enable interrupt vector for Timer 1 Output Compare B Match (OCR1B) 359 | 360 | // Directon Pin for Motor Shield Channel B - PROGRAMMING TRACK 361 | // Controlled by Arduino 16-bit TIMER 3 / OC3B Interrupt Pin 362 | // Values for 16-bit OCR3A and OCR3B registers calibrated for 1:1 prescale at 16 MHz clock frequency 363 | // Resulting waveforms are 200 microseconds for a ZERO bit and 116 microseconds for a ONE bit with exactly 50% duty cycle 364 | 365 | #define DCC_ZERO_BIT_TOTAL_DURATION_TIMER3 3199 366 | #define DCC_ZERO_BIT_PULSE_DURATION_TIMER3 1599 367 | 368 | #define DCC_ONE_BIT_TOTAL_DURATION_TIMER3 1855 369 | #define DCC_ONE_BIT_PULSE_DURATION_TIMER3 927 370 | 371 | pinMode(DIRECTION_MOTOR_CHANNEL_PIN_B,INPUT); // ensure this pin is not active! Direction will be controlled by DCC SIGNAL instead (below) 372 | digitalWrite(DIRECTION_MOTOR_CHANNEL_PIN_B,LOW); 373 | 374 | pinMode(DCC_SIGNAL_PIN_PROG,OUTPUT); // THIS ARDUINO OUTPUT PIN MUST BE PHYSICALLY CONNECTED TO THE PIN FOR DIRECTION-B OF MOTOR CHANNEL-B 375 | 376 | bitSet(TCCR3A,WGM30); // set Timer 3 to FAST PWM, with TOP=OCR3A 377 | bitSet(TCCR3A,WGM31); 378 | bitSet(TCCR3B,WGM32); 379 | bitSet(TCCR3B,WGM33); 380 | 381 | bitSet(TCCR3A,COM3B1); // set Timer 3, OC3B (pin 2) to inverting toggle (actual direction is arbitrary) 382 | bitSet(TCCR3A,COM3B0); 383 | 384 | bitClear(TCCR3B,CS32); // set Timer 3 prescale=1 385 | bitClear(TCCR3B,CS31); 386 | bitSet(TCCR3B,CS30); 387 | 388 | OCR3A=DCC_ONE_BIT_TOTAL_DURATION_TIMER3; 389 | OCR3B=DCC_ONE_BIT_PULSE_DURATION_TIMER3; 390 | 391 | pinMode(SIGNAL_ENABLE_PIN_PROG,OUTPUT); // master enable for motor channel B 392 | 393 | progRegs.loadPacket(1,RegisterList::idlePacket,2,0); // load idle packet into register 1 394 | 395 | bitSet(TIMSK3,OCIE3B); // enable interrupt vector for Timer 3 Output Compare B Match (OCR3B) 396 | 397 | 398 | 399 | delay(2000); 400 | mainMonitor.setGlobalPower(OFF); 401 | 402 | } // setup 403 | 404 | /*************************************************************************/ 405 | /* KEYPAD FUNCTIONS */ 406 | /*************************************************************************/ 407 | int read_LCD_buttons() 408 | { 409 | adc_key_in = analogRead(15); // read the value from the sensor 410 | 411 | // my buttons when read are centered at these valies: 0, 144, 329, 504, 741 412 | // we add approx 50 to those values and check to see if we are close 413 | if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result 414 | // For V1.1 us this threshold 415 | /*if (adc_key_in < 50) return btnRIGHT; 416 | if (adc_key_in < 250) return btnUP; 417 | if (adc_key_in < 450) return btnDOWN; 418 | if (adc_key_in < 650) return btnLEFT; 419 | if (adc_key_in < 850) return btnSELECT; */ 420 | 421 | // For V1.0 comment the other threshold and use the one below: 422 | if (adc_key_in < 50) return btnRIGHT; 423 | if (adc_key_in < 195) return btnUP; 424 | if (adc_key_in < 380) return btnDOWN; 425 | if (adc_key_in < 555) return btnLEFT; 426 | if (adc_key_in < 790) return btnSELECT; 427 | return btnNONE; // when all others fail, return this... 428 | } 429 | 430 | /////////////////////////////////////////////////////////////////////////////// 431 | // DEFINE THE INTERRUPT LOGIC THAT GENERATES THE DCC SIGNAL 432 | /////////////////////////////////////////////////////////////////////////////// 433 | 434 | // The code below will be called every time an interrupt is triggered on OCNB, where N can be 0 or 1. 435 | // It is designed to read the current bit of the current register packet and 436 | // updates the OCNA and OCNB counters of Timer-N to values that will either produce 437 | // a long (200 microsecond) pulse, or a short (116 microsecond) pulse, which respectively represent 438 | // DCC ZERO and DCC ONE bits. 439 | 440 | // These are hardware-driven interrupts that will be called automatically when triggered regardless of what 441 | // DCC++ BASE STATION was otherwise processing. But once inside the interrupt, all other interrupt routines are temporarily disabled. 442 | // Since a short pulse only lasts for 116 microseconds, and there are TWO separate interrupts 443 | // (one for Main Track Registers and one for the Program Track Registers), the interrupt code must complete 444 | // in much less than 58 microseconds, otherwise there would be no time for the rest of the program to run. Worse, if the logic 445 | // of the interrupt code ever caused it to run longer than 58 microseconds, an interrupt trigger would be missed, the OCNA and OCNB 446 | // registers would not be updated, and the net effect would be a DCC signal that keeps sending the same DCC bit repeatedly until the 447 | // interrupt code completes and can be called again. 448 | 449 | // A significant portion of this entire program is designed to do as much of the heavy processing of creating a properly-formed 450 | // DCC bit stream upfront, so that the interrupt code below can be as simple and efficient as possible. 451 | 452 | // Note that we need to create two very similar copies of the code --- one for the Main Track OC1B interrupt and one for the 453 | // Programming Track OCOB interrupt. But rather than create a generic function that incurrs additional overhead, we create a macro 454 | // that can be invoked with proper paramters for each interrupt. This slightly increases the size of the code base by duplicating 455 | // some of the logic for each interrupt, but saves additional time. 456 | 457 | // As structured, the interrupt code below completes at an average of just under 6 microseconds with a worse-case of just under 11 microseconds 458 | // when a new register is loaded and the logic needs to switch active register packet pointers. 459 | 460 | // THE INTERRUPT CODE MACRO: R=REGISTER LIST (mainRegs or progRegs), and N=TIMER (0 or 1) 461 | 462 | #define DCC_SIGNAL(R,N)\ 463 | if(R.currentBit==R.currentReg->activePacket->nBits){ /* IF no more bits in this DCC Packet */\ 464 | R.currentBit=0; /* reset current bit pointer and determine which Register and Packet to process next--- */\ 465 | if(R.nRepeat>0 && R.currentReg==R.reg){ /* IF current Register is first Register AND should be repeated */\ 466 | R.nRepeat--; /* decrement repeat count; result is this same Packet will be repeated */\ 467 | } else if(R.nextReg!=NULL){ /* ELSE IF another Register has been updated */\ 468 | R.currentReg=R.nextReg; /* update currentReg to nextReg */\ 469 | R.nextReg=NULL; /* reset nextReg to NULL */\ 470 | R.tempPacket=R.currentReg->activePacket; /* flip active and update Packets */\ 471 | R.currentReg->activePacket=R.currentReg->updatePacket;\ 472 | R.currentReg->updatePacket=R.tempPacket;\ 473 | } else{ /* ELSE simply move to next Register */\ 474 | if(R.currentReg==R.maxLoadedReg) /* BUT IF this is last Register loaded */\ 475 | R.currentReg=R.reg; /* first reset currentReg to base Register, THEN */\ 476 | R.currentReg++; /* increment current Register (note this logic causes Register[0] to be skipped when simply cycling through all Registers) */\ 477 | } /* END-ELSE */\ 478 | } /* END-IF: currentReg, activePacket, and currentBit should now be properly set to point to next DCC bit */\ 479 | \ 480 | if(R.currentReg->activePacket->buf[R.currentBit/8] & R.bitMask[R.currentBit%8]){ /* IF bit is a ONE */\ 481 | OCR ## N ## A=DCC_ONE_BIT_TOTAL_DURATION_TIMER ## N; /* set OCRA for timer N to full cycle duration of DCC ONE bit */\ 482 | OCR ## N ## B=DCC_ONE_BIT_PULSE_DURATION_TIMER ## N; /* set OCRB for timer N to half cycle duration of DCC ONE but */\ 483 | } else{ /* ELSE it is a ZERO */\ 484 | OCR ## N ## A=DCC_ZERO_BIT_TOTAL_DURATION_TIMER ## N; /* set OCRA for timer N to full cycle duration of DCC ZERO bit */\ 485 | OCR ## N ## B=DCC_ZERO_BIT_PULSE_DURATION_TIMER ## N; /* set OCRB for timer N to half cycle duration of DCC ZERO bit */\ 486 | } /* END-ELSE */\ 487 | \ 488 | R.currentBit++; /* point to next bit in current Packet */ 489 | 490 | /////////////////////////////////////////////////////////////////////////////// 491 | 492 | // NOW USE THE ABOVE MACRO TO CREATE THE CODE FOR EACH INTERRUPT 493 | 494 | ISR(TIMER1_COMPB_vect){ // set interrupt service for OCR1B of TIMER-1 which flips direction bit of Motor Shield Channel A controlling Main Track 495 | DCC_SIGNAL(mainRegs,1) 496 | } 497 | 498 | ISR(TIMER3_COMPB_vect){ // set interrupt service for OCR3B of TIMER-3 which flips direction bit of Motor Shield Channel B controlling Prog Track 499 | DCC_SIGNAL(progRegs,3) 500 | } 501 | 502 | /////////////////////////////////////////////////////////////////////////////// 503 | 504 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------