Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <EEPROM.h>
- #include <digitalWriteFast.h>
- #include <avr/wdt.h>
- //#include "ApplicationMonitor.h"
- //#include <AnalogSmooth.h>
- #include <TMRpcm_PLDuino.h>
- #include <SPI.h>
- #include <SD.h>
- //#include <PDQ_GFX.h>
- //#include <PDQ_ILI9341_config.h>
- //#include <PDQ_ILI9341.h>
- #include <Adafruit_GFX.h>
- #include <Adafruit_ILI9341.h>
- #include <PLDuino.h>
- #include <PLDTouch.h>
- #include <PLDuinoGUI.h>
- #include "utils1.h"
- #include <using_namespace_PLDuinoGUI.h>
- #include <DS3232RTC.h>
- #include <TimeLib.h>
- #include <avr/io.h>
- #include <SPI.h>
- #include <SD.h>
- #include "WiFiEsp.h"
- #include <WiFiEspUdp.h>
- #include <EEPROM.h>
- #include <Wire.h>
- //Watchdog::CApplicationMonitor ApplicationMonitor;
- // ASDA-B2
- // P1-08 POSITION SMOOTH (Position Low Pass Filter)
- // P1-44 E-GEAR RATIO [100]
- // P2-35 условие о превышении ошибки по положению AL009. default=480000
- // P1-34 время разгона [200мс] 30мс \\ для режима JOG_MODBUS < 3
- // P1-35 время торможения [200мс] 30мс \\ для режима JOG_MODBUS < 3
- // P1-68 фильтрр комманды позицианирования [0мс] 1мс
- // P2-33 полуавто. режим коррекции [0]
- // P2-32 выбор способа автонастройки [0] 1 - auto; 2 - au/to
- #define D1_FW 39 //1 fw1 дв1 - вперёд
- #define D2_FW 41 //2 fw2 дв2 - вперёд
- #define D1_RW 38 //1 rw1 дв1 - назад
- #define D2_RW 42 //2 rw2 дв2 - назад
- #define GK1 34 // геркон положения дв1
- #define GK2 35 // геркон положения дв2
- #define LBACK 10 // задняие диоды
- #define ASPEED A7
- #define ABREAK 10
- #define AANGLE A6
- #define LEDI 31
- #define A0SMOOTH 20
- #define A1SMOOTH 70
- #define A0SHIFT 506
- #define A1SHIFT 286//154 // в зависимости от положения датчика при установке датчика
- #define AENABLE true
- #define STARTPIN 31
- #define START_ENABLED false
- #define BAUDRATE 19200
- #define RSTPIN A5
- #define ANGLEC 1
- #define ANG 360
- #define SPEED0 284
- #define FILENAME "xtre.cfg"
- // --------------------
- int D;
- int DR_DELAY_1 = 0;
- int DR_DELAY_2 = 0;
- int UDP_DELAY = 0;
- bool touched = false;
- TMRpcm tmrpcm; // create an object for use in this sketch
- //AnalogSmooth asx = AnalogSmooth(10);
- File f;
- WiFiEspUDP udp;
- int status = WL_IDLE_STATUS;
- int clr = 0xF800;
- int shiftx=0;
- String s = "";
- String is,is1 = "" ;
- boolean sc = false;
- boolean i_s =false;
- bool CFG_OK = false;
- String ssid, pass;
- unsigned int localPort = 9999; // local port to listen on
- unsigned int rPort = 9990; // remote port
- IPAddress Ip(192, 168, 1, 255);
- Label l("", ILI9341_WHITE);
- Adafruit_ILI9341 tft = Adafruit_ILI9341(PLDuino::LCD_CS, PLDuino::LCD_DC);
- PLDTouch touch(PLDuino::TOUCH_CS, PLDuino::TOUCH_IRQ);
- int Y,X1,Y1;
- // --------------------
- int ASPEED_OUT = 0;
- long millis100 = 0;
- int prev_aspeed, prev_arb, aspeed, arot0, aangle;
- int x = 0;
- int cnt = 0;
- String inputString, oStr = ""; // a string to hold incoming data
- String spd1,spd2,pls1,pls2 = ""; //ccw_spd cw_spd impulses
- bool stringComplete = false; // whether the string is complete
- bool stringDelim = false;
- bool CORRECT = false;
- unsigned int CORRECTC = 0;
- long CNT_DELAY1,CNT_DELAY0, CNT_PULSES1, CNT_PULSES0, FFDELAY = 0;
- int dl1,dl0,speed1,speed1p,_speed1,speed2,speed2p,_speed2,D1,D2 = 0;
- long Pulses0, Pulses0CNT, Pulses1, Pulses1CNT;
- bool CNT1_,CNT0_,BRK0,BRK1,END1,END0,UP_DOWN = false;
- long A180 = 100000;
- #define GEAR_RATIO 40 // ASDA-B2 -> P1-44 -> VAL/100 = 40; текущее значние 4000
- #define RATIO_DELAY 20 //
- #define UDP_READ_TIMEOUT 2
- unsigned long micros0, micros1;
- long ar =0;
- float ar1,prev_arot = 0.0;
- int ari,ari1,arb,arb1,ledi = 0;
- bool abreakb = false;
- int abreakval = 0;
- unsigned int AREADDL = 0;
- char delim; // разделитель входных параметров
- String _str = "";
- unsigned int ASDA_ALARM_RESET_CNT = 0;
- long POSA,POSB; // счётчик абсолютного угла
- long POSA1,POSB1; // счётчик фактического угла
- typedef (*SmtToDo)();
- class DelayAsync{
- private:
- bool b = false;
- unsigned dl = 0;
- unsigned long t = 0;
- public:
- DelayAsync(int Delay);
- Start();
- bool isDone();
- };
- DelayAsync::Start()
- {
- if (b==false)
- {
- b = true;
- // t = micros();
- }
- }
- DelayAsync::DelayAsync(int Delay)
- {
- this->t = Delay;
- };
- bool DelayAsync::isDone()
- {
- return true;
- };
- class MyDelayedTask
- {
- private:
- int cnt = -1;
- typedef (*Task1)();
- struct TaskEx{
- Task1 Task;
- String tName;
- int tDelay;
- };
- TaskEx Tasks[255];
- public:
- MyDelayedTask();
- Add(String taskName, Task1 myTask, unsigned int Delay);
- Start (String taskName);
- Stop (String taskName);
- };
- void UDP_SEND(String s)
- {
- udp.beginPacket(Ip, rPort);
- udp.write(s.c_str()) ;
- udp.endPacket();
- }
- const char* c_str1(String str) {
- char* buf = new char[str.length()];
- str.getBytes(buf, str.length()+1, 0);
- strcpy(reinterpret_cast<const char*>(buf),buf);
- return buf;
- }
- void UpdStaticLog(String s, bool visible, uint16_t color)
- {
- //showl(is);
- tft.setCursor(0, 0);
- tft.setTextColor(0x0000);
- tft.println(s);
- if (!visible) return;
- tft.setTextColor(color);
- tft.setCursor(0, 0);
- tft.println(s);
- }
- void setup_PLC()
- {
- //pinMode(42, OUTPUT);
- PLDuino::init();
- PLDuino::enableLCD();
- PLDuino::enableESP();
- tft.begin();
- tft.fillScreen(ILI9341_BLACK);
- tft.setRotation(3);
- tft.setTextSize(1);
- touch.init(1);
- Serial.begin(115200);
- // Serial2.begin(115200);
- // WiFi.init(&Serial2);
- tmrpcm.speakerPin = 9;
- delay(100);
- tone(9, 700); delay(50); noTone(9);
- tone(9, 700); delay(50); noTone(9);
- while (!SD.begin(PLDuino::SD_CS))
- {
- UpdStaticLog("Failed to initialize SD card. Please check it.", true, 0xF800);
- delay(1000);
- UpdStaticLog("Failed to initialize SD card. Please check it.", false, 0x0000);
- delay(1000);
- }
- UpdStaticLog("Failed to initialize SD card. Please check it.", false, 0x0000);
- Serial.println("SD Open...");
- UpdStaticLog("SD card init OK.", true, 0xFFFF);
- /*
- File f = SD.open(FILENAME, FILE_READ);
- Serial.println("SD Open... OK");
- String fs = "SHITTTTTTTTTTT";
- {
- // Stop on error
- // UpdStaticLog("Failed to open " FILENAME ". Stop.", true, 0xF800);
- // return;
- }
- while (f.available() > 0)
- {
- fs = f.readStringUntil('\n');
- if (fs.indexOf("_apc]") > 0)
- {
- ssid = f.readStringUntil('\n');
- pass = f.readStringUntil('\n');
- break;
- }
- }
- Serial.println(ssid);
- Serial.println(pass);
- f.close();
- delay(1000);
- Serial.println(pass.c_str());
- UpdStaticLog("SD card init OK. Loading config...", false, 0x0000);
- UpdStaticLog("SSID=" + String(ssid) + "\nPASS=" + String(pass), true, 0xFFFF);
- delay(1000);
- UpdStaticLog("SSID=" + String(ssid) + "\nPASS=" + String(pass), false, 0x0000);
- byte l0 = ssid.length()+1;
- byte l1 = pass.length()+1;
- char ssid0[l0];
- char pass0[l1];
- ssid.toCharArray(ssid0,l0);
- pass.toCharArray(pass0,l1);
- if (WiFi.status() == WL_NO_SHIELD) {
- Serial.println("WiFi shield not present");
- // don't continue:
- while (true);
- }
- ssid.replace(0xd,'\0');
- ssid.replace(' ','\0');
- pass.replace(' ','\0');
- pass.replace(0xd,'\0');
- String s0 = "Attempting to connect to WPA SSID: "+String(ssid.c_str());
- while ( status != WL_CONNECTED) {
- digitalWriteFast(42,HIGH);
- delay(500);
- digitalWriteFast(42,LOW);
- UpdStaticLog(s0,false,0x0000);
- UpdStaticLog(s0,true,0xFFFF);
- Serial.println(s0);
- tone(9, 500); delay(100); noTone(9);
- // Connect to WPA/WPA2 network
- // ssid.remove(ssid.length());
- // pass.remove(pass.length());
- status = WiFi.begin(c_str1(ssid),c_str1(pass));
- delay(500);
- }
- char bufIP[16];
- sprintf(bufIP, "IP:%d.%d.%d.%d", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] );
- UpdStaticLog(s0,false,0x0000);
- UpdStaticLog("Connected. " +String(bufIP),true,0xFFFF);
- Serial.println(String(bufIP));
- udp.begin(localPort);
- delay(2000);
- UpdStaticLog("Connected. " +String(bufIP),false,0x0000);
- tft.setTextSize(2);
- */
- const char *x = "x1.bmp";
- bmpDraw(tft,x,0,0);
- }
- MyDelayedTask::MyDelayedTask()
- {
- cnt=0;
- }
- MyDelayedTask::Add(String taskName, Task1 myTask, unsigned int Delay)
- {
- TaskEx t;
- t.tName = "";
- t.Task = myTask;
- t.tDelay = Delay;
- Tasks[sizeof(Tasks)] = t;
- }
- MyDelayedTask:: Start(String taskName)
- {
- }
- long P2A(long Pulses)
- {
- return (((Pulses*GEAR_RATIO)*ANG)/A180) ;
- }
- void init1()
- { //INIT
- int prev_aspeed, prev_arb, aspeed, arot, prev_arot = 0;
- int x = 0;
- int cnt = 0;
- inputString = ""; // a string to hold incoming data
- stringComplete = false; // whether the string is complete
- long CNT_DELAY1,CNT_DELAY0, CNT_PULSES1, CNT_PULSES0;
- CNT_DELAY1 = 0;
- CNT_DELAY0 = 0;
- int dl1,dl0,speed1,_speed1,speed2,_speed2,D1,D2 = 0;
- long Pulses0, Pulses0CNT, Pulses1, Pulses1CNT = 0;
- bool CNT1_,CNT0_,BRK0,BRK1,END1,END0 = false;
- int ar,ar1 = 0;
- int ari,ari1,arb,arb1,ledi = 0;
- abreakb = false;
- abreakval = 0;
- }
- void POSAB()
- {
- int posa = 0; int posb = 0;
- if (POSA>POSB) {posa = (POSA-POSB)/2; posb = (POSA+POSB) /2;}
- if (POSA<POSB) {posa = (POSB-POSA)/2; posb = -(POSA+POSB) /2;}
- Serial.println(String(posa)+" "+String(posb));
- }
- void Cnvrtr() //преобразовние положения двигателей в положение осей 2dof
- {
- int x1 = 0;
- int y1 = 0;
- int posa, posb =0;
- int posa1 = P2A(POSA1); int posb1 = P2A(POSB1); // преобразование посчитаных импульсов двигателей 1 2 в углы
- if (posa1>posb1 && posa1>0 && posb1>=0) {posb = (posa1-posb1)/2; posa = posa1-posb; } else // _`_|_._
- if (posb1>posa1 && posb1>0 && posa1>=0) {posb = -(posb1-posa1)/2; posa = posb1-abs(posb);} else // _._|_`_
- // __|__
- if (abs(posa1)>abs(posb1) && posa1<0 && posb1<=0) {posb = -(abs(posa1)-abs(posb1))/2; posa = -(abs(posa1)-abs(posb));} else // . | `
- // __|__
- if (abs(posb1)>abs(posa1) && posb1<0 && posa1<=0) {posb = (abs(posb1)-abs(posa1))/2; posa = -(abs(posb1)-abs(posb));} else // ` | .
- if (abs(posa1)>abs(posb1) && posb1<=0 && posa1>0) {posb=(posa1+abs(posb1))/2; posa=posa1-posb; } else // _`_|_ _
- // | .
- if (abs(posb1)>abs(posa1) && posa1<=0 && posb1>0) {posb=-(posb1+abs(posa1))/2; posa=posb1-abs(posb); } else // _ _|_`_
- // . |
- if(abs(posa1)>posb1 && posa1<0 && posb1>0) {posb=-(abs(posa1)+abs(posb1))/2; posa = -(abs(posa1)-abs(posb)); } else // _`_|_ _ // если abs(`) > abs(.) и ` > 0 и . < 0
- // | .
- if(abs(posb1)>posa1 && posb1<0 && posa1>0) {posb= (abs(posa1)+abs(posb1))/2; posa = -(abs(posb1)-abs(posb)); } else //_ _|_`_ // если abs(`) > abs(.) и ` > 0 и . < 0
- // . |
- if(abs(posa1)==posb1 && posa1<0 && posb1>0) {posb= -(abs(posa1)); posa = 0; } else //_ _|_`_ // если abs(`) == abs(.) и ` > 0 и . < 0
- // . |
- if(abs(posb1)==posa1 && posb1<0 && posa1>0) {posb= abs(posa1); posa = 0; } else //_`_|_ _ // если abs(`) == abs(.) и ` > 0 и . < 0
- // | .
- if(abs(posa1)==posb1 && posa1>0 && posb1>0) {posb= 0; posa = abs(posa1); } else //_`_|_'_ // если abs(`) == abs(') и ` > 0 и ' > 0
- // |
- if(posb1==posa1 && posb1<0 && posa1<0) {posb= 0; posa = -(abs(posa1)); } //_ _|_ _ // если abs(.) == abs(,) и . < 0 и , < 0
- // . | ,
- //текущие позицыи двигателей относительно их текущего положения
- x1 = pls1.toInt(); y1 = pls2.toInt();
- int x2 = x1; int y2 = y1;
- x1 = x1 - posa;
- y1 = y1 - posb;
- pls1 = String(x1 + y1);
- pls2 = String(x1 - y1);
- POSA = x2;
- POSB = y2;
- if (x2==0 && y2==0)
- {
- pls1 = String(-P2A(POSA1));
- pls2 = String(-P2A(POSB1));
- POSA=0;POSB=0;
- }
- i_s = false;
- }
- int iofd(String s, char d) // проверка входной строки на корретность
- {
- int c = 0;
- for (int i=0; i<s.length(); i++)
- {if (s[i]==d) c++;}
- return c;
- }
- void parseStr(String &str)
- {
- if (str.indexOf("GLIST")>=0) { digitalWriteFast(42,HIGH); digitalWriteFast(42,HIGH);}
- if (str.indexOf("BLOXA")>=0) { digitalWriteFast(42,LOW); digitalWriteFast(42,LOW);}
- byte p0 = str.indexOf('[');
- byte p1 = str.indexOf(']');
- byte p2 = str.indexOf('.',p0);
- byte p3 = str.lastIndexOf('.',p0);
- String str0;
- if (p1>p0)
- {
- //&& p2>p0 && p3<p1 && iofd(str,'.')==3
- str0 = str.substring(str.indexOf('[')+1,str.length()-(str.length()-str.indexOf(']'))); i_s = true;}
- else {spd1 = "0"; spd2 = "0"; pls1 = "0"; pls2="0"; };
- // oStr = str0;
- //if (str[0]=='L') digitalWriteFast(LBACK, String(str[1]).toInt()); // вкл-выкл фонарей
- if (delim=='.' && !UP_DOWN) _str = str;
- str.indexOf(',')>0?delim='.':delim='.';
- /*
- if ( iofd(str,' ')>0 || iofd(str,'+')>0 || iofd(str,'I')>0 || iofd(str,',')>0 ) // проверка строки на корректность, если входная строка кривая то не парсит
- {
- // oStr = str;
- spd1 = "0"; spd2 = "0"; pls1 = "0"; pls2="0";
- return;
- } // если вх строка не правильная то выхожу
- */
- str = str0;
- if (str.indexOf(delim)>0)
- {
- int pos,pos1;
- char chrs[str.length()];
- spd1 = ""; spd2 = ""; pls1 = ""; pls2="";
- for (int i=0; i!=(int)str.indexOf(delim); i++)
- {
- spd1 = spd1 + str[i];
- }
- pos = str.indexOf(delim,str.indexOf(delim)+1);
- for (int i=str.indexOf(delim)+1; i!=pos; i++)
- {
- spd2 = spd2 + str[i];
- }
- // pos = str.indexOf(delim,pos+1);
- pos1 = str.indexOf(delim,pos+1);
- for (int i=pos+1; i!=pos1; i++)
- {
- pls1 = pls1 + str[i];
- }
- for (int i=pos1+1; i!=str.length(); i++)
- {
- pls2 = pls2 + str[i];
- }
- speed1=0; speed2 = 0;
- }
- Cnvrtr();
- //sSerial.println(String(POSA)+" "+String(POSB));
- //int posa, posb;
- // posa = POSA1; posb = POSB1;
- }
- void udp_read1()
- {
- int packetSize = udp.parsePacket();
- if (packetSize)
- {
- udp.setTimeout(UDP_READ_TIMEOUT);
- is = udp.readStringUntil('\n');
- // Serial.println(is);
- parseStr(is);
- //is = is.substring(is.indexOf(':')+1);
- sc = true;
- }
- //is = is.substring(is.indexOf(':')+1);
- sc = true;
- }
- void SC()
- {
- if (stringComplete) {
- parseStr(inputString);
- inputString = "";
- stringComplete = false;
- }
- //str = inputString[1].concat(inputString[1]);
- }
- void DriveIt(int srvNum,int Delay)
- {
- digitalWriteFast(srvNum, HIGH);
- delayMicroseconds(Delay);
- digitalWriteFast(srvNum, LOW);
- delayMicroseconds(Delay);
- }
- void DriveItPls(int srvNum,int Delay,int Pulses)
- {
- for (int i=0; i++; i!=Pulses)
- {
- digitalWriteFast(srvNum, HIGH);
- delayMicroseconds(Delay);
- digitalWriteFast(srvNum, LOW);
- delayMicroseconds(Delay);
- }
- }
- void DriveItAsync0(int CNT, int DELAY,int srvNum)
- {
- if (!CNT0_ && CNT==DELAY-1 && !BRK0)
- {
- CNT0_ = !CNT0_;
- Pulses0CNT++;
- srvNum==D1_RW?POSA1++:POSA1--;
- digitalWriteFast(srvNum, HIGH);
- }
- if (CNT0_ && CNT==DELAY-1 && !BRK0)
- {
- CNT0_ = !CNT0_;
- Pulses0CNT++;
- digitalWriteFast(srvNum, LOW);
- }
- // POSA = P2A(POSA1);
- }
- void DriveItAsync1(int CNT, int DELAY,int srvNum)
- {
- if (!CNT1_ && CNT==DELAY-1 && !BRK1)
- {
- CNT1_ = !CNT1_;
- Pulses1CNT++;
- srvNum==D2_RW?POSB1++:POSB1--;
- digitalWriteFast(srvNum, HIGH);
- }
- if (CNT1_ && CNT==DELAY-1 && !BRK1)
- {
- CNT1_ = !CNT1_;
- Pulses1CNT++;
- digitalWriteFast(srvNum, LOW);
- }
- // POSB = P2A(POSB1);
- }
- void DriveTo(int CW_CCW,int Delay, int pulses)
- {
- for (int i=0; i<pulses;i++)
- {
- if (CW_CCW==D1_RW) POSA1++;
- if (CW_CCW==D1_FW) POSA1--;
- if (CW_CCW==D2_RW) POSB1++;
- if (CW_CCW==D2_FW) POSB1--;
- DriveIt(CW_CCW, Delay);
- }
- //str1="";
- }
- void OnRx()
- {
- // SC();
- }
- int SMOOTHPIN(int PIN) // фильтр цифрового входа
- {
- int a = LOW;
- for (int i=0; i!=10; i++) a|=digitalRead(PIN);
- return a;
- }
- void setup()
- {
- Serial.setTimeout(3);
- pinMode(GK1, INPUT_PULLUP);
- pinMode(GK2, INPUT_PULLUP);
- pinMode(D1_FW, OUTPUT);
- pinMode(D2_FW, OUTPUT);
- pinMode(D1_RW, OUTPUT);
- pinMode(D2_RW, OUTPUT);
- setup_PLC();
- //pinMode(ASPEED, INPUT_PULLUP);
- // pinMode(AANGLE, INPUT_PULLUP);
- // tmrpcm.play("modem.wav");
- // delay(14000);
- /*
- for (int i = 0 ; i < EEPROM.length() ; i++) {
- EEPROM.write(i, 0);
- }
- */
- // pinMode(STARTPIN, INPUT);
- // digitalWriteFast(LBACK,LOW);
- // wdt_disable();
- // Serial.begin(128000);
- //detachInterrupt(0);
- //detachInterrupt(1);
- //ApplicationMonitor.Dump(Serial);
- //analogReference(INTERNAL);
- // Serial.begin(2000000);
- spd1 = "0";
- spd2 = "0";
- pls2 = "0";
- pls2 = "0";
- POSA = 0 ; POSB = 0;
- POSA1 = 0 ; POSB1 = 0;
- // wdt_enable(WDTO_4S);
- for (int i=0; i<400; i++)
- {
- DriveIt(D1_RW,690);
- DriveIt(D2_RW,690);
- }
- // digitalWriteFast(LBACK,HIGH);
- Serial.println("MOVE...");
- while (
- (digitalRead(GK1)!=LOW || digitalRead(GK2)!=LOW) ||
- ((digitalRead(GK1)!=LOW && digitalRead(GK2)!=LOW)) ||
- (digitalRead(GK1)!=HIGH || digitalRead(GK2)!=LOW) ||
- (digitalRead(GK1)!=LOW || digitalRead(GK2)!=LOW) // <<< - (!digitalRead(GK1)!=LOW || !digitalRead(GK2)!=LOW)
- )
- {
- // if (SMOOTHPIN(STARTPIN)==LOW) setup();
- int spd = 490;
- digitalRead(GK1)==LOW || digitalRead(GK2)==LOW?delayMicroseconds(20):delayMicroseconds(0);
- if (digitalRead(GK2)==HIGH) DriveIt(D1_RW,spd);
- if (digitalRead(GK1)==HIGH) DriveIt(D2_RW,spd);
- if (digitalRead(GK1) == LOW && digitalRead(GK2) == LOW) break;
- // if ( digitalRead(GK1)==LOW && digitalRead(GK2)==LOW ) break; // если оба геркона замкнулись то выхожу из цикла
- }
- /// wdt_disable();
- Serial.println("MOVE OK");
- // digitalWriteFast(LBACK,LOW);
- tone(9, 300); delay(100); noTone(9);
- tone(9, 600); delay(50); noTone(9);
- //tmrpcm.play("modem.wav");
- // delay(14000);
- // tone(9, 600); delay(50); noTone(9);
- //tone(9, 300); delay(100); noTone(9);
- /*
- wdt_enable(WDTO_1S);
- while (inputString.indexOf("tre")<1)
- {
- if (SMOOTHPIN(STARTPIN)==LOW) setup();
- for (int i=0; i<100; i++)
- {
- analogWrite(LEDI,i);
- delay(1);
- }
- Serial.println("matic");
- delay(100);
- serialEvent();
- wdt_reset();
- for (int i=50; i>1; i--)
- {
- analogWrite(LEDI,i);
- delay(1);
- }
- // if (stringComplete)
- // Serial.println(String(">")+inputString);
- }
- inputString = "";
- */
- // for (int i=0; i<5; i++) {Serial.println("matic"); delay(100);}
- //ApplicationMonitor.EnableWatchdog(Watchdog::CApplicationMonitor::Timeout_1s);
- wdt_enable(WDTO_2S);
- }
- int smoothAnal(int APIN,int shift)
- {
- aspeed = analogRead(APIN);
- ar=ar+aspeed;
- ari++;
- if (ari==300)
- {
- ari=0;
- if (ar/300!=prev_aspeed) {int x = 981-(ar/300); x<0?x=0:x; Serial.print(x);}
- prev_aspeed=ar/300;
- ar=0;
- }
- }
- void loop() {
- wdt_reset();
- if (Serial.available()){
- is = Serial.readStringUntil('\n');
- //// if(s!="[RST]")
- wdt_reset();
- parseStr(is);
- }
- //ApplicationMonitor.IAmAlive(); // watchdog + eeprom log
- //udp_read1();
- //UpdStaticLog(is1,false,0x0000);
- //UpdStaticLog(is,true,0xFFFF);
- //is1=is;
- //SC();
- //Serial.println(_str);
- if (delim=='.' && UP_DOWN)
- {
- UP_DOWN = false;
- parseStr(_str);
- // _str = "";
- }
- if (delim==',' && !UP_DOWN)
- {
- UP_DOWN = true;
- }
- if (spd1!="" && spd2!="" /*&& (pls1!="0" && pls2!="0")*/ ) // если на посл.порт пришли данные, то сброс
- {
- // init1();
- speed1 = 0; speed2 = 0;
- // Pulses0CNT = 0; Pulses1CNT = 0;
- //CNT_DELAY0=-1;
- //CNT_DELAY1=-1;
- Pulses0 = 10; Pulses1 = 10;
- END0=true; //Pulses0 = 0; speed1 = 0;
- END1=true; //Pulses1 = 0; speed2 = 0;
- if (speed1==0){
- int _spd = spd1.toInt();
- _spd>9?_spd=9:_spd=_spd; _spd<=0?_spd=1:_spd=_spd;
- speed1 = 10 -_spd;
- }
- if (speed2==0){
- int __spd = spd2.toInt();
- __spd>9?__spd=9:__spd=__spd; __spd<=0?__spd=1:__spd=__spd;
- speed2 = 10 - __spd;
- }
- //if (POSA1 == POSA+1 || POSA1 == POSA-1) POSA1 = POSA;
- //if (POSB1 == POSB+1 || POSB1 == POSB-1) POSB1 = POSB;
- if (Pulses0==0 || Pulses0==10)
- {
- int pls_ = pls1.toInt();
- Pulses0 = ((A180 * abs(pls_)*ANGLEC)/GEAR_RATIO) / ANG;
- if (pls_<0)
- {
- D1 = D1_FW;
- }
- else
- {
- D1 = D1_RW;
- }
- if (abs(POSA-POSA1)>2)
- {
- // if (POSA-POSA1 > 0) D1 = D1_FW;
- // else D1 = D1_RW;
- }
- }
- if (Pulses1==0 || Pulses1==10)
- {
- int pls__ = pls2.toInt();
- delim=='.'?Pulses1 = ((A180 * abs(pls__)*ANGLEC)/GEAR_RATIO) / ANG:Pulses1=abs(pls__);
- if (pls__<0)
- {
- // if (POSB+1>POSB1) pls__ = -1; // компенсация погрешности. если абсолютный градус отличается от фактического, то происходит коррекция
- D2 = D2_FW;
- }
- else
- {
- // if (POSB+1<POSB1) pls__ = 1; // компенсация погрешности. если абсолютный градус отличается от фактического, то происходит коррекция
- D2 = D2_RW;
- }
- if (abs(POSB-POSB1)>2)
- {
- // if (POSB-POSB1 > 0) D2 = D2_FW;
- // else D2 = D2_RW;
- }
- }
- if (Pulses0<11 && Pulses1>11 ) speed2 = speed2*2; // если, в итоге, одному двигателю не нужно импульсов, то уменьшается нагрузка на цп
- if (Pulses1<11 && Pulses0>11 ) speed1 = speed1*2; // следовательно второму двигателю нужно уменьшать итоговую скорость в 2 раза.
- // :} tone(9, abs(pls1.toInt()+pls2.toInt()));
- }
- //if (POSA<0)
- ///if (POSA<0) DriveItPls(D1_RW,290,((A180 * abs(pls__))/GEAR_RATIO) / 180)
- // Pulses0CNT - импульсы считаются при Low и High цыклах
- if (END0 && Pulses0 > 0 && Pulses0*2 > Pulses0CNT && speed1>0 ) /// добавить && speed!=0
- {
- // micros0 = micros();
- if (!i_s)
- DriveItAsync0( CNT_DELAY0,speed1,D1);
- // Serial.println(Pulses0CNT);
- // micros0 = micros()-micros0;
- }
- if ( END0 && (Pulses0CNT+10) > Pulses0*2 )
- {
- Pulses0CNT=0; Pulses0 = 0; speed1 = 0; END0=false; Pulses0CNT=0; spd1="";
- //noTone(9);
- if (UP_DOWN) delim='.';
- };
- if (END1 && Pulses1 > 0 && Pulses1*2 > Pulses1CNT && speed2>0 )
- {
- // micros0 = micros();
- if (!i_s)
- DriveItAsync1( CNT_DELAY1,speed2,D2);
- // micros0 = micros()-micros0;
- // Serial.println(Pulses1CNT);
- }
- if ( END1 && (Pulses1CNT+10) > Pulses1*2 )
- {
- Pulses1CNT=0; Pulses1 = 0; speed2 = 0; END1=false; Pulses1CNT=0; spd2="";
- // noTone(9);
- if (UP_DOWN) delim='.';
- };
- if (END0==false && Pulses0>10) {delayMicroseconds(GEAR_RATIO*2*(speed1+speed2)/2);}
- if (END1==false && Pulses1>10) {delayMicroseconds(GEAR_RATIO*2*(speed1+speed2)/2);}
- // если один из двигателей закончил движение быстрее, вводится доп задержка, чтобы компенсировать ускорение движения в одном из циклов
- if (speed1>0 && Pulses0*2 != (Pulses0CNT+10))
- {
- if (speed1p!=speed1) { speed1p = speed1; CNT_DELAY0 = 0; } // если новая скорость отличается от предыдущей то счётчик задержки в 0
- CNT_DELAY0++;
- if (CNT_DELAY0==speed1) CNT_DELAY0 = 0;
- } // счётчики задержки
- if (speed2>0 && Pulses1*2 != (Pulses1CNT+10))
- {
- if (speed2p!=speed2) { speed2p = speed2; CNT_DELAY1 = 0; } // если новая скорость отличается от предыдущей то счётчик задержки в 0
- CNT_DELAY1++;
- if (CNT_DELAY1==speed2) CNT_DELAY1 = 0;
- } //
- // глюк непоятного поведенеия при динамичской смене скорости заключается тут ^^^^^^
- if (inputString == "xtrematicrst") {Serial.println("matic_reset"); inputString=""; setup(); }
- //if (inputString=="" && AENABLE)
- /*
- { // датчик скорости
- unsigned int x = 0;
- aspeed = analogRead(ASPEED);
- // delayMicroseconds(1);
- ar=ar+aspeed;
- ari++;
- if (ari==A0SMOOTH)
- {
- ari=0;
- if (ar/A0SMOOTH!=prev_aspeed) {
- x = A0SHIFT-(ar/A0SMOOTH);// x<0?x=0:x;
- // if (abreakval==1) x=-1;
- {
- x = SPEED0-x;
- oStr += "S"+String(x)+'\n';
- // oStr += "S"+String(analogRead(ASPEED))+'\n';
- }
- }
- prev_aspeed=ar/A0SMOOTH;
- ar=0;
- // ledi++;
- // analogWrite(LEDI,10+x);
- //if (ledi==255) ledi==0;
- }
- //
- //
- /*
- { // датчик угла руля
- float x = 0;
- int arot = analogRead(AANGLE);
- //delayMicroseconds(1);
- ar1=ar1+arot;
- ari1++;
- if (ari1==A1SMOOTH)
- {
- ari1=0;
- long y = ar1/A1SMOOTH;
- if (ar1/A1SMOOTH!=prev_arot)
- {
- y>prev_arot+1?x = A1SHIFT-(prev_arot+1):y<prev_arot-1?x = A1SHIFT-(prev_arot-1):x = A1SHIFT-prev_arot;
- // ar1/A1SMOOTH>prev_arot+1?x = aangle++ :ar1/A1SMOOTH<prev_arot-1?x = aangle--:x = aangle;
- // x = A1SHIFT-(ar1/A1SMOOTH);
- // x<0?x=0:x = x;
- //x>prev_arot+3?x=prev_arot:x<prev_arot-3?x=prev_arot:x=x;
- oStr+="A"+String(x)+'\n';
- // Serial.print("$"+String(x)+";");
- // oStr+="A"+String(analogRead(AANGLE))+'\n';
- prev_arot = (y+prev_arot)/2;
- // prev_arot = ar1/A1SMOOTH ;
- }
- ar1=0;
- // ledi++;
- // analogWrite(LEDI,10+x);
- //if (ledi==255) ledi==0;
- }
- // датчик тормоза
- //int x;
- abreakval = digitalRead(ABREAK);
- }
- //oStr+="A"+String(A1SHIFT-asx.analogReadSmooth(AANGLE))+'\n';
- // AREADDL=0;
- //}
- */
- { // NOISE DELAY
- FFDELAY++;
- ;
- if (FFDELAY==40) {
- if (oStr!="")
- {
- UDP_SEND(oStr);
- oStr = "";
- }
- else
- {
- // POSA = POSA1;
- // POSB = POSB1;
- // отправляю градус поворота двигателя абсолютный и фактический(реально отработавшие такты)
- // String s = String("X")+String((int)P2A(POSA1))+" "+String(POSA);
- ///Serial.println(s);
- // Serial.println( String("Y")+String((int)P2A(POSB1)) +" "+String(POSB) );
- }
- // analogWrite(LEDI,ar-ar1);
- FFDELAY=0;
- }
- }
- //if (SMOOTHPIN(STARTPIN)==LOW) setup();
- delayMicroseconds(2);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement