uno r3+W5100 не переключается на SD
- Войдите на сайт для отправки комментариев
Сб, 14/06/2014 - 20:20
Пытаюсь работать с SD картой на Uno+W5100, но при подключении SD.h перестает работать web клиент.
Исходник ниже, если раскоментировать строку 10, то вызов client.connect(server, 80) просто повисает и через пару секунд программа стартует заново (reset).
Что делаю не так?
#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
//#include <EthernetServer.h>
#include <EthernetUdp.h>
#include <util.h>
#include <SPI.h>
#include <OneWire.h>
//#include <SD.h>
#define ETH_SS 10
#define SD_SS 4
//--------------- НАСТРОЙКИ ДЛЯ Ethernet -------------------//
// MAC-адрес нашего устройства
byte mac[] = { 0x00, 0x3A, 0xF1, 0x19, 0x69, 0xFC };
// ip-адрес устройства
//byte ip[] = { 192, 168, 1, 156 };
// ip-адрес удалённого сервера
//char server[] = {193,106,92,203}; // name address
char server[] = "www.rn3aig.ru"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 156);
// Создаем класс для работы по Ethernet
EthernetClient client;
//--------------- НАСТРОЙКИ ДЛЯ 1Wire -------------------//
// DS18S20 Temperature chip i/o
OneWire ds(7); // on pin 7
//--------------- НАСТРОЙКИ ДЛЯ NTP -------------------//
unsigned int localPort = 8888; // Порт для прослушки UDP - пакетов
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov NTP сервер
const int NTP_PACKET_SIZE= 48;
byte packetBuffer[ NTP_PACKET_SIZE];
EthernetUDP Udp;
unsigned long sendNTPpacket(IPAddress& address)
{ // отправляем запрос на NTP сервер и получаем ответ
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0b11100011;
packetBuffer[1] = 0;
packetBuffer[2] = 6;
packetBuffer[3] = 0xEC;
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
Udp.beginPacket(address, 123);
Udp.write(packetBuffer,NTP_PACKET_SIZE);
Udp.endPacket();
}
void setup()
{
pinMode(ETH_SS, OUTPUT);
digitalWrite(ETH_SS, HIGH);
//SD.begin(SD_SS);
digitalWrite(SD_SS, HIGH);
digitalWrite(ETH_SS, LOW);
Serial.begin(9600); // Скорость консольного порта 9600 (пригодится для отладки)
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
Serial.print("My IP address: ");
Serial.println(Ethernet.localIP());
Serial.print("My subnetMask: ");
Serial.println(Ethernet.subnetMask());
Serial.print("My gatewayIP: ");
Serial.println(Ethernet.gatewayIP());
Serial.print("My dnsServerIP: ");
Serial.println(Ethernet.dnsServerIP());
// give the Ethernet shield a second to initialize:
delay(1000);
}
void loop()
{
byte i;
byte present = 0;
byte data[12];
byte addr[8];
Serial.print("PIN10=");
Serial.println(digitalRead(10),DEC);
Serial.print("PIN4=");
Serial.println(digitalRead(4),DEC);
Serial.print("PIN53=");
Serial.println(digitalRead(53),DEC);
Serial.print("DDRB=");
Serial.println(DDRB,DEC);
Serial.print("DDRD=");
Serial.println(DDRD,DEC);
//--------------- ИЩЕМ ДАТЧИКИ НА ЛИНИИ 1WIRE И ЧИТАЕМ ИХ ТЕМПЕРАТУРУ-------------------//
if ( !ds.search(addr)) {
Serial.print("No more addresses.\n");
ds.reset_search();
return;
}
Serial.print("R=");
for( i = 0; i < 8; i++) {
Serial.print(addr[i], HEX);
Serial.print(" ");
}
if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial.print("CRC is not valid!\n");
return;
}
if ( addr[0] == 0x10) {
Serial.print("Device is a DS18S20 family device.\n");
}
else if ( addr[0] == 0x28) {
Serial.print("Device is a DS18B20 family device.\n");
}
else {
Serial.print("Device family is not recognized: 0x");
Serial.println(addr[0],HEX);
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
delay(1000); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
Serial.print("P=");
Serial.print(present,HEX);
Serial.print(" ");
for ( i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.print(" CRC=");
Serial.print( OneWire::crc8( data, 8), HEX);
Serial.println();
int HighByte, LowByte, TReading, SignBit, Tc_100, Whole, Fract;
char buf[100];
LowByte = data[0];
HighByte = data[1];
TReading = (HighByte << 8) + LowByte;
SignBit = TReading & 0x8000; // test most sig bit
if (SignBit) // negative
{
TReading = (TReading ^ 0xffff) + 1; // 2's comp
}
Tc_100 = (6 * TReading) + TReading / 4; // multiply by (100 * 0.0625) or 6.25
Whole = Tc_100 / 100; // separate off the whole and fractional portions
Fract = Tc_100 % 100;
if (SignBit) // If its negative
{
Serial.print("-");
}
Serial.print(Whole);
Serial.print(".");
if (Fract < 10)
{
Serial.print("0");
}
Serial.print(Fract);
Serial.print("\n");
//--------------- РАССЧИТЫВАЕМ ТОЧНОЕ ВРЕМЯ ПО NTP-------------------//
unsigned long epoch;
Udp.begin(localPort);
sendNTPpacket(timeServer); // send an NTP packet to a time server
delay(1000);
if (Udp.parsePacket() ) {
Udp.read(packetBuffer,NTP_PACKET_SIZE);
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// конвертируем время
Serial.print("Unix time = ");
const unsigned long seventyYears = 2208988800UL;
epoch = secsSince1900 - seventyYears;
Serial.println(epoch);
Serial.print("The UTC time is ");
Serial.print((epoch % 86400L) / 3600);
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
Serial.print('0');
}
Serial.print((epoch % 3600) / 60);
Serial.print(':');
if ( (epoch % 60) < 10 ) {
Serial.print('0');
}
Serial.println(epoch %60);
}
Udp.stop();
//--------------- END NTP-------------------//
sprintf(buf, "GET /save.php?temp=%c%0d.%d&utime=%lu&id=%02X%02X%02X%02X%02X%02X%02X%02X HTTP/1.0",SignBit ? '-' : '+',Whole,Fract,epoch,addr[0],addr[1],addr[2],addr[3],addr[4],addr[5],addr[6],addr[7]);
Serial.println(buf);
delay(100);
//--------------- ОТПРАВЛЯЕМ НА СЕРВЕР ПОЛУЧЕНЫЕ ДАННЫЕ (ДАТУ-ВРЕМЯ,ТЕМПЕРАТУРУ -------------------//
Serial.println("connecting..."); // Serial.println для отладки. Лучше его оставить, на всякий случай, потом будет легче понять, в чём проблема.
if (client.connect(server, 80)) {
delay(100);
Serial.println("connected");
Serial.println("sending reqest...");
client.println(buf); // Отправляем GET запрос
client.println("Host: www.rn3aig.ru");
client.println("Connection: close");
client.println();
delay(100);
Serial.println("reading responce...");
while (client.available()) {
char c = client.read(); // Читаем, что нам ответил Web-сервер
Serial.print(c);
}
Serial.println();
Serial.println("disconnecting.");
client.stop(); // Завершаем соединение
} else {
Serial.println("connection failed");
}
//--------------- END LOOP -------------------//
delay(3000); // задержка в 10 сек.
}
Нормальный спул в терминал, когда все работает:
My IP address: 192.168.1.102 My subnetMask: 255.255.255.0 My gatewayIP: 192.168.1.1 My dnsServerIP: 192.168.1.1 PIN10=1 PIN4=0 PIN53=0 DDRB=44 DDRD=0 R=28 11 F7 34 3 0 0 27 Device is a DS18B20 family device. P=1 A2 1 4B 46 7F FF E 10 D8 CRC=D8 26.12 Seconds since Jan 1 1900 = 3611751326 Unix time = 1402762526 The UTC time is 16:15:26 GET /save.php?temp=+26.12&utime=1402762526&id=2811F73403000027 HTTP/1.0 connecting... connected sending reqest... reading responce... HTTP/1.1 200 OK Server: nginx/0.8.55 Date: Sat, 14 Jun 2014 16:15:29 GMT Content-Type: text/html; charset=UTF-8 Connection: close X-Powered-By: PHP/5.2.17 Content-Length: 2 OK disconnecting. PIN10=1 PIN4=0 PIN53=0 DDRB=44 DDRD=0 R=28 4B 21 35 3 0 0 8B Device is a DS18B20 family device. P=1 A5 1 4B 46 7F FF B 10 F7 CRC=F7 26.31 Seconds since Jan 1 1900 = 3611751331 Unix time = 1402762531 The UTC time is 16:15:31 GET /save.php?temp=+26.31&utime=1402762531&id=284B21350300008B HTTP/1.0 connecting... connected sending reqest... reading responce... HTTP/1.1 200 OK Server: nginx/0.8.55 Date: Sat, 14 Jun 2014 16:15:34 GMT Content-Type: text/html; charset=UTF-8 Connection: close X-Powered-By: PHP/5.2.17 Content-Length: 2 OK disconnecting. PIN10=1 PIN4=0 PIN53=0 DDRB=44 DDRD=0 No more addresses.
Когда все подвисает:
My IP address: 192.168.1.102 My subnetMask: 255.255.255.0 My gatewayIP: 192.168.1.1 My dnsServerIP: 192.168.1.1 PIN10=1 PIN4=0 PIN53=0 DDRB=44 DDRD=0 R=28 11 F7 34 3 0 0 27 Device is a DS18B20 family device. P=1 A5 1 4B 46 7F FF B 10 F7 CRC=F7 26.31 Seconds since Jan 1 1900 = 3611751579 Unix time = 1402762779 The UTC time is 16:19:39 GET /save.php?temp=+26.31&utime=1402762779&id=2811F73403000027 HTTP/1.0 conn
Вот этот топик читал, это не помогло http://arduino.ru/forum/programmirovanie/ethernet-shield-c-sd-kartoi-ne-pishet-na-kartu
присоединяюсь к предыдущим ораторам.
http://arduino.ru/forum/obshchii/dostup-k-sd-karte-s-udalennogo-arduino#comment-69401
вот мой надежный подход
в который раз уже делаете мне смешно... попробуйте почитать как это работает.. даю на водку.. SPI... шина такая... почитайте как она работает и вам сразу таки станет понятно как заставить работать кучу устройств на ней висящих
мне поворачиватся фото за спиной ральных серваков делать?
ага, повернись к лесу передом и к нам задом и чуть чуть нагнись... :)
а то чушь, которую ты порешь, уже устала повизгивать...
И не приставай ко мне с безполезным тормозом SPI
тихо отполз в угол... ржунемогу... иди учи матчасть, потом побеседуем... а то набор никак не связаных слов, без знаков припинания вообще лень читать.
Вернемся ка к вопросу топика....
Переключение между SD и Ethernet у меня не получается, какие будут предложения ?
Попробовал, теперь инициализация проходит успешно, но работа с SD виснет или перезагружает arduino.
Логика работы устройства должна быть следующей:
1. замерить показания всех ds18b20
2. передать показания на web-сервер
3. если до сервера не достучались, то скидываем показания в файл на SD.
Для тестирования, все три действия сейчас делаются последовательно и показания с ds18b20 не снимаются. SD карту предварительно отформатировал под fat16.
Скетч:
#include <Dhcp.h> //#include <Dns.h> #include <Ethernet.h> //#include <EthernetClient.h> //#include <EthernetServer.h> #include <EthernetUdp.h> #include <util.h> #include <SPI.h> #include <OneWire.h> #include <SD.h> //--------------- НАСТРОЙКИ ДЛЯ Ethernet -------------------// // MAC-адрес нашего устройства byte mac[] = { 0x00, 0x3A, 0xF1, 0x19, 0x69, 0xFC }; // ip-адрес устройства //byte ip[] = { 192, 168, 1, 156 }; // ip-адрес удалённого сервера //char server[] = {193,106,92,203}; // name address char server[] = "www.rn3aig.ru"; // name address for Google (using DNS) // Set the static IP address to use if the DHCP fails to assign IPAddress ip(192, 168, 1, 156); // Создаем класс для работы по Ethernet EthernetClient client; File myFile; // change this to match your SD shield or module; // Arduino Ethernet shield: pin 4 // Adafruit SD shields and modules: pin 10 // Sparkfun SD shield: pin 8 const int chipSelect = 4; void DDR_status_print(void){ Serial.print("PIN10="); Serial.println(digitalRead(10),DEC); Serial.print("PIN4="); Serial.println(digitalRead(4),DEC); Serial.print("PIN53="); Serial.println(digitalRead(53),DEC); Serial.print("DDRB="); Serial.println(DDRB,DEC); Serial.print("DDRD="); Serial.println(DDRD,DEC); } void setup() { Serial.begin(9600); // Скорость консольного порта 9600 (пригодится для отладки) DDR_status_print(); // disable Ethernet / init SD pinMode(10, OUTPUT); digitalWrite(10, HIGH); Serial.print("Initializing SD card..."); // On the Ethernet Shield, CS is pin 4. It's set as an output by default. // Note that even if it's not used as the CS pin, the hardware SS pin // (10 on most Arduino boards, 53 on the Mega) must be left as an output // or the SD library functions will not work. if (!SD.begin(4)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); Serial.print("Initializing Ethernet..."); // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: // try to congifure using IP address instead of DHCP: Serial.println("Initializing Ethernet direct..."); Ethernet.begin(mac, ip); }else{ Serial.println("initialization done."); } Serial.print("My IP address: "); Serial.println(Ethernet.localIP()); Serial.print("My subnetMask: "); Serial.println(Ethernet.subnetMask()); Serial.print("My gatewayIP: "); Serial.println(Ethernet.gatewayIP()); Serial.print("My dnsServerIP: "); Serial.println(Ethernet.dnsServerIP()); // give the Ethernet shield a second to initialize: delay(1000); } void loop() { byte i; byte present = 0; byte data[12]; byte addr[8]; char buf[100]; sprintf(buf, "GET /save.php?temp=+26.31&utime=1402762531&id=284B21350300008B HTTP/1.0"); Serial.println(buf); delay(100); //--------------- ОТПРАВЛЯЕМ НА СЕРВЕР ПОЛУЧЕНЫЕ ДАННЫЕ (ДАТУ-ВРЕМЯ,ТЕМПЕРАТУРУ -------------------// Serial.println("connecting..."); // Serial.println для отладки. Лучше его оставить, на всякий случай, потом будет легче понять, в чём проблема. if (client.connect(server, 80)) { delay(100); Serial.println("connected"); Serial.println("sending reqest..."); client.println(buf); // Отправляем GET запрос client.println("Host: www.rn3aig.ru"); client.println("Connection: close"); client.println(); delay(100); Serial.println("reading responce..."); while (client.available()) { char c = client.read(); // Читаем, что нам ответил Web-сервер Serial.print(c); } Serial.println(); Serial.println("disconnecting."); client.stop(); // Завершаем соединение } else { Serial.println("connection failed"); } delay(1000); Serial.println("save data to SD card"); // disable Ethernet / init SD //pinMode(10, OUTPUT); //digitalWrite(10, HIGH); Serial.println("disable Ethernet / init SD"); // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. myFile = SD.open("data.txt", FILE_WRITE); Serial.println("file opened"); // if the file opened okay, write to it: if (myFile) { Serial.print("Writing to data file..."); myFile.println("1"); // close the file: myFile.close(); Serial.println("done."); } else { // if the file didn't open, print an error: Serial.println("error opening data file"); } //--------------- END LOOP -------------------// delay(3000); // задержка в 10 сек. }При этом скетче, arduino выдает в отладку вот так и циклически перезагружается:
Если раскоментировать строки 125 и 126 то лучше не становиться.
Что посоветуете?
i need help!
Возможно это важно, но установлен тдельно winavr в отдельную папку для программирования с avr studio.
Прошу помощи, на карту так и не получилось писать.
Прошу помощи, на карту так и не получилось писать.
попробуйте отойти за угол. что бы ветер не так задувал и писать там.. должно получиться.
но таки повторю еще раз.. почитайте что такое SPI. как он работает и почему нужно заканчивать общаться с одним устройством. прежде чем начать работать с с другим.. без этого вы врятли поймете почему не писаеться
Прошу помощи, на карту так и не получилось писать.
попробуйте отойти за угол. что бы ветер не так задувал и писать там.. должно получиться.
но таки повторю еще раз.. почитайте что такое SPI. как он работает и почему нужно заканчивать общаться с одним устройством. прежде чем начать работать с с другим.. без этого вы врятли поймете почему не писаеться
С этим интерфейсом я знаком. Само собой пробовал менять Slave Select pin при работе с SD на с Ethernet как написано у производителя но это не помогло:
digitalWrite(10, HIGH); // ethernet on
digitalWrite(4, HIGH); // SD on
Самое печальное что много примеров для web сервера, а для клиента совсем мало и они не работают.
Если поделитесь примером, буду признателен.
Добился работоспособности SD И Ethernet, похоже в библиотеке SD, SS не подтягивается в земле, а в Ethernet это делается.
#include <Dhcp.h> //#include <Dns.h> #include <Ethernet.h> //#include <EthernetClient.h> //#include <EthernetServer.h> #include <EthernetUdp.h> #include <util.h> #include <SPI.h> #include <OneWire.h> #include <SD.h> #define SWITCH_TO_W5100 digitalWrite(4,HIGH); digitalWrite(10,LOW) #define SWITCH_TO_SD digitalWrite(10,HIGH); digitalWrite(4,LOW) #define ALL_OFF digitalWrite(10,HIGH); digitalWrite(4,HIGH) //--------------- НАСТРОЙКИ ДЛЯ Ethernet -------------------// // MAC-адрес нашего устройства byte mac[] = { 0x00, 0x3A, 0xF1, 0x19, 0x69, 0xFC }; // ip-адрес устройства //byte ip[] = { 192, 168, 1, 156 }; // ip-адрес удалённого сервера //char server[] = {193,106,92,203}; // name address char server[] = "www.rn3aig.ru"; // name address for Google (using DNS) // Set the static IP address to use if the DHCP fails to assign IPAddress ip(192, 168, 1, 156); // Создаем класс для работы по Ethernet EthernetClient client; // Создаем класс для работы с SD File myFile; // change this to match your SD shield or module; // Arduino Ethernet shield: pin 4 // Adafruit SD shields and modules: pin 10 // Sparkfun SD shield: pin 8 const int chipSelect = 4; void DDR_status_print(void){ Serial.print("PIN10="); Serial.println(digitalRead(10),DEC); Serial.print("PIN4="); Serial.println(digitalRead(4),DEC); Serial.print("PIN53="); Serial.println(digitalRead(53),DEC); Serial.print("DDRB="); Serial.println(DDRB,DEC); Serial.print("DDRD="); Serial.println(DDRD,DEC); } void setup() { Serial.begin(9600); // Скорость консольного порта 9600 (пригодится для отладки) //DDR_status_print(); SWITCH_TO_SD; pinMode(4, OUTPUT); pinMode(10, OUTPUT); Serial.print("Initializing SD card..."); // On the Ethernet Shield, CS is pin 4. It's set as an output by default. // Note that even if it's not used as the CS pin, the hardware SS pin // (10 on most Arduino boards, 53 on the Mega) must be left as an output // or the SD library functions will not work. if (!SD.begin(chipSelect)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); pinMode(4, OUTPUT); pinMode(10, OUTPUT); SWITCH_TO_W5100; Serial.print("Initializing Ethernet..."); // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: // try to congifure using IP address instead of DHCP: Serial.println("Initializing Ethernet direct..."); Ethernet.begin(mac, ip); }else{ Serial.println("initialization done."); } /* Serial.print("My IP address: "); Serial.println(Ethernet.localIP()); Serial.print("My subnetMask: "); Serial.println(Ethernet.subnetMask()); Serial.print("My gatewayIP: "); Serial.println(Ethernet.gatewayIP()); Serial.print("My dnsServerIP: "); Serial.println(Ethernet.dnsServerIP()); // give the Ethernet shield a second to initialize: delay(1000); */ ALL_OFF; } void loop() { byte i; byte present = 0; byte data[12]; byte addr[8]; char buf[100]; sprintf(buf, "GET /save.php?temp=+26.31&utime=1402762531&id=284B21350300008B HTTP/1.0"); Serial.println(buf); delay(100); //--------------- ОТПРАВЛЯЕМ НА СЕРВЕР ПОЛУЧЕНЫЕ ДАННЫЕ (ДАТУ-ВРЕМЯ,ТЕМПЕРАТУРУ -------------------// //SWITCH_TO_W5100; client.connect(server, 80); Serial.println("connecting..."); // Serial.println для отладки. Лучше его оставить, на всякий случай, потом будет легче понять, в чём проблема. if (client) { delay(100); Serial.println("connected"); Serial.println("sending reqest..."); client.println(buf); // Отправляем GET запрос client.println("Host: www.rn3aig.ru"); client.println("Connection: close"); client.println(); delay(100); Serial.println("reading responce..."); while (client.available()) { char c = client.read(); // Читаем, что нам ответил Web-сервер Serial.print(c); } Serial.println(); Serial.println("disconnecting."); client.stop(); // Завершаем соединение } else { Serial.println("connection failed"); client.stop(); // Завершаем соединение } //--------------- ЗАКОНЧИЛИ ОТПРАВЛЯТЬ НА СЕРВЕР ПОЛУЧЕНЫЕ ДАННЫЕ (ДАТУ-ВРЕМЯ,ТЕМПЕРАТУРУ -------------------// //----------------ПИШЕМ НА SD КАРТУ ---------------------------------------------------------------// delay(1000); Serial.println("SD work start"); SWITCH_TO_SD; /* if (SD.exists("log.txt")) { Serial.println("file exists."); } else { Serial.println("file doesn't exist."); } */ myFile = SD.open("log.txt", FILE_WRITE); Serial.println("file opened"); // if the file opened okay, write to it: if (myFile) { Serial.println("Writing to data file..."); myFile.println("1"); // close the file: myFile.close(); Serial.println("done. SD work end."); } else { // if the file didn't open, print an error: Serial.println("error opening data file."); myFile.close(); Serial.println("SD work end."); } //---------------- НЕ ПИШЕМ НА SD КАРТУ ---------------------------------------------------------------// delay(3000); // задержка в 10 сек. }Теперь проблема с подключении возможности по NTP синхронизации времени, как только добавляю:
То сразу перестает работать клиент Ethernet и виснет на этом: