Jump to content

    

Не инициализируется SD карта

Добрый день, возникла проблема.

есть 2 скетча, один сканирует карту пропуска а второй отправляет на ftp файл по отдельности они работают, но при соединении карта SD не инициализируется.

#include <Wire.h>  
#include <SD.h>
#include <NewSoftSerial.h>
#include <SoftwareSerial.h>
#include <DS3231.h>
DS3231 Clock;
bool Century=false;
char* file_name1 = "RFIDlog1.csv"; // имя файла прикрепляемого
char char_buffer;
String string_buffer = "";
int buffer_space = 1000;
const int chipSelect = 10;
NewSoftSerial mySerial(3, 2); // Считыватель RFID
NewSoftSerial mySerialgsm(6, 7); // RX, TX  GSM  (rxPin, txPin)
int counter;
byte data[14];
byte hexBlock1,hexBlock2,hexBlock3,hexBlock4,hexBlock5;
byte hexCalculatedChecksum,hexChecksum;
#define stx 2//Define the value of rfid start bit
#define etx 3//Define the value of rfid end bit
byte res;
byte msb;
byte lsb;
int val;
bool h12;
bool PM;
byte ADay, AHour, AMinute, ASecond, ABits;
bool ADy, A12h, Apm;
void setup() {
Wire.begin();
Serial.begin(19200); 
mySerial.begin(9600);
mySerialgsm.begin(19200);
Serial.println("Hi");
			   InitiSD();
}
void loop() {
int  hour;
 hour = Clock.getHour(h12, PM);
  if ( hour >= 6 && hour <= 23 )  //Запуск программы считывания карт с 6 часов утра до 23 часов и соответсвенно отправка после 23 часов
 {
  read_and_log();
 }
 else
 {
File dataFile1 = SD.open(file_name1);
if (dataFile1) {
Serial.println("Opening the file: " + String(file_name1) + " done.");
}else {
Serial.println("Error opening " + String(file_name1));
while(true);
}
Serial.println("Starting...");
gprs_modem_function ();
Serial.println("The end...");
}
}
void read_and_log (){
 if (mySerial.available() > 0) {
data[counter] = mySerial.read();
counter++;
if(counter > 13) {
  counter = 0;
  //check if start of text and end of text is correct
  if(data[0] == stx && data[13] == etx) {
	//Turn LED on pin 8 ON
	digitalWrite(8,HIGH);
	Serial.println("RFID Tag correctly received.");
	//Hex ID blocks. Two transmitted Bytes form one Hex ID block.
	//Hex ID blocks:	  6   2  |  E   3  |  0   8  |  6   C  |  E   D
	//Transmitted Bytes: 36H 32H | 45H 33H | 30H 38H | 36H 43H | 45H 44H
	hexBlock1 = AsciiCharToNum(data[1])*16 + AsciiCharToNum(data[2]);
	hexBlock2 = AsciiCharToNum(data[3])*16 + AsciiCharToNum(data[4]);
	hexBlock3 = AsciiCharToNum(data[5])*16 + AsciiCharToNum(data[6]);
	hexBlock4 = AsciiCharToNum(data[7])*16 + AsciiCharToNum(data[8]);
	hexBlock5 = AsciiCharToNum(data[9])*16 + AsciiCharToNum(data[10]);
	//Transmitted checksum.
	hexChecksum = AsciiCharToNum(data[11])*16 + AsciiCharToNum(data[12]);
	//XOR algorithm to calculate checksum of ID blocks.
	hexCalculatedChecksum = hexBlock1 ^ hexBlock2 ^ hexBlock3 ^ hexBlock4 ^ hexBlock5;
	if ( hexCalculatedChecksum == hexChecksum )
	{
	  Serial.println("Checksum OK!");
	  // gets the date and time
	//  RX8025.getRtcTime(&rtc_sec, &rtc_min, &rtc_hou, &rtc_wee, &rtc_dat, &rtc_mon, &rtc_yea);
	  //going to write it all to sd now
	  Serial.println("Will try to write data to RFIDlog.csv on SD now.");
	  // open RFIDlog.csv. 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("RFIDlog.csv", FILE_WRITE);
	  // if the file is available, write to it:
	  if (dataFile) {
		//Write the RFID Card ID
		dataFile.print("ID:");
 dataFile.print(",");
 dataFile.print(data[3], BYTE);
 dataFile.print(data[4], BYTE);
 dataFile.print(data[5], BYTE);
 dataFile.print(data[6], BYTE);
 dataFile.print(data[7], BYTE);
 dataFile.print(data[8], BYTE);
 dataFile.print(data[9], BYTE);
 dataFile.print(data[10], BYTE);
 dataFile.print(",");
 dataFile.print(" :Serial: ");
dataFile.print(data[5], BYTE);
 dataFile.print(data[6], BYTE);
 dataFile.print(",");
 dataFile.print(" :Number: ");
 dataFile.print(data[7], BYTE);
 dataFile.print(data[8], BYTE);
 dataFile.print(data[9], BYTE);
 dataFile.print(data[10], BYTE);
 dataFile.print(" ,");
 dataFile.print(" ,");
 //print date
 if (Century) {			// Won't need this for 89 years.
	dataFile.print("1");
} else {
	dataFile.print("0");
}


 dataFile.print("Date:"); 
 dataFile.print(" ,");
 dataFile.print(Clock.getYear(), DEC);
 dataFile.print("/");
 dataFile.print(Clock.getMonth(Century), DEC);
 dataFile.print("/");
 dataFile.print(Clock.getDate(), DEC);
 dataFile.print(",");

 //print time
 dataFile.print("Time:");
 dataFile.print(",");
 dataFile.print(Clock.getHour(h12, PM), DEC);
 dataFile.print(":");
 dataFile.print(Clock.getMinute(), DEC);
 dataFile.print(":");
 dataFile.print(Clock.getSecond(), DEC);
 dataFile.print(",");
 if (h12) {
	if (PM) {
		dataFile.print(" PM ");
	} else {
		dataFile.print(" AM ");
	}
} else {
	dataFile.print(" 24h ");
}

 //print temp.
 dataFile.print("Temp Deg. C");

 dataFile.print(",");
dataFile.print(Clock.getTemperature(), 2);
 dataFile.println(",");
		//close the RFIDlog.csv file
		dataFile.close();
		// print to the serial port for monitoring this line can be removed along with
		// 'void monitorout()' at the end of the script to reduce sketch size, but
		// only do this if you are sure every thing works and you DO NOT need a diag output
		// when writing the data to the SD card 
		monitorout();
		// flush newsoftserial and delay to prevent mutiple readings of same RFID tag
		delay(2000);  // По умолчанию 2500
		mySerial.flush();
		//turn led off
		digitalWrite(8,LOW);
	  } 
	  // if the file RFIDlog.csv isn't open, pop up an error:
	  else {
		Serial.println("Error opening file - RFIDlog.csv");
		return;
	  }
	}
	else {
	  Serial.println("Checksum didn't match transmitted checksum. Corrupt data!");
	  // don't do anything more:
	  return;
	}
  }
}
 }
}

