Loaded my program in an ATMega but it does not work

Hello friends.

I'm making a sensor with an ATMega328, so I'm programming it with the Arduino IDLE. I have found information on how to load a sketch from an arduino UNO to an ATMega328, what happens is, that I have done it twice with two arduino UNO's and I have screwed them up. Then I took an Arduino Mega and did the same thing and loaded the sketch, this time the program did load successfully on the ATMega328.

Now, it happens that when I connect my microcontroller with the sketch to my circuit, it doesn't work as it should. As extra information I could tell you that my circuit uses an Xbee that allows to communicate wirelessly with other devices. My program is in an infinite loop until a message arrives by XBee, this makes the program exit the loop, and the circuit starts to work.

This is my code.


#include <SD.h>
#include <SPI.h>
#include <Wire.h>
#include <TimeLib.h>
#include <DS1307RTC.h>
#include <SafeString.h>
#include <SoftwareSerial.h>

//--------------------------------------INICIALIZACION DE VARIABLES------------------------------

const int chipSelect = 4;

const int ADCpin = A1;
float voltPanel;
String sfVolts = "";

SoftwareSerial XBeeSerial(2, 3); //(Rx, TX)
uint8_t Rx_nextByte;

//--------------------------------------ENCABEZADO DE TRAMA DE ENVIO------------------------------

byte packet1[] = {0x7E, 0x00, 0x27}; //Byte delimitador y Longitud de trama // variar por el voltaje
byte packet2[] = {0x10, 0x01, 0x00, 0x13, 0xA2, 0x00, 0x40, 0xD7, 0xAE, 0xAD, 0xFF, 0xFE, 0x00, 0x00,}; //Id de trama, tipo de trama, direccion de 64bits, opciones y numero de brincos.
// xx.xx,00:11:46,05/01/2021 == 25 chars
byte fullPacket[43];// (Delimitador + longitud )+ (tipo + direccion)+ voltage + fecha + checksum = 37
//  [3 + 14 + 4 + 19 + 1]
char buffer [27]; // 19 la fecha  +1  '\0', 25 bytes de tamaño // cambiar porque hay voltaje
#define DEBUG SafeString::Output

