Uploading code onto the Arduino Uno to allow external control

Noob here, but DESPERATE for any kind of help anyone might be able to provide.

What we want:
To control hardware using the arduino and an external software program. To do this, we upload code onto the Arduino Uno which allows us to hereafter utilize an external software (Experimentor Software) to program in. This Experimentor Software is 'idiot friendly' (the language is much simpler than C++. Yes, it's possible to make it simpler) and so that's why we're using it. The so the chain of command is Experimentor Software, to the Arduino, to our external hardware that we want to use for our research experiments (doors, lights, pellet dispensers, etc). The schematics connecting our Arduino to our hardware involve relays, and they are not the problem as we've tested every connection thoroughly. The relays are all working and will turn on independent of the arduino board, and all the hardware works when the correct current is applied. [i.e. we know everything is hooked up right]

What actually happens:
The initial code that we use to upload onto the Arduino loads just fine. We can also write a great many programs that utilize the Experimentor Software just fine. HOWEVER, when we attempt to utilize the Experimentor Software to control our hardware, we get 'resend the command #1' error messages.

What we're working with:
The Arduino board works fine. The relays and hardware can be controlled and are wired up correctly. The Experimentor Software is functioning and we can program a great many other tasks (independent of the arduino) using the software. Essentially, everything is working fine independently...it's the integration that seems to be the problem. That's why we are highly suspect of the initial code that we've uploaded onto the Arduino, as this code is essential for facilitating all future communication with the Arduino when programming in Experimentor.

I know that it's probably not likely that someone, not knowing anything about the syntax/function of Experimentor software, would be able to identify a problem in the code, but its very generic and there might be something obvious we should have included in a code looking to interface the Arduino with external software.

I'm sure it's easier to see the entire code in context, but it's too long to include in this post. There general 'sections' included in it are 1) Constants used by the code, 2) The master debug function 3) The master Pin class 4) Setup code 5) The main application loop 6) Serialization code 7) Process commands from Experimentor (and the sendAcknowledgement() function) 8) Functions for writing to Experimentor and 9) Low-level I/O functions. I feel like the problem is probably in the master pin class, so that's what I've attached

///////////////////////////////////////////////////////////////////////////////////////////////////
// The master Pin class
///////////////////////////////////////////////////////////////////////////////////////////////////
class PinInfo {

	// Create a new PinInfo object
	public: PinInfo( int pinType, int pinIndex ) {
		// Check pre-conditions
		if( pinType!=ANALOG && pinType!=DIGITAL ) {
			DEBUG_PRINT("Invalid pin type: " + String(pinType) );
			return;
		}

		// Setup the instance's member variables
		_pinType  = pinType;
		_pinIndex = pinIndex;
		resetPin();
#ifdef DEBUG
		const char* pinTypeString = pinType==ANALOG ? "Analog" : "Digital";
		DEBUG_PRINT(String(pinTypeString) + " Pin #" + String(_pinIndex) + String(" created."));
#endif
	}
	
	// Reset the pin
	public: void resetPin() {
		// Use impossible values to ensure that a change will result
		// in a message to Experimentor telling the PC software what
		// the new value is
		_oldValue = -32768;
		_newValue = -32768;
		 _sentZero = false;

		// Setup the default direction for the pin
		if( _pinType==ANALOG ) {
			_direction = UNUSED;
		} else {
			// Digital; set the output pin mode and the value
			setPinMode(OUTPUT, DIGITAL_HIGH_LOW);
			setOutputPinValue(LOW);
		}//else
	}

	// Get the pin-type (either ANALOG or DIGITAL) for this pin
	public: int getPinType() {
		return _pinType;
	}
	private: int _pinType;

	
	// Get the pin-index that this instance represents
	public: int getPinIndex() {
		return _pinIndex;
	}
	private: int _pinIndex;
	
		
	// Get the pin direction
	public: int getPinDirection() {
		return _direction;
	}
	private: int _direction;	// INPUT or OUTPUT
	
	
	// Get the pin direction
	public: String getPinDirectionString() {
		if( _direction==INPUT ) return String("INPUT");
		if( _direction==OUTPUT ) return String("OUTPUT");
		return String(_direction);
	}

	
	// Defines if this pin should use pulse-width
	// modulation for output (DIGITAL_PWM),
	// or just standard digital (DIGITAL_HIGH_LOW)
	public: int getDigitalPinOutputMode() {
		return _outputMode;
	}
	private: int _outputMode;	// DIGITAL_HIGH_LOW OR DIGITAL_PWM


	// Get the pin direction
	public: int getPinValue() {
		return _newValue;
	}
	private: int _newValue;


	// Configure the pin mode and remember it for later use
	// @direction - one of: INPUT or OUTPUT
	// @outputMode - one of: DIGITAL_HIGH_LOW OR DIGITAL_PWM
	public: void setPinMode( int direction, int outputMode ) {
		// Analog pins used for output only support on/off output (not PWM)
		if( _pinType==ANALOG ) outputMode = DIGITAL_HIGH_LOW;
	
		// Figure out the pin # to use (analog pins are offset)
		int pin = _pinIndex;
		if( _pinType==ANALOG ) pin += A0;

		// Remember the direction and output mdoe
		_direction = direction;
		_outputMode = outputMode;
		pinMode(pin, _direction);		// Tell the Arduino about the pin's direction
		DEBUG_PRINT("Setting mode on pin #" + String(_pinIndex) + String(" to ") + getPinDirectionString());
	}


	// Checks an input pint to see if its value has changed
	// from the last time we read from the pin.
	// If it has, then we need to tell Experimentor Software about the new value.
	public: void checkInputPin( ) {
		// Only do this if this pin is an input pin
		if( _direction!=INPUT ) return;

		// Read the value from this pin
		int newValue;
		int requiredDelta = 1;	// Default delta is 1 (for digital)
		if( _pinType==ANALOG ) {
			requiredDelta = ANALOG_REQUIRED_DELTA;
			newValue = analogRead(_pinIndex);
		}
		else {
			newValue = digitalRead(_pinIndex);
		}//else
		
		// Has the value changed enough to trigger a call to Experimentor?
		// Without this the analog input pins would constantly be sending data
		// and overload the serial buffer, basically crashing the Arduino.
		// So that's what the delta logic is for, to ensure we don't overflow
		// the output serial buffer and/or hang the Arduino sending so much
		// output data
		// The extra sent-zero logic here is to ensure that if the value is close to
		// zero (say 5, which is less than the required analog delta)
		// and then drops to zero that we'll still send the zero;
		// that is, zero is a special case where we want to bypass the delta logic
		// to ensure we send the zero.
		int delta = abs(newValue - _oldValue);
		if( delta>requiredDelta || (!_sentZero && newValue==0) ) {
			// The pin has changed its value; let Experimentor Software know.
			_newValue = newValue;
			_oldValue = newValue;
			serialWriteInputPinCommandToExperimentor(*this);
			
			// Remember if we sent a zero
			_sentZero = newValue==0;
		}//if - new value
	}
	private: bool _sentZero;


	// If this is an output pin, set it's value
	public: void setOutputPinValue( int newValue ) {
		// Only do this if this pin is an output pin
		if( _direction!=OUTPUT ) return;	
	
		// Move the previous new value to the old value
		_oldValue = _newValue;

		// Figure out the pin # to use (analog pins are offset)
		int pin = _pinIndex;
		if( _pinType==ANALOG ) pin += A0;
		
		// Set the value of the pin based on how this output pin is configured
		_newValue = newValue;
		if( _outputMode==DIGITAL_PWM ) {
			// The pin is configured as a PWM pin,
			// so it can be anything between 0 and 255 and we use analog write
			// (which does not actually write to the analog pins - they're read-only)
			analogWrite(pin, newValue);
		} else {
			// The pin is NOT configured as a PWM pin, so it is either HIGH or LOW
			digitalWrite(pin, newValue);
		}
	
#ifdef DEBUG
		const char* pinTypeString = _pinType==ANALOG ? "Analog" : "Digital";
		DEBUG_PRINT( String(pinTypeString ) + " pin #" + String(_pinIndex) + String(" set to: ") + String(newValue));
#endif
	}
	
	private: int _oldValue;
};

// Our corresponding array of analog pins
PinInfo* analogPins[MAX_ANALOG_PIN_NUMBER+1];	// +1 for the zero indexed pin

// Our array of digital pins
PinInfo* digitalPins[MAX_DIGITAL_PIN_NUMBER+1];	// +1 for the zero indexed pin

Like I said, ANY help or guidance AT ALL would be so very appreciated. I shall be in your debt forever. And if I haven't explained myself properly please let me know and I will do my best to clarify

What do the commands sent to the arduino look like. Where's the code which reads and actions those commands?

I'm no fan of C or C++, I'd much prefer to program in Ruby but I realize that it's not really suitable for a microprocessor. And the Arduino system makes C++ tolerable, or at least a lot easier than Assembler.

I can't help feeling that a programming system that has to guard against invalid pintypes is rather missing the whole concept of understanding microprocessors.

...R

holmes4 here's what the commands sent to the arduino look like

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Process commands from Experimentor (and the sendAcknowledgement() function)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Try and get the command ID of the next command to execute
int getCommandType() {
	int commandType = serialReadInt();
	if( (commandType & 0xFF00)!=CMD_PREFIX_MASK ) {
		// Unknown command, try and synchronize
		DEBUG_PRINT( String("Off-synch; attempting to correct... 0x") + String(commandType));
		commandType = synchronizeInput();
	}
	
	return commandType;
}

// The logic for processing an unexpected command ID
// commandType - one of the constants defined at the top of the code that
//				 uniquely defines the command type; that is, which command to run
// id		   - The command ID, which "uniquely" identifies this particular command
void dealWithUnexpectedCommandId( int commandType, int id ) {
	// Is this a restart command?
	if( commandType==CMD_RESTART && id==0 ) {
		processRestartCommand();
		return;
	}

	// Did we get the previous command again?
	int previousId = expectingCommandId - 1;
	if( id==previousId ) {
		// We already processed this ID; flush it and resend the acknowledgement
		flushSerialInputCommand(commandType);
		sendAcknowledgement(previousId);
	}//if - previous ID

	// If it's a completely unexpected ID simply throw it out and flush everything
	DEBUG_PRINT( "Unexpected ID: " + String(id) + String("  expected ") + String(expectingCommandId) );
	sendResendRequest(expectingCommandId);
}


// Reset the Ardunio
void processRestartCommand() {
	// The command counter will be restarted
	expectingCommandId = 1;

	// Initialize all of the pins again
	for( int i=0; i<=MAX_ANALOG_PIN_NUMBER; i+=1 ) {
		analogPins[i]->resetPin();
	}//for
	for( int i=0; i<=MAX_DIGITAL_PIN_NUMBER; i+=1 ) {
		digitalPins[i]->resetPin();
	}//for
}


// Process the set pin mode command from Experimentor
// id - the command's pseudo-unique ID
// pinType - either DIGITAL or ANALOG
// pinIndex - the pin # whose value will be set
bool processSetPinModeCommand(int id, int pinType, int pinIndex) {
	int dbyte = serialReadByteWithTimeout();	// The direction byte
	int obyte = serialReadByteWithTimeout();	// The output-type byte
	int checksum = serialReadByteWithTimeout();
	int expectedChecksum = (0x2A ^ ((pinIndex<<4) + (dbyte<<3) + (obyte<<2) + pinType)) & 0xFF;
	if( checksum!=expectedChecksum ) {
		DEBUG_PRINT("Set pin-mode command checksum failed");
		return false;
	}//if

	// Okay, everything looks good, set the pin and send an acknowledgement
	// (Note that the analog pins are input only, so we'll never have to set their mode)
	PinInfo* pin = getPin(pinType, pinIndex);
	if( pin==NULL ) return false;
	
	int direction = dbyte==0 ? OUTPUT : INPUT;
	int outputType = obyte==0 ?  DIGITAL_HIGH_LOW : DIGITAL_PWM;
	pin->setPinMode( direction, outputType );
	DEBUG_PRINT("Successfully set pin mode");
	sendAcknowledgement(id);
	return true;
}

// Process the set pin value command from Experimentor
// id - the command's pseudo-unique ID
// pinType - either DIGITAL or ANALOG
// pinIndex - the pin # whose value will be set
bool processSetPinValueCommand(int id, int pinType, int pinIndex) {
	int value = serialReadInt();
	int checksum = serialReadByteWithTimeout();
	int expectedChecksum = (0x2B ^ ((pinIndex<<4) + (pinType<<3) + value)) & 0xFF;
	if( checksum!=expectedChecksum )
		return false;

	// Okay, everything looks good, set the pin and send an acknowledgement
	PinInfo* pin = getPin(pinType, pinIndex);
	if( pin==NULL ) return false;

	pin->setOutputPinValue( value );
	DEBUG_PRINT("Successfully set pin " + String(pinIndex) + " to: " + String(value));
	sendAcknowledgement(id);
	return true;
}

// Returns a pointer to the appropriate pin 
// pinType - either DIGITAL or ANALOG
// pinIndex - the pin # whose value will be set
PinInfo* getPin(int pinType, int pinIndex) {
	if( pinIndex<0 ) return NULL;
	
	if( pinType==ANALOG ) {
		if( pinIndex>MAX_ANALOG_PIN_NUMBER ) return NULL;
		return analogPins[pinIndex];
	}

	if( pinType==DIGITAL ) {
		if( pinIndex>MAX_DIGITAL_PIN_NUMBER ) return NULL;
		return digitalPins[pinIndex];
	}

	return NULL;
}


// Send a command acknowledgement for the processed command
void sendAcknowledgement(int id) {
	serialWriteInt(CMD_ACKNOWLEDGE);
	Serial.write(id);	// Acknowledging this command ID
	Serial.write(id);	// Send the ID twice
}

// Send a command resend request for the given command number
void sendResendRequest(int id) {
	flushSerialInput();
	
	// Now send the resend request
	serialWriteInt(CMD_RESEND);
	Serial.write(id);	// Acknowledging this command ID
	Serial.write(id);	// Send the ID twice
}

// Flush the given command, reading only the bytes consumed by the paricular
// command type
void flushSerialInputCommand(int commandType) {
	int bytesToConsume = 0;
	switch( commandType ) {
		case CMD_SET_PIN_MODE:
			bytesToConsume = 3;
			break;
		
		case CMD_SET_OUTPUT_PIN_VALUE:
			bytesToConsume = 4;
			break;
	}//switch
	
	// Consume the rest of the command
	for( int i=0; i<bytesToConsume; i+=1 )
		serialReadByteWithTimeout();
}

// Only flush the serial's input
void flushSerialInput() {
	while( Serial.available() )
		Serial.read();
}

// Attempts to synchronize the input back to a recognized command
int synchronizeInput() {
	while( Serial.available()>0 ) {
		int nextByte = serialReadByteWithTimeout();
		if( nextByte==CMD_PREFIX ) {
			nextByte = serialReadByteWithTimeout();
			if( nextByte==0 ) return 0;
			int commandType = CMD_PREFIX_MASK | (nextByte & 0xFF);
			return commandType;
		}//if
	}//while
	return 0;
}



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions for writing to Experimentor
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// A very simple debug message function
void debugToExperimentor( String message ) {
	serialWriteInt(CMD_DEBUG_OUTPUT);
	Serial.print(message);
	Serial.write(0);
}

// Writes an "input-pin changed" command data structure to the serial port
// telling Experimentor software running on the PC that one of the
// input pins on the Ardino has a new value
void serialWriteInputPinCommandToExperimentor( PinInfo& pinInfo ) {
	// Bytes #1 & #2: Write the command code
	serialWriteInt(CMD_INPUT_PIN_VALUE_CHANGED);

	// Byte #3: Write the pin type (either analog or digital)
	Serial.write(pinInfo.getPinType());
	
	// Byte #4: Write the pin whose value has changed
	Serial.write(pinInfo.getPinIndex());

	// Bytes #5 and #6: Write the pin's new value
	serialWriteInt(pinInfo.getPinValue());
}

And Robin2 I understand what you're saying about the invalid pintypes, but with the hardware we're using a few of the pins will always input/output. Once we had what we wanted we didn't need to to be versatile.
Thank you both for your comments!

Not meant to derail your project but Arduino has a fairly good firmata sketch for external host to control its inputs and outputs. If you want to dumb down the arduino then try firmata.

For anyone who wants to learn programming, c/c++ is the dominating family of languages. Other languages have relatively narrow applications or syntax that don't translate into each other. I am not a fan of Perl. I taught myself some Perl but can't stand the way it handles naming and referencing variables and their values etc. All too arbitrary to me. All these interpreting languages are trying to use syntax to do what functions are designed to do. OOP smudges the two with overloading operators and what not but a programmer should know data types well and not just generic containers that with magic syntax (is it the $ or single quote or $ and single quote that does the trick?!) can produce the right outcome. I am not a fan of FORTRAN. Taught myself a bit of it and had to stand one semester of formal study. It's a dying language. I was not a fan of C but ended up learning it (can't remember why, maybe high school was too easy). It is the best all around language you can find and what you learn is far more than just programming. You will understand computer architecture, operating system, etc.