uint8_t AsciiCharToNum(byte data) {
 //First substract 48 to convert the char representation
 //of a number to an actual number.
 data -= '0';
 //If it is greater than 9, we have a Hex character A-F.
 //Substract 7 to get the numeral representation.
 if (data > 9)
data -= 7;
 return data;
}



void data_file_dump () {
 File dataFile = SD.open("RFIDlog.csv");
 // if the file is available, write to it:
 if (dataFile) {
while (dataFile.available()) {
  Serial.write(dataFile.read());
}
dataFile.close();
Serial.print("Finished dumping, waiting for 2 min");
delay(120000);	//delay for 2 minutes after dumping RFIDlog.csv
 }
 // if the file isn't open, pop up an error:
 else {
Serial.println("Error opening RFIDlog.csv to dump data");
delay(2000);
 }
}

void monitorout(){
 //Print Tags ID
 Serial.print("ID:");
}

void InitiSD(){
 Serial.println("Initializing SD Card...");
 pinMode(10, OUTPUT);
 if (!SD.begin(chipSelect)) {
Serial.println("SD Card failed, or not present.");
return;
 }
 Serial.println("SD Card Ready.");
 Serial.println(" ");


}

void erase_dataFile(){
 Serial.println("Removing RFIDlog.csv...");
 SD.remove("RFIDlog.csv");
 Serial.println("RFIDlog.csv Removed");
 delay(20000);
 if (SD.exists("RFIDlog.csv")){
Serial.println("RFIDlog.csv exists.");
delay(5000);
 }
 else {
Serial.println("RFIDlog.csv doesn't exist.");
delay(5000);
 }
}


