GithubHelp home page GithubHelp logo

Comments (78)

Tyill avatar Tyill commented on June 2, 2024

Здравствуйте.

MsTimer2::set(SV_CYCLEREC_MS, thrProc);
MsTimer2::start();

заменить на

Timer0.attachInterrupt(thrProc).start(SV_CYCLEREC_MS);

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Спасибо, заменил. Теперь скетч загружается успешно. Но модуль в SVMonitor не появляется.
Может быть, ещё что-то нужно изменить при использовании другого таймера?

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Да вроде ничего больше не надо.
Попробуйте поотлаживать так: напишите в функцию thrProc где-нидь Serial.print("Hello"), и запустите в Arduino IDE, то есть без подключения к SVMonitor. Тем самым проверите что функция отправки данных вызывается внутри по таймеру.
Потом можно дальше копать.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Не работает.
Capture
Хотя я не уверен, что написал правильно.

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Правильно все.
Значит надо разбираться с DueTimer.

Попробуйте Timer1 сделать:
Timer1.attachInterrupt(thrProc).start(SV_CYCLEREC_MS);

Вот здесь у него есть примеры, посмотрите:
https://github.com/ivanseidel/DueTimer/tree/master/examples

В интернете еще поищите примеры с DueTimer.

from svisual.

Tyill avatar Tyill commented on June 2, 2024

А. Нет. Неправильно.

Функция thrProc - это моя ф-я.

Ее на править в https://github.com/Tyill/SVisual/blob/master/src/SVArduino/sv_client.cpp#L88

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Попробовал Timer1 – ни чего не изменилось. А вот дальше:

Если
1
То
1+

А если
2
То
2+

Может быть, МИЛЛИсекунды в MsTimer2 и МИКРОсекунды в DueTimer?

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Да, точно, там микросекунды:
To call a function handler every 1000 microseconds:

Сделайте так тогда:
Timer1.attachInterrupt(thrProc).start(SV_CYCLEREC_MS * 1000);

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Сделал: "Timer1.attachInterrupt(thrProc).start(SV_CYCLEREC_MS * 1000);".
В мониторе порта "Hello" печатает, но в SVMonitor модуль не появляется.
Где-то что-то ещё не так.

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Проверьте еще раз как сейчас выглядит ф-я thrProc, когда вы работаете с SVMonitor.
Должна выглядеть так:

void thrProc (){
   objCln.doSendCycle();
}

То есть без всяких Serial.print(...), которые вы добавляли для проверки.

Можете файлы мне отправить, которые вы поменяли в SVArduino, я их посмотрю еще.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Да, вот папка из c:\Program Files (x86)\Arduino\libraries\

SVArduino.zip

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Все правильно вроде. Должно работать все.

Можете попробовать в ArduinoIDE запустить, то есть без подключения к SVMonitor,
в Serial.print(...) ничего не надо писать.

Программа тестовая:

void setup() {

	bool ok = svisual::connectOfCOM("test");

}
int cnt = 0;
void loop() {

	svisual::addIntValue("dfv", cnt);

	++cnt;
	if (cnt > 10) cnt = 0;

	bool odd_cnt = cnt % 2;

    svisual::addBoolValue("bFW", odd_cnt);

    svisual::addBoolValue("bBW", !odd_cnt);

	delay(200);
}

Посмотрите монитора порта в ArduinoIDE, должен показывать данные.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

В мониторе порта ArduinoIDE только "=".

test

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Тоже самое сделайте, только с MsTimer, то есть обратно на MsTimer верните как было.
Посмотрим.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

К сожалению MsTimer2 не работает с AVR контроллером.
MsTimer2
#error Unsupported CPU type
#error MsTimer2 library only works on AVR architecture

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

То есть наоборот работает только с AVR, а Due ARM.

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Ладно тогда с этим MsTimer.

Я помню что писал в монитор, когда данные передавал.
Сейчас значит ничего не пишет.
Дальше надо значит отладочные сообщения писать в каждую функцию, которая должна вызываться, таким образом:

void thrProc(){
   Serial.print("thrProc")


void sv_client::doSendCyc(){
    Serial.print("sv_client::doSendCyc")


bool sv_client::sendData(){
   Serial.print("sv_client::sendData")

bool sv_client::sendDataOfCom(){
   Serial.print("sv_client::sendDataOfCom")

То есть надо понять где затык, потом из-за чего.

И запускать все это дело из под ArduinoIDE, то есть SVMonitor не подключать.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Отладочные сообщения добавил в функции. В результате в мониторе:
thrProcsv_client::doSendCycthrProcsv_client::doSendCycthrProcsv_client::doSendCycthrProcsv_client::doSendCycthrProcsv_client::doSendCycthrProcsv_client::doSendCycthrProcsv_client::doSendCycthrProcsv_client::doSendCycthrProcsv_client::doSendCyct
monitor

from svisual.

Tyill avatar Tyill commented on June 2, 2024

вот видите, нет sv_client::sendData().

Уберите все отладоч сообщения, чтобы не мешали.
Дальше ставьте отладочные сообщения в ф-ии sv_client::doSendCyc(), например здесь:

 void sv_client::doSendCyc(){
	   
	  // connection support
	  if (!isConnect_)
		  isConnect_ = tcpConnect();
	
Serial.print("isConnect = ");Serial.print(isConnect); Serial.print("\n");

	  // check active value in current cycle
	  int prevCyc = curCycCnt_ - 1; if (prevCyc < 0) prevCyc = SV_PACKETSZ - 1;
	  int sz = values_.size(); valueRec* vr;
	  for (int i = 0; i < sz; ++i){

		  vr = (valueRec*)values_.at(i);

		  if (!vr->isActive){
			  vr->vals[curCycCnt_] = vr->vals[prevCyc];

			  if ((vr->type == valueType::tBool) && vr->isOnlyFront)
				  vr->vals[curCycCnt_].tBool = false;
		  }

		  vr->isActive = false;
	  }

	  int next = curCycCnt_ + 1;
 
Serial.print("next = "); Serial.print(next); Serial.print("\n");

	  // send data
	  if (next >= SV_PACKETSZ) {

Serial.print("beforeSendData"); Serial.print("\n");

		  isConnect_ = (isConnect_) ? sendData() : false;

		  curCycCnt_ = 0;
	  }
	  else 
		  ++curCycCnt_; 
	 
	}


from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Поскольку "sv_client.cpp:339:44: error: 'isConnect' was not declared in this scope",
Заменил "Serial.print("isConnect = ");Serial.print(isConnect); Serial.print("\n");"
на "Serial.print("isConnect_ = ");Serial.print(isConnect_); Serial.print("\n");".
В результате:
isConnect

from svisual.

Tyill avatar Tyill commented on June 2, 2024

После "Serial.print("next = "); Serial.print(next); Serial.print("\n");"
напишите еще:
Serial.print("SV_PACKETSZ= "); Serial.print(SV_PACKETSZ); Serial.print("\n");

Дальше. Сюда поставьте запись:

  bool sv_client::sendData(){
      Serial.print("sendData");
    bool ok = isCom_ ? sendDataOfCom() : sendDataOfEthernet();
      
	return ok; 
  }

И сюда:

bool sv_client::sendDataOfCom(){
      Serial.print("sv_client::sendDataOfCom");


}

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Добавил записи, может быть, посмотрите файл, насколько правильно.

sv_client.zip

Capture

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Да все правильно. Дальше то что пишет после "next = 9"?
Вы понимаете что мы делаем?

Мы пытаемся понять, почему не заходит в функцию sendDataOfCom, соответственно не передает данные.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Дальше то что пишет после "next = 9"?

На этом останавливается.

Вы понимаете что мы делаем?

Пытаюсь вникнуть, но без Вашей помощи я с этим не разберусь.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Должно быть так:

isConnect_ = 1
next = 9
SV_PACKETSZ= 10
isConnect_ = 1
next = 10
SV_PACKETSZ= 10
beforeSendData
sendDatasv_client::sendDataOfCom=begin=

Но останавливается на:

isConnect_ = 1
next = 9
SV_PACKETSZ= 10
i

По аналогии с тестом "Hello", когда печатает только первые две буквы "He" и останавливается.
Может с этим таймером нужно как-то по-другому?..

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Давайте еще одну вещь проверим, сделайте так:

void sv_client::doSendCyc(){
	   
         Serial.print("sv_client::doSendCyc\n");

         return ;   

	  // connection support
	  if (!isConnect_)
	  .
          .
          .
}

Подсчитаем сколько раз выведет "sv_client::doSendCyc" прежде чем заткнется.
Если заткнется, значит таймер считает только до 10, хотя не должен так работать.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Не затыкается. Что-то другое.

Capture

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Замените:

// send data
	  if (next >= SV_PACKETSZ) {

Serial.print("beforeSendData"); Serial.print("\n");

		  isConnect_ = (isConnect_) ? sendData() : false;

		  curCycCnt_ = 0;
	  }
	  else 
		  ++curCycCnt_; 

на

// send data
	  if (next >= SV_PACKETSZ) {

Serial.print("beforeSendData"); Serial.print("\n");

		 if (isCom_)
                     sendDataOfCom();
                 else 
                     sendDataOfEthernet();

		  curCycCnt_ = 0;
	  }
	  else 
		  ++curCycCnt_; 

Дальше здесь, закомментируйте "Serial.flush();":

bool sv_client::sendDataOfCom(){

Serial.print("sv_client::sendDataOfCom");
      
	int sz = values_.size();
	
	if (sz == 0) return true;
	
	//Serial.flush();
		
	const char* start = "=begin=";
.
.
.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Вот что получается:
Capture

sv_client.zip

from svisual.

Tyill avatar Tyill commented on June 2, 2024

вы это уберите, иначе не идет дальше:

void sv_client::doSendCyc(){
	   
         //Serial.print("sv_client::doSendCyc\n");

         //return ;   

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Убрал.

Capture

from svisual.

Tyill avatar Tyill commented on June 2, 2024

покажите файл sv_client.cpp

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

sv_client.zip

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip
пробуйте. что напишет - сюда.

Тяжелый случай какой-то. Мне пока кажется, что в размерности типов проблема, там есть места где я подразумеваю размеры, а надо было sizeof писать. Ну это ладно пока, смотрим дальше.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Вот что получается:

monitor

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

идем дальше. что напишет - сюда.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Сейчас:
2

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

дальше. что напишет - сюда.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Не пишет, только "=".
К сожалению, не было возможности проверить раньше.

Capture

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

дальше.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

test

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

дальше.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Capture

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Замените

  bool sv_client::connectOfCOM(const char* moduleName, int speed){
  		
.
.
.
		Serial.begin(speed);   ->  Serial3.begin(speed); 

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Если не пойдет еще так попробуйте:

bool sv_client::connectOfCOM(const char* moduleName, int speed){
  		
.
.
.
		Serial.begin(speed); 
                SerialUSB.begin(speed); 

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Первый вариант – ошибка компиляции.
А второй однократно печатает "=".
sv_client.zip

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

пробуйте так.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

То же самое, только "=".

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

еще раз.

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

поправил. предыд-й с ошибкой.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Не получается:

\sv_client.cpp:311:35: error: no matching function for call to 'UARTClass::write(svisual::valueType&, int)'
Serial.write(data->type, 4);

\sv_client.cpp:316:47: error: call of overloaded 'write(int&, int)' is ambiguous
Serial.write(data->vals[j].tInt, 4);

\sv_client.cpp:318:49: error: no matching function for call to 'UARTClass::write(float&, int)'
Serial.write(data->vals[j].tFloat, 4);

\sv_client.cpp:325:12: error: 'pAuxSD' was not declared in this scope
delete pAuxSD;

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

так.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Эти ошибки остались:

\sv_client.cpp:311:35: error: no matching function for call to 'UARTClass::write(svisual::valueType&, int)'
Serial.write(data->type, 4);

\sv_client.cpp:316:47: error: call of overloaded 'write(int&, int)' is ambiguous
Serial.write(data->vals[j].tInt, 4);

\sv_client.cpp:318:49: error: no matching function for call to 'UARTClass::write(float&, int)'
Serial.write(data->vals[j].tFloat, 4);

from svisual.

Tyill avatar Tyill commented on June 2, 2024

sv_client.zip

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

То же самое: "=".

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Только: "=".

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Попробуйте увеличить размер внутреннего буфера, подробнее о нем тут
http://mypractic-forum.ru/viewtopic.php?t=11

поставьте 256 байт:
#define SERIAL_TX_BUFFER_SIZE 256
#define SERIAL_RX_BUFFER_SIZE 256

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Поставил 256.
256
HardwareSerial.zip
sv_client.zip

4

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Не могу оценить, насколько это проще, но может быть попробовать подойти с другой стороны, адаптировать DueTimer к SVMonitor?

from svisual.

Tyill avatar Tyill commented on June 2, 2024

DueTimer не причем.
Здесь я думаю буфер переполняется (в который Serial.write пишет перед физической отправкой).

Попробуйте, еще пример сократить, только 1 переменную записывать:

#include <SVClient.h>
void setup() {

	bool ok = svisual::connectOfCOM("test");

}
int cnt = 0;
void loop() {

	svisual::addIntValue("dfv", cnt);

	++cnt;
	if (cnt > 10) cnt = 0;

	bool odd_cnt = cnt % 2;
 
	delay(200);
}

from svisual.

Tyill avatar Tyill commented on June 2, 2024

.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

С одной переменной заработало.

monitor

SVM

from svisual.

Tyill avatar Tyill commented on June 2, 2024

ну вот и хорошо.
попробуйте буфер увеличить еще до 1024. И 3 переменные как в исходном примере записать.
(чтобы точно убедится что в нем дело)

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Буфер увеличил, так как на скриншоте.
BS

С тремя не работает, с двумя тоже.
3
2

from svisual.

Tyill avatar Tyill commented on June 2, 2024

значит не в буфере дело, да и настройки общие поди для всех мк.
обратно верните настройки по буферу, которые были (выше скрин был с ними).

Такой вопрос, вы когда грузите скетч, он же пишет сколько памяти осталось в мк.
Посмотрите, может впритык. Скрин сделайте.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Настройки буфера вернул, память использует только 6%.

6

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Может быть дело в разной разрядности Mega и Due?
99

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Посмотрите сколько напишет:

void setup() {

}
void loop() {

    Serial.print("int sz "); Serial.print(sizeof(int)); Serial.print("\n");
    Serial.print("long int sz "); Serial.print(sizeof(long int)); Serial.print("\n");
delay(200);

}

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Пишет четыре.

4

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Посмотрел еще раз код.
Ну, не вижу где это (int32) могло повлиять. Везде правильно указываю размеры, когда вызываю Serial.write.

Так. Давайте попробуем отказаться от DuoTimer. Вручную если будете передавать данные, добавил для этого метод 'manualSendData':

void setup() {
	svisual::connectOfCOM("test");
}

int cnt = 0;
void loop() {

	svisual::addIntValue("dfv", cnt);

	++cnt;
	if (cnt > 10) cnt = 0;

	bool odd_cnt = cnt % 2;

    svisual::addBoolValue("bFW", odd_cnt);

    svisual::addBoolValue("bBW", !odd_cnt);


    svisual::manualSendData();

    delay(SV_CYCLEREC_MS);
}

sv_client.zip

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

Без таймеров наконец-то заработало, тест во всяком случае.
Попробую Ethernet, и уменьшить SV_CYCLEREC_MS, нужно ли при это изменять SV_PACKETSZ?

svm

from svisual.

Tyill avatar Tyill commented on June 2, 2024

Отлично.
Какой можно вывод сделать из всей этой эпопеи - пока думаю, что все таки dueTimer что-то там неправильно работает, или какое-то влияние на Serial оказывает.

SV_CYCLEREC_MS, нужно ли при это изменять SV_PACKETSZ

нет, они между собой не связаны.

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

БОЛЬШОЕ СПАСИБО ЗА ПОМОЩЬ.

Если не трудно, расскажите, пожалуйте более подробно о "SV_PACKETSZ" (размер пакета, как я понимаю).

В зависимости от чего нужно изменять и как он коррелируется с количеством переменных.

В моём, конкретном случае, это 12 целочисленных (10bit) и 18 булевых.

"SV_CYCLEREC_MS" при этом желательно - 1MS, 10 – приемлемо, ну а 100 край.

from svisual.

Tyill avatar Tyill commented on June 2, 2024

SV_PACKETSZ зачем вообще нужен. Этот параметр задает количество значений переменной, которое за раз передается на сервер (SVMonitor). Это разгружает линию передачи и обработку, иначе бы пришлось передавать каждое значение.

SV_PACKETSZ может принимать значения от 1 до ... какого-то приемлемого значения. Чем больше, тем больший буфер будет в памяти МК для каждой переменной, например, SV_PACKETSZ = 10, значит буфер в МК для переменной 4 * 10 = 40 байт.

SV_CYCLEREC_MS может принимать значения от 10 мс.
То есть 10 мс это принятый мной минимум.
Потому что, если ниже ставить, архив записей на диске начинает занимать гигабайты.
Ну и посчитал что, нет смысла чаще писать, это уже сфера осциллографа.

from svisual.

Tyill avatar Tyill commented on June 2, 2024

В вашем случае можно не трогать SV_CYCLEREC_MS, оставить по умолчанию (100мс).

А цикл опроса датчиков, сделать 1мс.

Получится так:

vaoid setup() {
	svisual::connectOfCOM("test");
}

int svSendCnt = 0;
int cnt = 0;
void loop() {
	
	++cnt;
	if (cnt > 10) cnt = 0;

	bool odd_cnt = cnt % 2;
  
    if ((svSendCnt % SV_CYCLEREC_MS) == 0) {

        svisual::addIntValue("dfv", cnt);

        svisual::addBoolValue("bFW", odd_cnt);

        svisual::addBoolValue("bBW", !odd_cnt);

       svisual::manualSendData();
   }

    ++svSendCnt;
    
    delay(1);
}

from svisual.

Alex6305 avatar Alex6305 commented on June 2, 2024

from svisual.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.