void setup() {
  Serial.println("CODIGO PRINCIPAL");



void loop() {

//--------------------------------------LOOP MIENTRAS ESPERA EL MENSAJE DE ARRANQUE------------------------------
  Serial.println("Espera a recibir señal");
  while (XBeeSerial.available()) {
    Rx_nextByte = XBeeSerial.read();
    if (Rx_nextByte == START_DELIMITER) {
      //Inicia a mandar datos Si el primer Byte que recive de la PC es un 0x7E.  
      Serial.println("Señal recibida");

//--------------------------------------SE INICIA TOMANDO LA HORA FECHA ------------------------------    

      tmElements_t tm;
      if (RTC.read(tm)) {
        sprintf(buffer, "%02d:%02d:%02d,%02d/%02d/%04d", tm.Hour , tm.Minute, tm.Second, tm.Day, tm.Month, tmYearToCalendar(tm.Year));
        Serial.println(buffer); // Compruebo la fecha y hora actual.
//--------------------------------------SE COMIENZA A FORMAR Y CONTAR LOS CARACTERES DEL ENCABEZADO ------------------------------  
        size_t idx = 0;
        memmove(fullPacket + idx, packet1, sizeof(packet1));
        idx += sizeof(packet1);
        memmove(fullPacket + idx, packet2, sizeof(packet2));
        idx += sizeof(packet2);
        if ((idx + 6 + 19 + 1) > sizeof(fullPacket)) {
          Serial.println(F("1 Paquete completo esta mal."));

//--------------------------------------SE TOMAN 20 MUESTRAS DEL VOLTAJE DEL SENSOR EN EL ADC ------------------------------  
        sfVolts = ""; // Voltage xx.xx == 5 y coma 1 == 6     
        const int SAMPLES = 20;
        float fv = (float(analogRead(ADCpin)) * 4.7 / 1023) * 6 + 10;
        fv = 0;
        for (int i = 0; i < SAMPLES; i++) {
          fv = fv + ((float(analogRead(ADCpin)) * 4.7 / 1023) * 6 + 10);
        fv = fv / SAMPLES;
        sfVolts = String(fv)+',';

//--------------------------------------SE EMPAQUETA EL DATO DEL ADC EN LA TRAMA------------------------------          
        memmove(fullPacket + idx, sfVolts.c_str(), 6); // Siempre van a ser 6 caracteres de largo
        idx += 6;
        if ((idx + 19 + 1) > sizeof(fullPacket)) {
            Serial.println(F("2 Paquete completo esta mal."));
//--------------------------------------SE EMPAQUETA EL DATO DEL RTC EN LA TRAMA------------------------------          
        memmove(fullPacket + idx, buffer, 19);
        idx += 19;
        //Dejo un ultimo byte para tener el Checksum.
        if ((idx + 1) != sizeof(fullPacket)) {
            Serial.println(F("3 Paquete completo esta mal."));
//--------------------------------------SE DA EL FORMATO A LA TRAMA D DATOS Y SUS CARACTERES SE CONVIERTEN A HEX------------------------------          
        int chksum = 0;
        for (size_t i = 3; i < idx; i++) { // comienza despues del tamaño dela trama
          chksum += fullPacket[i];
        chksum = (0xff & chksum);
        chksum = (0xff) & (0xff - chksum);
        fullPacket[idx] = chksum;
        idx++; // El tamao total de la trama
        if (idx != sizeof(fullPacket)) {
          Serial.println(F("fullPacket size error"));
        size_t printSize = idx * 3; // ..<space>
         XBeeSerial.write (fullPacket , idx);
         Serial.println();//Se comprueba que el formato de la Trama API.
//--------------------------------------SE GUARDAN LOS DATOS EL EL DATALOGGER------------------------------          
        String dataString = "";
        dataString += String(sfVolts);
        dataString += String(buffer);
        File dataFile = SD.open("TensionDePanel.txt", FILE_WRITE);
        if (dataFile) {
//--------------------------------------SE ENVIA LA TRAMA------------------------------          
        //XBeeSerial.write (fullPacket[i], 3);//Se envia la trama del sensor a la PC.

//--------------------------------------FUNCION QUE DA FORMATO A LA HORA Y FECHA------------------------------          
void print2digits(int number) {
  if (number >= 0 && number < 10) {

My connections are this:


I click the reset button too but doesnt work.

I believe that AREF should have a cap to GND and not tied to VCC. Which may or my not affect your sketch.

1 Like

But Why? Can you explain to me ? Because ADC need AREF to have a level to compare in an range of 5V to 0V.

Have you got the 328 on a PCB?

If so can you please post an EXPORT of the PCB pattern of that you program too, from your CAD so we can see your component layout.

If not, can you post an image(s) of your project so we can see your component layout.
Do you have a DMM?

Thanks.. Tom... :smiley: :+1: :coffee: :australia:

Hi Tom, I'm testing it on a breadboard for now. The PCB circuit I'm designing, in fact that image I uploaded above is a part of the whole system I'm making. I would be happy to share the files.

The problem with the photo with the atmega on the breadboard, is that it has too many wires and makes the connections not appreciated.

These are the PCB schematic files, I am working with the Eagle program.
PCBEsquematic.zip (63,9 KB)

This is a block diagram.

If you are comparing to 5V, then the ADC reference can come from AVCC, which you have connected to VCC. It can also come from the internal reference.

The RESET pin is one of the most fundamental inputs to the micro and requires no user code to function. Perhaps you can expand on "doesn't work" .

How are you loading your sketch? Looking at the schematic, I assume you have an ICSP header somewhere that's not shown as you have no connections to the UART that is normally used alongside the boot loader to load sketches.

Can you expand on what you mean by this.

If you have a schematic, it is better to post a picture of it (Eagle can do this for you), as people are wary of downloading zip files.

Did you flash the program code via ISP (ICSP)? If so, and the Atmega was new and unused, did you set the fuses correctly so that the Atmega knows that it has to run with an external frequency and also selected the correct frequency? Setting the fuses also works if you first flsh the Arduino bootloader and then flash your program. because the Arduino IDE sets the fuses when the bootloader is burning. are the fuses.
and: You MUST connect a 100nf ceramic capacitor directly to the controller between VCC and GNC so that the controller runs stably.

1 Like

Sorry but a PCB needs to be presented in as an image, a jpg image.
Your CAD should be able to EXPORT a jpg image.
The file you have presented needs the CAD to open it.

A complete schematic would help.

Is there a reason to use the 328 IC rather than mount a Nano or ProMicro onto headers on your PCB. That way most of the hardwork is done and you can easily program you code.

Like in this prototype.

Thanks.. Tom... :smiley: :+1: :australia:

I've opened your schematic in Eagle v7.7.0 after suitable virus checking and it throws out some warnings - I assume because you are using a newer version. This is an image of your schematic:

Your board appeared only partially routed so I didn't upload the image of it.

1 Like

Ok Mark, So is it the same or is it better to use an internal reference? What do you mean by internal reference?
Does it have to be programmed in the sketch or by default, the micro will know.

"It doesn't work, I mean that when I load my program in the ATMega328, it doesn't respond to the signal I send it from my computer. This signal makes the program that is running in the microcontroller to exit the main loop.

I follow this steps

I make the connections and turn the Mega2560 as ISP.

I start with Arduino UNO to use as a tool for program my Atmega (with bootloader) and I follow this steps https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoToBreadboard .
But I dont know what happen. But When I load the sketch in the arduino one, this procedure gives me an error.

Im Sorry for that.

Hello DeltaFlyer The Atmega328's I have are microcontrollers with the bootloader already implemented in them.

Hi Tom, yes of course I'm with you. I also wanted to use an arduino board already implemented, the thing is that my teacher wants something from scratch and didn't want to use ready made boards. That's why I use the microcontroller.

Ok, then the fuses should actually fit.
Please try to load the simple blink sketch from the examples of the Arduino IDE onto your board. Then let it go and then try to unplug your board and connect it again. Is the blinking, Sketch still running without you having to flash it again?
Für diesen Test musst Du allerdings zwischen SKC und GND eine LED mit Vorwiderstand anschliessen. Als Vorwiderstand nimmst Du am besten 1kOhm, so kannst du trotz LED ohne Probleme flashen.

1 Like

The 328P has an internal 1.1V reference which you can use as the reference voltage for the ADC. You select the reference voltage using the analogReference() function. You have to select it in your sketch. See the documentation on the function i've linked to above.

It looks like you are using the 28-pin DIP 328P in your design. That makes it a lot easier to solder additional connections. I would solder an LED + resistor to a spare pin and then run the simple blink sketch as @Deltaflyer has suggested above.

1 Like

I therefore recommended the SKC pin for the LED because this is pin D13, i.e. the same pin that corresponds to the LED_BUILTIN in the definition for the UNO.

I found something else where someone also describes your problem exactly. Please measure once, WITHOUT the ISP programmer being connected, whether you really have a HIGH signal on the RESET PIN when the operating voltage is switched on. If R3 has no connection to + 5V or to the reset pin, this would explain the behavior of your board!
I know that R3 is absolutely correct in your circuit diagram, but maybe there is either a break in the conductor or a bad soldering point! Of course, you can also test the relevant points with a continuity test.

You say my board, so I run the sketch in my Arduino Mega and yes is works. Unplug and connect and its ok.

So I upload the sketch in to Atmega and didnt work. But the sketch its alredy inside, because i dont have any problem charging the atmega via arduino mega.

I want to clarify that still the ATMega328 is not soldered to the PCB board, in fact the PCB board is in design. The tests I am doing are on the breadboard. Because I want to make sure that everything works well and finish the PCB design with the correct connections.

Yes, I think I can see your problem even if the photo in the upper area is a bit very dark to my eyes. After you have uploaded the program 'ArduinoISP' to the Mega, you MUST attach a capacitor with at least 10 microfarads (10V or more, is ok) between RESET and GND of the MEGA. Positive connection to reset, negative to GND). Only then can you use the MEGA to bottle the Atmega 328 on the breadboard.
Without this capacitor, the Atmega cannot function faster as an ISP, because it performs a reset as soon as you want to burn a program to the target system. I can't see this capacitor in your photo. So here is the procedure again, because you have to start again at 0 to flash:

  1. Without the 10 micrifarad capacitor, upload the ArduinoISP Sketch to the MEGA.

  2. Attach 10 microfarad capacitors between RESET and GND on the MEGA.

  3. From now on you can flash the Atmega328 on the breadboard with the MEGA as ISP.
    It is important that you attach the capacitor to the reset of the MEGA2560 board, under no circumstances to the reset of the Atmega328.

If you later want to use the Mega2560 again for something other than ISP, you MUST remove the capacitor first, otherwise the Mega cannot accept a new Skech.

To test whether the flashing worked, you can use the blink sketch, even though your Atmega328 already has it, simply change the delays in the blink sketch before flashing so that you can see a clear difference in the blinking frequency.

1 Like

I just saw in your photo that on your breadboard at Pin1 = RESET of the Atmega328 there is NO 10kOhm resistor to + 5V (VCC), the resistor is essential, without this resistor the ATmega328 will not run if the ISP bottle is not connected is, I wrote to you yesterday that you should check whether this resistor is connected and the reset gets a HIGH signal if the ISP is not connected. Likewise, the 100nF capacitor is still missing directly on the controller at the VCC and GND connections. !!!! THAT is ALWAYS needed, this is a MANUFACTURER'S SPECIFICATION. It CAN work without it, but without any guarantee. And if I already have problems getting a system to work properly (ALSO ON THE BREADBOARD) then it is particularly important to rule out such sources of error.
If you don't follow my troubleshooting instructions, I can't help you get the Atmega up and running, as I assume that you will implement my troubleshooting ideas and not just say them; It doesn't work.

1 Like