Reverse engineering someone else's code issue

Hi all,

I am a first time Arduino user and was tasked with this project at work.

The project is a safety inhibitor, which via a RS232 connection, stops a motor running if their is no communication between the motor and the computer running a control software.

I was given some bare PCB boards and the Arduino code that someone else wrote.

After building the boards and testing, the project is not working, so was hoping I could share the code here and if anyone could see anything obviously wrong with it?

Hardware wise, I am am using and Arduino Nano R3 for programming, and once the sketch complies and uploads successfully, I am transplanting the ATMEGA328P IC onto the PCB.

Here is my code


int         timer1_counter;
int         counter2 = 0;

boolean     framerunning = false;

String COMMAND;


void setup()
{
 // start serial port at 9600 bps:
 Serial.begin(9600,SERIAL_8N2);
 Serial.setTimeout(50000);  
 
 pinMode(13, OUTPUT);
 
 noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;

  timer1_counter = 100;   // preload timer 65536-16MHz/256/2Hz
  
  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12) | (1 << CS10);      // 1024 prescaler 
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();             // enable all interrupts
}
  


void loop()
{
   if (Serial.available()) {
   
   COMMAND = Serial.readStringUntil('\r');  
      
   // determines wether the command
   if (COMMAND == "0"){
   framerunning = false;  
   digitalWrite(13, LOW);
   // Serial.println("0 read, which is stop command");  
 }
   else if(COMMAND == "1"){
   framerunning = true;   
   digitalWrite(13, HIGH);
   // Serial.println("1 read, which is travel upwards command");
   }  
   else if(COMMAND == "2"){
   digitalWrite(13, HIGH);
   framerunning = true; 
   // Serial.println("2 read, which is travel downwards command"); 
   }  
   
   Serial.print(COMMAND);
   Serial.write('\r');
   TCNT1 = timer1_counter;
   counter2 = 0;

}


}

ISR(TIMER1_OVF_vect)        // interrupt service routine 
{
  // Serial.println("timer interupt ran"); 
  TCNT1 = timer1_counter;   // preload timer
  if(counter2 > 4){ 
  if(framerunning == true){  
  // Serial.println("frame running condition executed");
  Serial.write("0");
  Serial.write('\r');
  framerunning = false;
  digitalWrite(13, LOW);
  }
  
  counter2 = 0;
  }
  else{
  counter2++;
  }
}




Anything obviously wrong with that?

Hi! Welcome to the Forum.

In a quick reading, missing the keyword void at the ISR. Try this version:

int         timer1_counter;
int         counter2 = 0;

boolean     framerunning = false;

String COMMAND;


void setup()
{
 // start serial port at 9600 bps:
 Serial.begin(9600,SERIAL_8N2);
 Serial.setTimeout(50000);  
 
 pinMode(13, OUTPUT);
 
 noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;

  timer1_counter = 100;   // preload timer 65536-16MHz/256/2Hz
  
  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12) | (1 << CS10);      // 1024 prescaler 
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();             // enable all interrupts
}
  


void loop() {
   if (Serial.available()) {
   
   COMMAND = Serial.readStringUntil('\r');  
      
   // determines wether the command
   if (COMMAND == "0"){
   framerunning = false;  
   digitalWrite(13, LOW);
   // Serial.println("0 read, which is stop command");  
  }
   else if(COMMAND == "1"){
   framerunning = true;   
   digitalWrite(13, HIGH);
   // Serial.println("1 read, which is travel upwards command");
   }  
   else if(COMMAND == "2"){
   digitalWrite(13, HIGH);
   framerunning = true; 
   // Serial.println("2 read, which is travel downwards command"); 
   }  
   
   Serial.print(COMMAND);
   Serial.write('\r');
   TCNT1 = timer1_counter;
   counter2 = 0;
 }
}

void ISR(TIMER1_OVF_vect)        // interrupt service routine 
{
  // Serial.println("timer interupt ran"); 
  TCNT1 = timer1_counter;   // preload timer
  if(counter2 > 4){ 
  if(framerunning == true){  
  // Serial.println("frame running condition executed");
  Serial.write("0");
  Serial.write('\r');
  framerunning = false;
  digitalWrite(13, LOW);
  }
  
  counter2 = 0;
  }
  else{
  counter2++;
  }
}

Thanks for the suggestion, but after I tried to compile that I got the following error message

In file included from C:\Users\dperry1\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.7\cores\arduino/Arduino.h:30:0,
                 from C:\Users\dperry1\AppData\Local\arduino\sketches\3749747396D0EAC91409A2C29A73C858\sketch\sketch_apr15a.ino.cpp:1:
