0
votes

I have a simple circuit, with an ESP8266 and an Arduino Nano, communicated via Serial.

To test this communication, I send a simple "TURN ON" string and the Arduino should turn on a LED.

This is the Arduino code:

void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT);
}

void loop() {

  if(Serial.available() > 0) 
  {
    String command = "";
    while(Serial.available())
    {
      command += (char)Serial.read();
      delay(1);
      if (command == "T"){
        while(Serial.available())
        {
          command += (char)Serial.read();
          delay(1);
        }
      }else{
        command = "";
      }
    }

    if(command == "TURN ON") {
      digitalWrite(3, HIGH);  
    }

    if(command == "TURN OFF") {
      digitalWrite(3, LOW);
    }
  }

  delay(500);
}

This works fine.

Now, I would like to replace the Arduino with an Atmega328p.

I have the basic circuit: enter image description here

Plus the led, and the TX and RX pins connected to the ESP8266.

If I upload the same code to the Atmega328p, it doesn't work, so I guess I'm missing something very important (like UART configuration or something) but I don't know what that is

3

3 Answers

1
votes

I am guessing that you have used an external programmer with the Atmega328p, and it is a fresh Atmega328p.

If my assumptions are right, then the fuse bits within your Atmega328p are set to use the internal 1MHz clock, and that is causing the problem.

What you can do to fix this: Connect the programmer to the Atmega328p Go to tools>boards, select Arduino Uno in the Boards. Go to tools>programmer select the programmer you are using. Go to tools and select Burn bootloader.

You can then upload your code to the Atmega328p, it should start working the way you expect it to.

I hope this helps.

1
votes

In case that someone arrives here with a similar issue:

Yes, it should work as I intended.

I was using a damaged breadboard! (you can't receive a message if the pins are not connected ... )

0
votes

The way you use the Serial API is very sensitive to the timing of the bytes. Depending on the timing of the bytes that are received, you might just go back to the top of your loop and set command to the empty string, meaning your program forgets about the bytes it saw earlier. You were lucky that this code worked on one processor, and it's not surprising that it fails on another.

How about you limit yourself to one-byte commands for now? 'T' could turn on the LED and 'S' could turn it off. To implement multi-byte commands, you will probably need a small state machine, and you will need to feed it bytes from the UART one at a time, in a way that doesn't depend on the timing.