/* Arduino sketch for DDS-60 controller Described at http://www.theladderline.com/dds-60 Author: Ross Keatinge Email: tetranz (at) gmail.com Amateur radio callsign: KB1KGA Date: March 6th 2010 Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License http://creativecommons.org/licenses/by-nc-sa/3.0/us/ Revision 1.1 - March 11th 2010 Now using our own LCD driver code instead of Arduino LiquidCrystal library Revision 1.2 - March 12th 2010 Now using our own code to write to DDS instead of ShiftOut Revision 1.3 - March 14th 2010 We now have QRSS mode! Revision 1.31 - May 3rd 2010 - Bug fix Reset frequency (i.e, key up) when switching away from QRSS. QRSS dot time changed to six seconds. Revision 1.4 - October 30th Transceiver mode for direct conversion transceiver. See http://www.theladderline.com/qrp-40-meter-cw-transceiver --------------------------------------------------------------------------------------------------------------------------------------- November 11,2015 - This sketch should compile & run ok in Arduino 1.0 & higher. Additional cumulative Mods by R.L. Snow, N9KR (partially described in reverse chronological order below)are attempts to customize the code for use in my homebrew CW station. The most recent hacks include adapting the code to use an Arduino Mega2560 board (many more I/O pins available) vs. the original ATMega328. All the credit goes to Ross Keatinge for this great original softwate. My very non-professional 'hacks' were created for custom use in my ham shack and as such will not be plug-and-play for your situation. Hopefully however, interested parties will glean some useful ideas to re-engineer for your own use along the Arduino trail... Good luck. 11/10/15 1.Chgd low side injection variable "_offset=" from -560 to 0 for this generic version of the software. 2.Note: the variable "_freq_adj=" is used to force the RX display to include a plus or minus 9,000,000 Hz I.F. offset. You could change all 7 occurances (find & replace) to your I.F. or change all 7 to zero (0) in which case the display would show actual frequency the DDS is putting out (essentially bench test generator mode). 3.QRSS & Silent Modes from Ross's original code have been disabled. Uncomment SetMode(QRSS_MODE); & comment out SetMode(MEMORY_MODE); under Case 1 at approx line 608 to re-enable QRSS mode. 4.CW Sidetone & TR switching (in Ross's original code) have been replaced with custom control code for transmitter relay switching using the same digital pins 11 & 13 (not shown in the schematic). You should be able to ignore these statements unless you need to use the associated pins for your project. 5.A Fritzing schematic of my Mega256 DDS VFO w/ AD9850, 16x2 Display,& Encoder can be found here: http://www.qsl.net/n9kr/MegaDDS/2560_dds_vfo_schem.pdf A copy of this Arduino sketch can be found here: http://www.qsl.net/n9kr/MegaDDS/MEGA-DDS1.ino 1/30/15 Several changes to match Pin Mapping differences going from Mega328 to Mega 2560 (new ddsvfo box) rls. 1. PortC LCD pins all changed A0 thru A5 chgd to Digital Pins 32 thru 37. The PortC code wasn't modified at all. 2. PortD manipulation was used for encoder reads and DDS module writes. DDS pins moved to PortF pins A4,A5,A6. Encoder Pins needed interrupts 0 & 1 on digital pins 2 & 3 but PortD pins are diff on Mega2560. Chgd to interrupts 2 & 3 on Digital PortD pins 20 & 21& modified Interupt(0) & Interrupt(1) code to have correct PIND bitwise code (chged from 8 & 4, to 2 & 1 to match pin positions of the new iterrupts). 1/16/15 modified memory_confirm_mode due to trouble with hold button 3 in original code not working. Left the save mem code the same (button_push_event plus event parameter event as 3 - button 3) runs save mem code. Chgd the Hold button to push button as well & chged the event parameter to 1 (button 1) & also chged msg displayed frm save? to "Sav 3, Del 1". Also minor chgs to ClearLowerRight function to match clearing of the longer message on line 1. Also LCD ClearArea function chged to (5,1,11). 1/15/15 fix mem display actual freq incl. +/- 0 or zero adj. code is in GetMemoryChannel function. rls 1/15/15 add Trans_mode and printfrequency code at top of main loop to correct lcd display at startup or mem change 1-15-15 rls 1/14/15 chg _offset to -560 if <125000000 (low side inj 20 & 40m)in Transceiver_mode &Normal mode sections. 1/13/15 remove qrss as mode choice. Startup & mem chg go straight to RX (transceive) mode. Chg backlite feed from 12 to 5vdc (dump 560 ohm R). 1/13/15 replaced encoder to fix jumpy freq. 1/13/15 Fixed startup display to include the 9 MHz offset without having to move the encoder. Fixed with if (_mode == TRANS_MODE) statement b4 the printfrequency.. 11/28/14 chgd 13000000 offset to 12500000 to allow 80 mtrs to work correctly with dds vfo in qrp station(5 places). 9-12-13 added 2nd xmit relay pin (13) and remmed out original pin 13 TR code below. Also built interface using 2n7000 ttl switch driving a 3906 12v keyed switch for the 2 sets of 3 relays inside xmit relay box (20 & 30 mtrs). 9-10-2013 attempt to add available pins 11 as relay pin to close the transmitter switch lines inside the xmit relay box 9-10-13 Reverse 2 button port lines (pinmode and enable pullup lines) per Ladder-line note in March 2013 update. Supposedly fixes some issues users were haveing with buttons not working correctly. 8-27-2013 chg the 11,000,000 mhz RX preselector kick in to 13,000,000 (7 locations in the code) to allow 21 mhz (15 Mtrs) to be low side injection like 20 mtrs (ie 12 mhz + 9 mhz = 21 mhz) vs. (30 mhz – 9 mhz = 21 mhz) - 2-19-12 RLS modified for ad9850 (writebytetoDDS to 0x08) & (const long clock_base=180000000 to =125000000), - And (const unsigned long clock_lsb_min=0x4EB0 to =0x286C) and (const unsigned long clock_lsb_max=0xDB50 to =0x8A14) - Added 9mhz or 0mhz offset choice in 'normal mode' & display same offset in 'trnscv' mode. - Also chd tx_timeout from 750 to 0. (not using tr delay function now because my rig has full QSK). - Chgd cw_freq from 800 to 750 to match my best offset 'tone' - Not currently using TR switching or audio sidetone functions altho they still run & output to arduino Pins D11 & D13 3/25/12 Built dual relay receiver LP/HP input filter switch board for HB receiver & this code below to auto switch pin D7 on high when frequency goes to one of the high band segments (above 11 Mhz). The TTL high voltage from D7 keys a 2n2222 on which pulls in the (2) 12 volt relay coils - switching in the High Pass filter. The Low pass filter is Normally Closed (3 - 11 Mhz). rls 4-15-12 attempt to add change offset on low side injection (11 mhz & lower) to -500 instead of the default 550 hz used for high side. use _offset variable and set it to eitherr -500 or 0 hz down in the setddsfrequency code rls 4-28-12 looks like -610 is the best freq offset for the lo side injection offset rls 4-28-12 As of this date _cw_freq is set to 470hz (lo bands)and _offset is set to -610hz (hi bands). This seems to be the transceive 'sweet spot'. */ #include // define our event codes const byte BUTTON_PUSH_EVENT = 1; // push a button const byte BUTTON_HOLD_EVENT = 2; // hold a button down for 5 seconds const byte ENCODER_TURN_EVENT = 3; // the encoder was turned // these are the event code and parameter generated by our I/O code byte _event = 0; int _eventParam; int _ms; // our main timing variable instead of using millis() directly. See comments in main loop. volatile byte _encoderCount = 0; // used by interupt code to communicate encoder rotation to main loop // encoder speed setting. 1 = maximum speed, 2 = half speed etc. This should only be set to a power of 2. byte _encoderSpeed = 1; const byte MEMORY_CHANNEL_MAX = 99; // lets have 99 memory channels // addresses used in EEPROM const int EE_FREQUENCY = 0; // last frequency const int EE_CALIBRATION = 4; // calibration offset const int EE_MODE = 6; // mode const int EE_MEMORY_CHANNELS = 1024 - (MEMORY_CHANNEL_MAX * 4); // put the memory channels at the top of the EEPROM // frequency range const long FREQ_MIN = 1000000; // 1 MHz const long FREQ_MAX = 60000000; // 60 MHz // the limits of the LSB of the clock value. // 180,000,000 is ABA9500 hex. We make use of the convenient fact that + or - 100 ppm (18 KHz) only changes the 2 least significant btes. // This means that we can do a simple and quick OR with CLOCK_BASE to get the final clock to calculate the delta to send to the DDS const unsigned long CLOCK_LSB_MIN = 0x286c; //chd for ad9850 rls const unsigned long CLOCK_LSB_MAX = 0x8a14; //chd for ad9850 rls // 64 bit 2 to the power of 32. // note that this is a 64 bit integer using the int64_t type. const int64_t TWO_E32 = 0x100000000LL; const long CLOCK_BASE = 125000000 & 0xFFFF0000; // Upper bits of 180 MHz. ORed with _clockLSB when programming DDS chd to 125 rls // modes const byte NORMAL_MODE = 0; const byte TRANS_MODE = 1; const byte MEMORY_MODE = 2; const byte MEMORY_CONFIRM_MODE = 3; const byte QRSS_MODE = 4; const byte CALIBRATE_MODE = 5; const byte SILENT_MODE = 6; byte _mode; // the current mode unsigned int _clockLSB; // calibration value. 0x9500 for clock = exactly 180 MHz unsigned int _saveClockLSB; // save _clockLSB in case we don't commit to calibration adjustment long _frequency; // current frequency in Hz long _frequencyStep = 100; // selected frequency step in Hz long _freq_adj = 0; // in Hz - Primarily for RX display to include plus or minus 9,000,000 Hz I.F. adjustment rls long _offset; //rls use this variable to manipulate TX offset for low side injection change(+550hz to -550hz) long _normalFrequencyStep; long _ritFrequencyStep = 10; // default step for RIT boolean _frequencyHasChanged = false; // set of the frequency has changed. Used for saving frequency to EEPROM boolean _modeHasChanged = false; byte _memoryChannel = 1; // selected memory channel long _memoryFrequency; // frequency of selected memory channel byte _buttonPorts[3]; // holds the port numbers of the push buttons. // define output pin 7 for rx ttl high output when freq is above 11 mhz. used for switching receiver input filter relay rls int _outpin =7; //const byte SIDETONE_PORT = 11; // audio sidetone out 9-10-13 remarked out related code below to free up pin 11 // for transmitter relay use along with pin 13 const int XMIT_RELAY1 = 11; //9-10-13 add transmit relay port rls const byte CW_PORT = 12; // CW keying in //const byte TR_PORT = 13; // Transmit / Receive switching out. 9-12-13 remarked out related code below const int XMIT_RELAY2 = 13; //9-12-13 add 2nd transmit relay port rls // CW audio frequency in Hz. // This controls both the DDS frequency shift between TX and RX and the sidetone audio. const int CW_FREQ = 700; // transmit timeout in ms. This is the key up time required before switching back to receive const int TX_TIMEOUT = 0; //chgd from 750 to 0 rls int _ritOffset = 0; boolean _ritOn = false; boolean _transmit = false; boolean _key_down = false; void setup() { pinMode(_outpin, OUTPUT); // Set Rx input relay pin as output. Used for custom hardware manipulation - rls LCDInitialize(); // initialize the LCD for 4 bit data mode // Set push button port numbers. The array index starts at zero but I find it easier to think of the buttons as 1, 2 and 3. // We use the Arduino digital port functions for the (slow) buttons so it's easy to add more buttons to the 3 spare ports // but, to get good performance, we write directly to the port registers for the DDS, LCD and encoder. _buttonPorts[0] = 8; // button 1 _buttonPorts[1] = 9; // button 2 _buttonPorts[2] = 10; // button 3 // initialize the button ports for (int i = 0; i < sizeof(_buttonPorts); i++) { pinMode(_buttonPorts[i], INPUT); // set port as vinput digitalWrite(_buttonPorts[i], HIGH); // enable pull-up resistor } SetTxRx(false); //pinMode(TR_PORT, OUTPUT); // these are outputs //pinMode(SIDETONE_PORT, OUTPUT); pinMode (XMIT_RELAY1, OUTPUT); //added 9-10-13 to control custom hardware manipulation - rls pinMode (XMIT_RELAY2, OUTPUT); //added 9-12-13 to control custom hardware manipulation - rls // CW port is an input digitalWrite(CW_PORT, HIGH); // turn on the pull-up resistor for the open collector interface on the transeiver. pinMode(CW_PORT, INPUT); // setup ports with |= and &= to avoid disturbing serial / USB ports 0 and 1 DDRD &= B11110011; // encoder ports as inputs DDRF |= B01110000; // set DDS ports as outputs //1-30-15 chg to PortF for mega2560 pins 4,5,6 (analog) vs old 4,5,6 digital pins for mega328 rls PORTD |= B00001100; // set encoder inputs to use pull-up resistors PORTF &= B10001111; // set DDS ports low //chgd from D to F ports 1-30-15 rls _clockLSB = ReadIntFromEEPROM(EE_CALIBRATION); // read calibration value from EEPROM // if it is outside + or - 9999 Hz then set it from 0 Hz, i.e., clock assumed to be exactly 180 MHz if (_clockLSB < CLOCK_LSB_MIN || _clockLSB > CLOCK_LSB_MAX) { _clockLSB = 0x9500; SaveToEEPROM(_clockLSB, EE_CALIBRATION); } WriteToDDS(0); // write 0 to the DDS. This might not be necessary but it keeps it off until we set it to a known frequency // enable interupts and attach our interupt routines. Set to trigger on every transition of the inputs attachInterrupt(2, Interrupt0, CHANGE); //1-30-15 chd from 0 and 1 to interupts 3 and 2 to match PortD pin changes on Mega2560 to pins 20 & 21 rls attachInterrupt(3, Interrupt1, CHANGE); //same here delay(250); // delay 1/4 second. This seems to help ensure a clean power-up ReadEncoder(); // throw away any initial interupts on power up _frequency = ReadLongFromEEPROM(EE_FREQUENCY); // get freqency from EEPROM // set it to some favorite frequency if it is out of range. This should really only happen on the first power-up if (_frequency < FREQ_MIN || _frequency > FREQ_MAX) { _frequency = 3560000; } SetDDSFrequency(); // set the DDS to the selected frequency _event = 0; // no events are happening yet _mode = EEPROM.read(EE_MODE); // read the last mode setting from EEPROM // saving the mode is mostly for the benefit of QRSS mode so we restart after a power failure // there doesn't seem much sense to start in CALIBRATE or MEMORY mode // so we start in TRANS, QRSS or NORMAL if (_mode == TRANS_MODE || _mode == QRSS_MODE) { SetMode(_mode, true); } else { SetMode(NORMAL_MODE, true); } } // ---------------------------------------------------- // Main loop // ---------------------------------------------------- */ void loop() { //-------------------------------------------------------------------------------------------------------------------------------- // added to get right lcd display at startup or mem change 1-13-15 rls if (_mode == TRANS_MODE) { PrintFrequency(_frequency + _freq_adj); } //---------------------------------------------------------------------------------------------------------------------------------- //Used to set the 9 MHz IF offset depending on whether Hi or Lo side injection is used. My homebrew cw station //with its 9 MHz IF uses Hi side injection for bands below 20 meters & Low side on bands above. if (_frequency <12500000) //rls { _freq_adj=9000000; //rls } if (_frequency >12500000) //rls { _freq_adj=-9000000; } //Some custom code for xmtr relay switching - rls //---------------------------------------------------------------------------------------------------------- //9-10-13 Setup pin 11 for xmit relay switching 20 meters (5000000 offset)& 15 meters (12000000 offset) rls if (_frequency >4980000 && _frequency <5300000 || _frequency >11980000 && _frequency <12500000) //rls { digitalWrite (XMIT_RELAY1, HIGH); } else //rls { digitalWrite (XMIT_RELAY1, LOW); } //9-12-13 add 2nd xmit_relay for 30 meters rls if (_frequency >18900000 && _frequency <19300000) //rls { digitalWrite (XMIT_RELAY2, HIGH); } else //rls { digitalWrite (XMIT_RELAY2, LOW); } //------------------------------------------------------------------------------------------------------------------ // We need to keep track of elapsed time for the various delays. millis() returns a 32 bit long. // If we only use the lower 16 bits then it will cycle around (overflow) every 65 seconds or so. That's plenty for us. // Since _ms is an int, our other time variables only need to be ints rather than longs // With the usual 2s complement arithmetic, "elapsed" calculations work fine without us needing to do anything special for overflow. _ms = millis() & 0xFFFF; ReadButtons(); // read the buttons if (!_event) // read the encoder if no button was pushed { ReadEncoder(); } if (_event && _mode != QRSS_MODE) // was there an event? { switch(_mode) // yes, so lets direct it to the appropriate mode routine { case NORMAL_MODE: NormalMode(); break; case TRANS_MODE: TransceiverMode(); break; case MEMORY_MODE: MemoryMode(); break; case MEMORY_CONFIRM_MODE: MemoryConfirmMode(); break; case CALIBRATE_MODE: CalibrateMode(); break; case SILENT_MODE: SilentMode(); break; } _event = 0; // The event has been processed } if (_mode == QRSS_MODE) { QRSSMode(false); } // Save the frequency and mode in EEPROM if these have changed. // Because of the save delay to protect the EEPROM from excessive writes, this is called every time whether or not an event happened. SaveStateToEEPROM(); if (_mode == TRANS_MODE) { DoCW(); // do the CW logic } } void DoCW() { static int lastKeydownMS; boolean was_key_down = _key_down; // remember the key state _key_down = !digitalRead(CW_PORT); // read the new key state if (_key_down) { if (!_transmit) // if key is down and we are not on transmit then go to transmit { SetTxRx(true); } // if (!was_key_down) // if key is down but was up before (i.e, it's just been pressed) then start sidetone // { // tone(SIDETONE_PORT, CW_FREQ); //} lastKeydownMS = _ms; // remember the last time the key was down } if (_transmit) { // if we're on transmit but the key has been up for the timeout period then go to receive. int elapsed = _ms - lastKeydownMS; if (elapsed > TX_TIMEOUT) { SetTxRx(false); } } } // // NORMAL mode. This is the normal "turn the dial and the frequency changes" mode // void NormalMode() { switch(_event) { case ENCODER_TURN_EVENT: // encoder was turned _frequency += ((long) _eventParam) * _frequencyStep; // adjust the frequency by the amount the encoder moved _frequency = RestrictFrequency(_frequency); // restrict the frequency to the allowable range SetDDSFrequency(); // set the DDS to the new frequency PrintFrequency(_frequency + _freq_adj); // print the new frequency- added + freq_adj rls _frequencyHasChanged = true; // remember that te frequency has changed so we can save it to EEPROM later if (_frequency <12500000) //rls defines cutoff freq for kicking in the RX filter relays { digitalWrite(_outpin, HIGH); //rls } else //rls { digitalWrite(_outpin, LOW); } //Hi or low side injection - freq readout adjustments if (_frequency <12500000) { _freq_adj=9000000; //rls } if (_frequency >12500000) //rls { _freq_adj=-9000000; } //--------------------------------------------------------------------------------------------------------------------------- //experimenting here with tx offsets for low side injection in my homebrew setup //4-15-12 added change offset on low side injection (11 mhz & lower) to -550 instead of the default 550 hz used for high side rls // if (_frequency <12500000) //rls //{ // _offset= -560; //added for high bands lo side injection. //} //else //{ // _offset=0; //} //------------------------------------------------------------------------------------------------------------------------------- break; case BUTTON_PUSH_EVENT: // a button was pressed switch(_eventParam) { case 1: SetMode(TRANS_MODE); // move to QRSS mode break; case 2: IncrementFreqAdj(); //chg freq offset PrintFrequencyOffset(); //Print offset //SetMode(SILENT_MODE); // turn the output off break; case 3: IncrementFrequencyStep(); // change the frequency step PrintFrequencyStep(); // print the new frequency step break; } break; } } void TransceiverMode() { if (_frequency <12500000) //rls defines cutoff freq for kicking in the RX filter relays { digitalWrite(_outpin, HIGH); //rls } else //rls { digitalWrite(_outpin, LOW); } //----------------------------------------------------------------------------------------------------------------------- //1-14-15 add change offset on low side injection (11 mhz & lower) to -560 here rls if (_frequency <12500000) { _offset= 0; //chgd from -560 for this generic sw version 11-8-15 rls } else { _offset=0; } //----------------------------------------------------------------------------------------------------------------- switch(_event) { case ENCODER_TURN_EVENT: // encoder was turned if (!_transmit) // ignored on transmit { if (_ritOn) { // RIT is on so move and print RIT offset _ritOffset += _eventParam * _frequencyStep; // restrict RIT to + or - 9.999 KHz if (_ritOffset > 9999) { _ritOffset = 9999; } else if (_ritOffset < -9999) { _ritOffset = -9999; } PrintOffset(_ritOffset); } else { _frequency += ((long) _eventParam) * _frequencyStep; // adjust the frequency by the amount the encoder moved _frequency = RestrictFrequency(_frequency); // restrict the frequency to the allowable range PrintFrequency(_frequency + _freq_adj); // ** print the new frequency ** added _freq_adj ** rls _frequencyHasChanged = true; // remember that the frequency has changed so we can save it to EEPROM later } SetDDSFrequency(); } break; case BUTTON_PUSH_EVENT: // a button was pressed switch(_eventParam) { //chg case 1 from qrss_mode to mem_mode to skip the qrss choice from the mode button when in transceive mode rls 1-11-15 ************ case 1: //SetMode(QRSS_MODE); // move to QRSS mode SetMode(MEMORY_MODE); break; case 2: SetRit(!_ritOn); // toggle RIT SetDDSFrequency(); break; case 3: IncrementFrequencyStep(); // change the frequency step PrintFrequencyStep(); // print the new frequency step break; } break; } } void SetRit(boolean onOff) { _ritOffset = 0; if (onOff) // setting RIT on { _normalFrequencyStep = _frequencyStep; // save freq step for normal tuning _frequencyStep = _ritFrequencyStep; // restore RIT frequency step PrintOffset(_ritOffset); // print frequency step } else { if (_mode == TRANS_MODE && _ritOn) // logic so we can call this even if RIT was already off { _ritFrequencyStep = _frequencyStep; } _frequencyStep = _normalFrequencyStep; ClearOffsetArea(); } PrintFrequencyStep(); _ritOn = onOff; } void SetTxRx(boolean state) { // toggle the transmit / receive state _transmit = state; //digitalWrite(TR_PORT, state); remmed out 9-12-13 if (_transmit) { LCDPrint("TX", 14, 0); } else { LCDPrint("RX", 14, 0); } SetDDSFrequency(); } void MemoryMode() { switch(_event) { case ENCODER_TURN_EVENT: // the encoder was turned _memoryChannel += _eventParam; // move the memory channel up or down if (_memoryChannel < 1) // cycle around if we go outside the range { _memoryChannel = MEMORY_CHANNEL_MAX; } else if (_memoryChannel > MEMORY_CHANNEL_MAX) { _memoryChannel = 1; } GetMemoryChannel(); // get the frequency of the new channel and display break; case BUTTON_PUSH_EVENT: // a button was pressed switch(_eventParam) { case 1: SetMode(CALIBRATE_MODE); // move to calibrate mode break; case 2: // if the selected channel is not "empty" then set the DDS to the new frequency and return to NORMAL mode if (_memoryFrequency) { _frequency = _memoryFrequency; SetDDSFrequency(); _frequencyHasChanged = true; } //SetMode(NORMAL_MODE); SetMode (TRANS_MODE); //Chg the result of memory select push to go to transcieve mode vs. going to normal mode rls 1-10-15 break; case 3: SetMode(MEMORY_CONFIRM_MODE); // we have chosen to save into this channel so move to confirm mode break; } } } void MemoryConfirmMode() { // the display is saving "Save ?" and waiting for a button push //1-16-15 chg mem save & mem delete methods here. Both use button_push_event with eventParam==3 (pushbutton3) for saving the freq // to memory and eventParam==1 (pushbutton1) for running the memory delete code below. if (_event == BUTTON_PUSH_EVENT && _eventParam == 3) { // button 3 pressed so save to that memory channel SaveToEEPROM(_frequency, EE_MEMORY_CHANNELS + ((_memoryChannel - 1) * 4)); SetMode(NORMAL_MODE); } if (_event == BUTTON_PUSH_EVENT && _eventParam == 1) { // button 1 pressed so erase that memory channel _memoryFrequency = 0; SaveToEEPROM(_memoryFrequency, EE_MEMORY_CHANNELS + ((_memoryChannel - 1) * 4)); ClearLowerRight(); PrintFrequency(_memoryFrequency); SetMode(MEMORY_MODE); } else { // return to normal mode without changing memory channel ClearLowerRight(); SetMode(MEMORY_MODE); } } void CalibrateMode() { switch(_event) { case ENCODER_TURN_EVENT: // the encoder was turned _clockLSB += ((long) _eventParam) * _frequencyStep; // move the _clockLSB calibration value up or down RestrictClock(); // restrict to + or - 9999 PrintClock(); // print the new calibration value SetDDSFrequency(); // set the DDS frequency using the new calibration value break; case BUTTON_PUSH_EVENT: switch(_eventParam) { case 1: // button 1 pressed. Return to normal mode without saving calibration value _clockLSB = _saveClockLSB; SetDDSFrequency(); SetMode(NORMAL_MODE); break; case 2: // button 2 pressed. Save new calibration value SaveToEEPROM(_clockLSB, EE_CALIBRATION); SetMode(NORMAL_MODE); break; case 3: // button 3 pressed. Change increment. IncrementFrequencyStep(); PrintFrequencyStep(); break; } } } void SilentMode() { // toggle between NORMAL and SILIENT modes with button 2 if (_event == BUTTON_PUSH_EVENT && _eventParam == 2) { SetDDSFrequency(); SetMode(NORMAL_MODE); } } void SetMode(byte mode) { SetMode(mode, false); } // setup for new mode void SetMode(byte mode, boolean init) { if (_ritOn) // start new mode with RIT off { SetRit(false); } boolean setFreq = false; boolean printStep = false; _mode = mode; switch(mode) { case NORMAL_MODE: LCDClear(); _encoderSpeed = 1; ReadEncoder(); // throw away any extra encoder movement setFreq = true; printStep = true; break; case TRANS_MODE: LCDClear(); ReadEncoder(); // throw away any extra encoder movement SetTxRx(false); _ritOn = false; _ritOffset = 0; if (!init) { _frequency -= CW_FREQ; // this avoids the DDS moving frequency } setFreq = true; printStep = true; break; case QRSS_MODE: if (!init) { _frequency += CW_FREQ; // this avoids the DDS moving frequency } PrintFrequency(_frequency); ClearLowerRight(); PrintMode("QRSS "); QRSSMode(true); printStep = true; break; case MEMORY_MODE: ClearLowerRight(); //added 1-16-15 w/ mem save/erase changes (using button 3 or 1 single push) rls SetDDSFrequency(); // set frequency in case we were shifted for QRSS key down _encoderSpeed = 2; PrintMode(" Mem "); ClearLowerRight(); GetMemoryChannel(); break; case MEMORY_CONFIRM_MODE: LCDPrint(" Sav 3,Del 1", 4, 1); //chged 1-16-15 rls //LCDPrint(" Save ?", 9, 1); break; case CALIBRATE_MODE: _saveClockLSB = _clockLSB; _encoderSpeed = 1; PrintMode("Calib"); PrintClock(); setFreq = true; printStep = true; break; case SILENT_MODE: WriteToDDS(0); PrintMode("Quiet"); break; } if (setFreq) { PrintFrequency(_frequency); SetDDSFrequency(); } if (printStep) { PrintFrequencyStep(); } _modeHasChanged = true; } // retrieve and print the memory channel in _memoryChannel void GetMemoryChannel() { char str[5]; sprintf(str, "M %2i", _memoryChannel); // format as M nn where nn is memory channel LCDPrint(str, 0, 1); _memoryFrequency = ReadLongFromEEPROM(EE_MEMORY_CHANNELS + ((_memoryChannel - 1) * 4)); // restrict frequency if out of range if (_memoryFrequency < FREQ_MIN || _memoryFrequency > FREQ_MAX) { _memoryFrequency = 0; } //-------------------------------------------------------------------------------------------------- //1-15-15 fix mem display actual freq incl. +/- 0 or zero adj rls if (_memoryFrequency <12500000) //rls { _freq_adj=9000000; //rls } if (_memoryFrequency >12500000) //rls { _freq_adj=-9000000; //rls } if (_memoryFrequency == 0) //rls { _freq_adj=0; } PrintFrequency(_memoryFrequency + _freq_adj); //add check_freq_adj 1-15-15 rls //---------------------------------------------------------------------------------------------------- } // save current frequency to EEPROM void SaveStateToEEPROM() { static int lastSaveMS; // remember when we last did this. Note: a static variables retains its value on each call of this routine int elapsed = _ms - lastSaveMS; // we only do this every 5 seconds if (elapsed >= 5000) { // only save if the frequency has actually changed if (_frequencyHasChanged) { SaveToEEPROM(_frequency, EE_FREQUENCY); _frequencyHasChanged = false; } if (_modeHasChanged) { if (EEPROM.read(EE_MODE) != _mode) { EEPROM.write(EE_MODE, _mode); } _modeHasChanged = false; } lastSaveMS = _ms; } } // cycle the frequency step around 100 KHz, 10 KHz, 1 KHz, 100 Hz, 10 Hz, 1 Hz void IncrementFrequencyStep() { if (_frequencyStep == 1) { _frequencyStep = 100000; } else { _frequencyStep = _frequencyStep / 10; } } //Cycle the IF offset between 0 Hz and -9,000,000 Hz rls void IncrementFreqAdj() { if (_freq_adj != 0) { _freq_adj=0; } else { _freq_adj= _freq_adj -(9000000); } } // -------------------------------------------------------- // Read buttons // -------------------------------------------------------- void ReadButtons() { // define some sub modes const byte WAIT_FOR_DOWN = 0; // wait for a button press const byte WAIT_FOR_UP_OR_TIME = 1; // wait for buttion to be released or for it to be pressed long enough to be considered "held". const byte WAIT_FOR_ALL_UP = 2; // waiting for all buttons released static int lastReadMS = 0; // remember when we last did this static int downTimeMS = 0; // how long has the button been held down static byte state = WAIT_FOR_DOWN; // start by waiting for a button press static byte activeButton; // the button that was pushed or held last time int elapsed = _ms - lastReadMS; // how long since we last did this? // only check the buttons every 100 ms (i.e, 10 times a second). // this is how we debounce the button contacts if (elapsed < 100) { return; } lastReadMS = _ms; // Is there a button currently pressed? // We only want to know about one button down at the time. i.e, we're not implementing any "shift" keys. // Note that the other side of the buttons are grounded so the port reads zero when a button is pressed. // My buttons are all on PORTB so the code could be simplified and made slightly faster by reading PORTB directly in one operation // but this is more generic and makes it simple to change the port assignments or add more buttons. byte buttonDown = 0; for (int i = 0; !buttonDown && i < sizeof(_buttonPorts); i++) { if (!digitalRead(_buttonPorts[i])) { buttonDown = i + 1; } } // at this point, buttonDown > 0 means that a button is pressed switch(state) { case WAIT_FOR_DOWN: if (buttonDown) // a button is pressed { downTimeMS = _ms; // start the hold counter state = WAIT_FOR_UP_OR_TIME; // wait for release or timeout activeButton = buttonDown; // remember which button is active for next time around the loop _event = BUTTON_PUSH_EVENT; // raise button push event _eventParam = activeButton; // tell other code which button was pressed } break; case WAIT_FOR_UP_OR_TIME: if (buttonDown != activeButton) { // the button that was pressed is now up if (buttonDown) { // we prefer all buttons to be up now. i.e, we're do cope with two buttons pressed at the same time state = WAIT_FOR_ALL_UP; } else { state = WAIT_FOR_DOWN; // nothing pressed now so go back to waiting for the next button press } } else { // button is still pressed elapsed = _ms - downTimeMS; // how long has it been pressed? if (elapsed >= 5000) // consider it "held" if it has been pressed for 5 seconds { _event = BUTTON_HOLD_EVENT; // raise button hold event _eventParam = activeButton; // tell other code which button was held state = WAIT_FOR_ALL_UP; // wait for all released } } break; case WAIT_FOR_ALL_UP: if (!buttonDown) { state = WAIT_FOR_DOWN; // all released so wait for next press } break; } } // -------------------------------------------------------- // Read encoder // // -------------------------------------------------------- void ReadEncoder() { // the interupt codes moves _encoderCount up or down. static int prevCount; // read the count into another variable. It's a single byte so it's safe to read without stopping interupts byte count = _encoderCount; int diff = count - prevCount; // how much has it shifted // this handles overflow or underflow of _encoderCount if (diff < -100) { diff += 256; } else if (diff > 100) { diff -= 256; } if (_encoderSpeed > 1) // reduce the speed if necessary { diff = diff / _encoderSpeed; } // if diff is > 0 then we moved clockwise // if diff is < 0 then we moved counterclockwise if (diff != 0) { // the encoder moved prevCount = count; // remember for next time _event = ENCODER_TURN_EVENT; // raise event _eventParam = diff; // turn other code how far we moved and in what direction } } // --------------------------------------------------------------------------------------------------------------- // Interupts // we want to do as little as possible here. // by knowing which pin caused the interupt and the state of both pins, we can figure out which direction it moved // --------------------------------------------------------------------------------------------------------------- void Interrupt0() { // this is called whenever pin A of the encoder changes byte inpB = PIND & 2; //1-30-15 chg frm 8 to 2 to match mega chg to portD pins 21 and 20 (vs old mega pins 2 and 3) rls if (PIND & 1) //1-30-15 chg frm 4 to 1 to match mega chg to portD pins 21 and 20 (vs old mega pins 2 and 3) rls { if (inpB) { _encoderCount--; } else { _encoderCount++; } } else { if (inpB) { _encoderCount++; } else { _encoderCount--; } } } void Interrupt1() { byte inpA = PIND & 1; //1-30-15 chg frm 8 to 2 to match mega chg to portD pins 21 and 20 (vs old mega pins 2 and 3) rls if (PIND & 2) // 1-30-15 chg frm 8 to 2 to match mega chg to portD pins 21 and 20 (vs old mega pins 2 and 3) rls { if (inpA) { _encoderCount++; } else { _encoderCount--; } } else { if (inpA) { _encoderCount--; } else { _encoderCount++; } } } // -------------------------------------------------------- // Printing // -------------------------------------------------------- void PrintFrequency(long frequency) { if (frequency == 0) // an "empty" memory channel returns frequency == 0 { LCDPrint(" Empty ", 0, 0); } else { // this formats the frequency in the typical transceiver format with two decimal points separating MHz and KHz char str[11]; sprintf(str, "%010lu", frequency); str[0] = str[2]; str[1] = str[3]; str[2] = '.'; str[3] = str[4]; str[4] = str[5]; str[5] = str[6]; str[6] = '.'; if (frequency < 10000000) { str[0] = ' '; } LCDPrint(str, 0, 0); } } // print the mode in the top left void PrintMode(char str[6]) { LCDPrint(str, 11, 0); } void ClearLowerRight() { LCDClearArea(5, 1, 11); } // prinnt the frequency step in the lower right void PrintFrequencyStep() { char str[8]; if (_frequencyStep < 1000) { sprintf(str, "%4lu Hz", _frequencyStep); } else { sprintf(str, "%3lu KHz", _frequencyStep / 1000); } LCDPrint(str, 9, 1); } // print the frequency IF Offset in Lower Left rls void PrintFrequencyOffset() { char str[8]; if (_freq_adj ==0) { sprintf(str, "IF=%1lu Hz", _freq_adj); } else { sprintf(str, "IF=%1lu MHz", _freq_adj / -1000000); } LCDPrint(str,0,1); } // print the calibration value void PrintClock() { // if _clockLSB == 0x9500 then the offset is zero PrintOffset(_clockLSB - 0x9500); } void PrintOffset(int offset) { if (offset) { char str[7]; sprintf(str, "%+6i", offset); LCDPrint(str, 0, 1); } else { LCDPrint(" 0", 0, 1); } } void ClearOffsetArea() { LCDClearArea(0, 1, 7); } // Set the DDS frequency void SetDDSFrequency() { if (_mode == TRANS_MODE && !_transmit) { SetDDSFrequency(_frequency + CW_FREQ + _ritOffset); } else { SetDDSFrequency(_frequency + _offset); //rls } } void SetDDSFrequency(long frequency) { long clock = CLOCK_BASE | _clockLSB; // get the clock frequency to use. if _clockLSB is 0x9500 then this is exactly 180 MHz // calculate and write the required delta to the DDS // the formula is delta = frequency * (2 to the power of 32) / clock frequency WriteToDDS((frequency * TWO_E32) / clock); } void WriteToDDS(long delta) { // we shift 5 bytes, i.e, 40 bits LSB first PORTF &= B10111111; // load line low WriteByteToDDS(delta); // shift out first byte // now do the other 3 bytes of the delta value for (int i = 0; i < 3; i++) { delta = delta >> 8; WriteByteToDDS(delta); } // this follows example in AD9841 data sheet WriteByteToDDS(0x08); PORTF |= B01000000; // load line high } // Serially shift 8 bits out to the DDS // this is faster than using the Arduino ShiftOut function void WriteByteToDDS(byte data) { byte mask = 1; // mask to pick out the bit to send for (int i = 0; i < 8; i++) { if (data & mask) { PORTF |= B00010000; // sending 1 so set data bit high PORTF &= B11011111; // set clock low } else { PORTF &= B11001111; // sending 0 so set data and clock both low } // 1us delays are much longer than we need. The AD9851 datasheet indicates that only a few ns are necessary // but it seems foolish to push our luck with long wires to the display etc. // with 1us delays we still shift out 40 bits in about 130us which is plenty fast enough // and much faster than using ShiftOut which takes about 620us. delayMicroseconds(1); // let data settle PORTF |= B00100000; // set clock high delayMicroseconds(1); // data hold delay mask = mask << 1; // shift for next bit } } long RestrictFrequency(long frequency) { if (frequency < FREQ_MIN) { frequency = FREQ_MIN; } else if (frequency > FREQ_MAX) { frequency = FREQ_MAX; } return frequency; } void RestrictClock() { if (_clockLSB < CLOCK_LSB_MIN) { _clockLSB = CLOCK_LSB_MIN; } else if (_clockLSB > CLOCK_LSB_MAX) { _clockLSB = CLOCK_LSB_MAX; } } // -------------------------------------------------------- // EEPROM // -------------------------------------------------------- void SaveToEEPROM(unsigned int value, int address) { // save a 2 byte int to EEPROM. The MSB is saved to the lowest address address += 1; for (int i = 0; i < 2; i++) { byte toSave = value & 0xFF; if (EEPROM.read(address) != toSave) // only write if we really need to so we avoid excessive writes { EEPROM.write(address, toSave); } value = value >> 8; address--; } } void SaveToEEPROM(long value, int address) { // save a 4 byte long to EEPROM. The MSB is saved to the lowest address address += 3; for (int i = 0; i < 4; i++) { byte toSave = value & 0xFF; if (EEPROM.read(address) != toSave) // only write if we really need to so we avoid excessive writes { EEPROM.write(address, toSave); } value = value >> 8; address--; } } // read 2 byte int from EEPROM unsigned int ReadIntFromEEPROM(int address) { unsigned int value = EEPROM.read(address); value = value << 8; return value | EEPROM.read(address + 1); } // read 4 byte long from EEPROM long ReadLongFromEEPROM(int address) { long value = 0; for (int i = 0; i < 4; i++) { value = value | EEPROM.read(address); if (i < 3) { value = value << 8; address++; } } return value; } // ---------------------- // LCD driver // ---------------------- void LCDInitialize() { DDRC = B00111111; PORTC = 0; // setup 4 bit mode following page 46 of the HD44780 datasheet delayMicroseconds(50000); // wait 50 ms at power-up LCDWrite4Bits(0x03, false); delayMicroseconds(5000); LCDWrite4Bits(0x03, false); delayMicroseconds(200); LCDWrite4Bits(0x03, false); delayMicroseconds(200); LCDWrite4Bits(0x02, false); delayMicroseconds(5000); // we are now in 4 bit mode LCDWrite(0x28, false); // 2 lines LCDWrite(0x08, false); // display off, cursor off LCDClear(); // clear the display LCDWrite(0x06, false); // increment cursor after writing. Don't shift display LCDWrite(0x0C, false); // move cursor, not the display. Move to right } // print at string at specified position void LCDPrint(char *str, byte column, byte row) { LCDSetCursor(column, row); LCDPrint(str); } // print at string cursor position void LCDPrint(char *str) { while (*str) { LCDWrite(*str++, true); } } // clear an area of the display. This is probably more efficient and wastes // less space than potentially having " " of varying lengths throughout the code void LCDClearArea(byte column, byte row, byte length) { LCDSetCursor(column, row); for (int i = 0; i < length; i++) { LCDWrite(' ', true); } } // clear display. Note the 2 ms delay void LCDClear() { LCDWrite(0x01, false); delayMicroseconds(2000); } // set the cursor position void LCDSetCursor(byte column, byte row) { byte bits = row ? 0xC0 : 0x80; LCDWrite(bits | column, false); } // write a byte as 2 writes of 4 bits each void LCDWrite(byte value, boolean rs) { LCDWrite4Bits(value >> 4, rs); LCDWrite4Bits(value & 0x0F, rs); } // write 4 bits to the display void LCDWrite4Bits(byte value, boolean rs) { if (rs) { value |= 0x20; // set RS bit } PORTC = value; // write data delayMicroseconds(1); // wait 1 us to settle PORTC |= 0x10; // set E high delayMicroseconds(1); // 1 us delay PORTC &= 0x2F; // set E low delayMicroseconds(50); // wait 50 us } // ------------------ // QRSS mode // ------------------ void QRSSMode(boolean reset) { // define the CW (Morse) codes // the most significant 1 is a marks the beginning of the sequence. // from the next bit to LSB, 0 means dit (or dot) and 1 means dah static byte cwCodes[] = { B1010101, // . B110010, // / B111111, // 0 B101111, // 1 B100111, // 2 B100011, // 3 B100001, // 4 B100000, // 5 B110000, // 6 B111000, // 7 B111100, // 8 B111110, // 9 B1001100, // ? B1011010, // @ B101, // A B11000, // B B11010, // C B1100, // D B10, // E B10010, // F B1110, // G B10000, // H B100, // I B10111, // J B1101, // K B10100, // L B111, // M B110, // N B1111, // O B10110, // P B11101, // Q B1010, // R B1000, // S B11, // T B1001, // U B10001, // V B1011, // W B11001, // X B11011, // Y B11100 // Z }; // define the state of this code const byte RESET = 0; const byte START_CHARACTER = 1; const byte START_ELEMENT = 2; const byte KEY_UP_WAIT = 0x03; const byte KEY_UP_END_OF_ELEMENT = 0x03; const byte KEY_UP_END_OF_CHARACTER = 0x43; const byte KEY_UP_END_OF_STRING = 0x83; const byte KEY_DOWN_WAIT = 4; // put your message here. Usually this is just your callsign. // You can only use characters in the table above. i.e, upper case letters, numbers, . / ? static char message[] = "YOUR MESSAGE"; // change fSKShift and dotime to something like 500 and 100 if you want to hear normal speed CW for testing const byte fSKShift = 6; // shift up 6 Hz on key down const int dotTime = 6000; // dot time is 6000 ms. static byte state = RESET; static byte bitMask; // keeps track of where we are in the character static byte cwBits; // this is the cw code from the table above static byte dotsToWait; // used for timing static byte charIdx; // keeps track of where we are in the message static int lastMS = 0; // remember when we last did this if (reset) { state = RESET; return; } if (_event == BUTTON_PUSH_EVENT) { switch (_eventParam) { case 1: SetMode(MEMORY_MODE); // button 1 so move to memory mode break; case 2: state = RESET; // button 2 sets us back at the beginning of the message break; } _event = 0; return; } char toSend; int elapsed; // how long has passed since we were here last time switch (state & 0x3F) // what state are we in? We ignore the 2 most significant bits so the KEY_UP_WAITs go together { case RESET: SetCWKeyState(false, fSKShift); // key up charIdx = 0; // point to start of message state = START_CHARACTER; // start sending break; case START_CHARACTER: toSend = message[charIdx]; // get character to send if (toSend == ' ') { // if it's a space then we wait 4 dot times to give a total of 7 dot times because we have // already done 3, i.e, 1 at the end of the last element and 2 at the end of the last character dotsToWait = 4; lastMS = _ms; state = KEY_UP_END_OF_CHARACTER; } else { if (toSend < '?') // get the cw bits to send { cwBits = cwCodes[toSend - '.']; } else { cwBits = cwCodes[toSend - '.' - 5]; // the 5 is because of a gap in our table between ASCII '9' and '?' } bitMask = 0x80; while (!(cwBits & bitMask)) // find the most significant 1 { bitMask = bitMask >> 1; } bitMask = bitMask >> 1; // move to the first real element state = START_ELEMENT; // start sending } break; case START_ELEMENT: SetCWKeyState(true, fSKShift); // key down dotsToWait = cwBits & bitMask ? 3 : 1; // key stays down for 1 dot time for a dit, 3 for a dah lastMS = _ms; // start timing state = KEY_DOWN_WAIT; break; case KEY_UP_WAIT: case KEY_DOWN_WAIT: elapsed = _ms - lastMS; // how long since we last did this? if (elapsed > dotTime) // have we done a dot time yet? { lastMS = _ms; // remember ms for next time dotsToWait--; if (!dotsToWait) // have we waited all the required dot times? { if (state == KEY_DOWN_WAIT) { SetCWKeyState(false, fSKShift); // key up dotsToWait = 1; // key was down so now wait 1 dot time state = KEY_UP_END_OF_ELEMENT; } else { switch(state) { case KEY_UP_END_OF_ELEMENT: // we just finished the 1 dot wait after a dit or dah if (bitMask > 1) // have we sent all this character? { bitMask = bitMask >> 1; // no, so send next element state = START_ELEMENT; } else { dotsToWait = 2; // we're finished this character so wait 2 more dot times to give a 3 dot character spacing state = KEY_UP_END_OF_CHARACTER; } break; case KEY_UP_END_OF_CHARACTER: // we just finished the 3 (1+2) dot wait after a character charIdx++; // point to next character in the message if (message[charIdx]) // is this the end of the message { state = START_CHARACTER; // not yet so send next charatcer } else { // end of message to wait 4 dot time. this gives a total of 7 dot times dotsToWait = 4; // so we're effectively sending a space before starting the message again state = KEY_UP_END_OF_STRING; // you might want to make that time a little bigger } break; case KEY_UP_END_OF_STRING: // we just finished the space at the end of the message charIdx = 0; // reset the pointer and start the message again state = START_CHARACTER; break; } } } } break; } } // toggle the 'key' up and down void SetCWKeyState(boolean isKeyDown, byte fSKShift) { // key down shifts the frequency up SetDDSFrequency(_frequency + (isKeyDown ? fSKShift : 0)); LCDSetCursor(15, 0); // write a * on the display to indicate key down LCDWrite(isKeyDown ? '*' : ' ', true); }