C:\Users\dperry1\AppData\Local\Temp\.arduinoIDE-unsaved2026315-8732-1bltmnm.o2kk\sketch_apr15a\sketch_apr15a.ino:60:6: error: expected unqualified-id before string constant
 void ISR(TIMER1_OVF_vect)        // interrupt service routine
      ^
exit status 1

Compilation error: expected unqualified-id before string constant

You have a computer which controls a motor. You want to detect the failure case where there is no communication between the computer and the motor. You are assembling a system to detect this failure case. Is that right ?

I'd say that the best strategy is that the computer itself determines is there is a correct communication between it and the motor. It should then give some sort of regular "the connection to the motor is alive" message to a watchdog system. If that message is missing for a certain period of time, then the watchdog raises an alarm. Is this what you are doing, that is building such a "watchdog" ?

Maybe show a block diagram of the components of your system and how these are intercommunicating.

The answer to both of your questions is yes.

Block diagram incoming

I think I gave a bad suggestion. Looking for other examples, the line

ISR(TIMER1_OVF_vect) 

without the "void" seems correct.

Variables used in both the ISR and elsewhere in the code need to be declared volatile.

This line should print some value to the serial monitor.

Are any values ​​being printed?

The code is really bad on multiple fronts…

It would be better to rewrite it all from scratch - with a clear understanding of how the issue detection works (which you need to clarify).

A cleaner design is to remove the ISR entirely and reduce the system to a single periodic time check using millis(). The Arduino then maintains one piece of state: the timestamp of the last valid received command. This turns the problem into a simple asynchronous state machine driven by serial input plus time comparison.

Something as basic as this might work

const unsigned long timeoutMs = 2000;
unsigned long lastHeartbeat = 0;

bool frameRunning = false;

int command = -1;

void setup()
{
  Serial.begin(9600, SERIAL_8N2);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  lastHeartbeat = millis();
}

void loop()
{
  command = Serial.read();

  switch (command) {
    case '0':
      frameRunning = false;
      digitalWrite(13, LOW);
      break;

    case '1':
    case '2':
      frameRunning = true;
      digitalWrite(13, HIGH);
      lastHeartbeat = millis();
      break;

    default:
      break;
  }

  if (frameRunning && (millis() - lastHeartbeat) > timeoutMs) {
    frameRunning = false;
    digitalWrite(13, LOW);
    Serial.write('0');
    Serial.write('\r');
  }
}

Typed here from my phone - mind typos

We need to understand how you inject the commands and listen - are you plugged as a middle man on the serial link ?

int         timer1_counter;
int         counter2 = 0;

boolean     framerunning = false;

The most obvious is that these variables should be declared volatile since they are used and modified in both the main thread and the ISR

Im not a fan of calling Serial.print() from an ISR.

I'm a bit tied to the existing system as it's for very old hardware, so just wanted to ask...is there a way to copy the working code from a known working ATMEGA328p ?

Not the c++ code
Possibly the binary but that won’t help much

Can you clarify the exact hardware set up?

If you just want to clone it as-is into another Mega328, sure. But you can't extract the source code that you would need to make changes.

Sounds like what you're saying is along the way, source code revision control has been lost, and you're not sure what's really in there; the code you've presented is either:

  • a best guess at what might be in there
  • the most recent file you've located, which might or might not be anywhere near what's really in there

Is that the case?

If either is the case, you're back to defining what the real requirements are, from the system you have working in front of you.

Thanks for all the help everyone.

I have just transplanted the known working 328p IC into a new PCB and it doesn't work, whereas transplanting one of the 328p's that I programmed into the known working PCB works...so therefore despite the seemingly wonky code, it's a hardware issue.

Be careful if that is the only chip you have containing a working application.

I guess that the new PCB does not exactly match the one which had the working chip. There are lots of possibilities for example:

  1. The old chip tested a jumper which is missing on the new board.
  2. The old chip used the crystal oscillator pins as GPIO pins
    etc. and many others.

So you anyway have a working solution ?

please explain, with some detail, just how you are testing the program! Are you actually monitoring the motor communications and interrupting it? I do not see the program giving any indication that it is running.

Indeed. It's hard to believe someone got paid to write that.

Presumably they're no longer employed as a programmer.

The whole project seems bogus. The RS-232 line is used by some other computer to talk to a motor controller, then this project also tries to SEND on the same RS-232 line a code to stop the motor. There can only be one sender on an RS-232 line.