Code Review asap

I am creating a code for a barcode system. I am using a Host USB, Clock, SD card and a scanner. The idea is to read the bar code using a scanner connected to the host USB. Then, this information should be stored on an SD card along with the date and time.

Can anyone review my code below?

  /* Program to demonstrate Data Logging/Visualisation using Arduino
 * 
 * ###Connection with SD card module###
 * Vcc->5V
 * Gnd->Gnd
 * MISO->pin 12
 * MOSI->pin 11
 * SCK-> pin 13
 * CS-> pin 4
 * 
 * ###Connection with DS3231###
 * Vcc->5V
 * Gns->Gnd
 * SCL->pin A5
 * SDA-> pin A4
 * 
 *
 * Vcc->5V
 * Gnd->Gnd
 * Out-> pin 7
 * 
 * 
 */

#include "RTClib.h"
#include <hidboot.h>
#include <usbhub.h>
#include <SPI.h>
#include <SD.h>

RTC_DS3231 rtc;



const int chipSelect = 4;
String codigoLido="";
bool leituraRealizada = false;



#include "Leitor.h"

void setup() {


  Remove_SDcard();
  Initialize_RTC();
  Serial.begin(9600);
  Serial.println("Serial begin");
  Serial.println("Iniciando USB Host Shield");
  usb();
  Initialize_SDcard();
  Serial.println("initialize end!");
  
}



void Remove_SDcard() 
{
  SD.remove("Barcode.txt");
}


void Initialize_RTC()
{
   if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
   }
   

   // Initialize the rtc object
  rtc.begin();

  // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    //rtc.adjust(DateTime(2021, 06, 30, 07, 59, 00));

//#### The following lines can be uncommented to set the date and time for the first time###  
/*
rtc.setDOW(FRIDAY);     // Set Day-of-Week to SUNDAY
rtc.setTime(18, 46, 45);     // Set the time to 12:00:00 (24hr format)
rtc.setDate(6, 30, 2017);   // Set the date to January 1st, 2014 
*/
}


void usb () {

  if (Usb.Init() == -1) {
    Serial.println("Something went wrong :( ");
    Serial.println("Check your Sketch");
  }
  delay( 200 );

  // CONFIGURA O OBJETO DO LEITOR DE CODIGO DE BARRAS
  Serial.println("Starting Barcode reading");
  HidKeyboard.SetReportParser(0, &Prs);

  Serial.println("Setup completed");
}


void Initialize_SDcard()
{
  DateTime now = rtc.now();
  
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
   // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("Barcode.txt", FILE_WRITE);
  // if the file is available, write to it:
  if (dataFile) {
    dataFile.print("Date  Time  Input "); //Write the first row of the excel file
    dataFile.print(now.day(), DEC);
    dataFile.print("/");
    dataFile.print(now.month(), DEC);
    dataFile.print("/");
    dataFile.print(now.year(), DEC); //Store date on SD card
    dataFile.print("  ");

    dataFile.print(now.hour(), DEC); //Store date on SD card
    dataFile.print(":");
    dataFile.print(now.minute(), DEC);
    dataFile.print(":");
    dataFile.print(now.second(), DEC);
    dataFile.println();
    dataFile.close();
  }
}


// ***************** FIM DO SETUP ***************************

// ***************** INÍCIO DO LOOP *************************
void loop() {
  // REALIZA A LEITURA DA PORTA USB DA SHIELD
  Usb.Task();

  // EXECUTA AS FUNÇÕES APÓS TER IDENTIFICADO UMA LEITURA COMPLETA
  if(leituraRealizada){
      
    Serial.print("Código lido: ");
    Serial.println(codigoLido);
   
    leituraRealizada = false;
    codigoLido = "";
  }

   Write_SDcard();
  //Write_PlxDaq();
  delay(1000); //Wait for 5 seconds before writing the next data 

}



void Write_SDcard() {
    // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("Barcode.txt", FILE_WRITE);
  DateTime now = rtc.now();
  Serial.begin(9600);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.print(now.day(), DEC);
    dataFile.print("/");
    dataFile.print(now.month(), DEC);
    dataFile.print("/");
    dataFile.print(now.year(), DEC); //Store date on SD card
    dataFile.print("  ");

    // Serial print
     Serial.print(now.day());
    Serial.print("/");
    Serial.print(now.month(), DEC);
    Serial.print("/");
    Serial.print(now.year(), DEC); //Store date on SD card
    Serial.print("  ");


    
    //dataFile.print(","); //Move to next column using a ","
    dataFile.print(now.hour(), DEC); //Store date on SD card
    dataFile.print(":");
    dataFile.print(now.minute(), DEC);
    dataFile.print(":");
    dataFile.print(now.second(), DEC);
    dataFile.print("  ");

    // Serial print
    Serial.print(now.hour(), DEC); //Store date on SD card
    Serial.print(":");
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    Serial.print(now.second(), DEC);
    Serial.print("  ");
    
    
    //dataFile.print(","); //Move to next column using a ","
    dataFile.print(codigoLido);
    dataFile.print("  ");
    
    //Serial print
    Serial.print(codigoLido);
    Serial.print("  ");
    Serial.println();

    dataFile.println(); //End of Row move to next row
    dataFile.close(); //Close the file
    

  }
  else
  Serial.println("OOPS!! SD card writing failed");
}


Hello
post the sketch in code tags
grafik

not sure i fully understand the code

in loop(), why is there an unconditional call to Write_SDcard()? shouldn't it only be called when something is read? and why is the delay needed. presumably Write_SDcard() returns when the write is complete.

in both Initialize_SDcard() and Write_SDcard() there is an open and a close. shouldn't there just be a single open in setup() and if it fails, enter some error loop?

usb() can also fail and if so should also enter an error loop

i suggest using sprintf to format a complete string and write the same string to both the SD and Serial interface

it's convention that only constants are Capitalized and function and variable names are not

Hi! I just updated the code... Im trying to write the string read by the scanner to the SD card:

dataFile.print(codigoLido)

Does the code work as you presented it?

If not, what does it do or not do that it shouldn’t or should?

Also, if you meant you updated the code in the original,post, don’t do that. Put the new code in a new post.

Otherwise the comments following become meaningless and can make ppl who have tried to help look like they idiots.

a7

.print() suppresses leading zeroes. Most people add the leading 0 back on minutes and seconds:

    Serial.print(":");
    if (now.minute() < 10)
      Serial.print('0');
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    if (now.second() < 10)
      Serial.print('0');

your prints can be simplified

    char s [80];
    sprintf (s, "%02d/%02d/%04d %02d:%02d:%02d, %d\n",
        now.day, now.month, now.year, now.hour, now.minute, now.second,
        ReadCode);

    dataFile.print (s)
    Serial.print (s)

still don't understand why there are multiple open/close. are stings appended after an open or do they overwrite the existing file?

The file is opened in 'write' mode. That means new lines are added at the end of the file.

so what would you need to do to overwrite the file?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.