byte gprs_modem_function (){
  File dataFile1 = SD.open(file_name1);
 byte reply = 1;
 int i = 0;
 while (i < 10 && reply == 1){ //Try 10 times...
reply = sendATcommand("AT+CREG?","+CREG: 0,1","ERROR", 1000);
i++;
delay(1000);
 }
 if (reply == 0){
reply = sendATcommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\"","OK","ERROR", 1000);
if (reply == 0){
  reply = sendATcommand("AT+SAPBR=3,1,\"APN\",\"internet.mts.ru\"", "OK", "ERROR", 1000);
  if (reply == 0){
	reply = sendATcommand("AT+SAPBR=3,1,\"USER\",\"mts\"", "OK", "ERROR", 1000);
	if (reply == 0){
	  reply = sendATcommand("AT+SAPBR=3,1,\"PWD\",\"mts\"", "OK", "ERROR", 1000);
	  if (reply == 0){
		reply = 2;
		i = 0;
		while (i < 3 && reply == 2){ //Try 3 times...
		  reply = sendATcommand("AT+SAPBR=1,1", "OK", "ERROR", 10000);
		  if (reply == 2){
			sendATcommand("AT+SAPBR=0,1", "OK", "ERROR", 10000);
		  }
		  i++;
		}
		if (reply == 0){
		  reply = sendATcommand("AT+SAPBR=2,1", "OK", "ERROR", 1000);
		 if (reply == 0){
			reply = sendATcommand("AT+FTPCID=1", "OK", "ERROR", 1000);
		   if (reply == 0){
			reply = sendATcommand("AT+FTPMODE=1", "OK", "ERROR", 1000);  // Пассивный режим (1) Активный режим (0)
			 if (reply == 0){
			  reply = sendATcommand("AT+FTPSERV=\"185.28.24.13\"", "OK", "ERROR", 1000);  //сервер фтп, можно как айпи указать так и адрес типа ftp.tra-ta-ta.com
			  if (reply == 0){
				reply = sendATcommand("AT+FTPPORT=21", "OK", "ERROR", 1000);
				if (reply == 0){
				  reply = sendATcommand("AT+FTPUN=\"u21278091\"", "OK", "ERROR", 1000);  // Логин u21278091
				  if (reply == 0){
					reply = sendATcommand("AT+FTPPW=\"Simpson\"", "OK", "ERROR", 1000); // Пароль Simpson
					if (reply == 0){
					  reply = sendATcommand("AT+FTPPUTNAME=\"" + String(file_name1) + "\"", "OK", "ERROR", 1000);
					  if (reply == 0){
						reply = sendATcommand("AT+FTPPUTPATH=\"/\"", "OK", "ERROR", 1000);
						if (reply == 0){
						  unsigned int ptime = millis();
						  reply = sendATcommand("AT+FTPPUT=1", "+FTPPUT: 1,1", "+FTPPUT: 1,6", 60000);
						  Serial.println("Time: " + String(millis() - ptime));
						  if (reply == 0){
							if (dataFile1) {
							  int i = 0;
							  while (dataFile1.available()>0) {
								char_buffer = dataFile1.read();
								string_buffer.concat(char_buffer);
								i++;
								if (i == buffer_space) {
								  sendATcommand("AT+FTPPUT=2," + String(buffer_space), "AT+FTPPUT=2,10", "ERROR", 1000);
								  sendATcommand(string_buffer, "OK", "ERROR", 5000);
								  string_buffer = "";
								  i = 0;
								}
							  }
							  if (string_buffer != ""){
								sendATcommand("AT+FTPPUT=2," + String(i), "AT+FTPPUT=2,10", "ERROR", 1000);
								sendATcommand(string_buffer, "OK", "ERROR", 5000);
								sendATcommand("AT+FTPPUT=2,0", "OK", "ERROR", 1000);
							  }
							  dataFile1.close();
							}
						  }
						}
					  }
					}
				  }
				}
				}
			  }
			}
		  }
		}
	  }
	}
  }
}
 }
 return reply;
}

byte sendATcommand(String ATcommand, String answer1, String answer2, unsigned int timeout){
byte reply = 1;
 String content = "";
 char character;

 //Clean the modem input buffer
  while(mySerialgsm.available()>0) mySerialgsm.read();

 //Send the atcommand to the modem
 mySerialgsm.println(ATcommand);
 delay(100);
 unsigned int timeprevious = millis();
 while((reply == 1) && ((millis() - timeprevious) < timeout)){
while(mySerialgsm.available()>0) {
  character = mySerialgsm.read();
  content.concat(character);
  Serial.print(character);
  delay(10);
}
//Stop reading conditions
if (content.indexOf(answer1) != -1){
  reply = 0;
}else if(content.indexOf(answer2) != -1){
  reply = 2;
}else{
  //Nothing to do...
}

}
 return reply;

}

 

Arduino nano 328

SD карта подключена к CS 10 пину

 

собственно byte gprs_modem_function () отправляет на фтп

 

если закоментировать часть

 

Serial.println("Time: " + String(millis() - ptime));
                              if (reply == 0){
                                if (dataFile1) {
                                  int i = 0;
                                  while (dataFile1.available()>0) {
                                    char_buffer = dataFile1.read();
                                    string_buffer.concat(char_buffer);
                                    i++;
                                    if (i == buffer_space) {
                                      sendATcommand("AT+FTPPUT=2," + String(buffer_space), "AT+FTPPUT=2,10", "ERROR", 1000);
                                      sendATcommand(string_buffer, "OK", "ERROR", 5000);
                                      string_buffer = "";
                                      i = 0;
                                    }
                                  }
                                  if (string_buffer != ""){
                                    sendATcommand("AT+FTPPUT=2," + String(i), "AT+FTPPUT=2,10", "ERROR", 1000);
                                    sendATcommand(string_buffer, "OK", "ERROR", 5000);
                                    sendATcommand("AT+FTPPUT=2,0", "OK", "ERROR", 1000);
                                  }

то карта инициализируется... подскажите пожалуйста в чем может быть проблема

Edited by IgorKossak
[codebox] для длинного кода. [code]-для короткого!!!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this