r/ArduinoProjects • • Jul 13 '24

Need suggestion to improve/fix code.

0 Upvotes

I am trying to make an Arduino based ESC for 3-phase BLDC motor, which is based on the first esc made by YouTuber Electronoobs. I don't understand most of the code, but I do know just enough to change the pin numbers in the code to match my circuit.

My ESC does run but it's very slow and have little torque. Rotating the potentiometer which according to code is supposed to change the speed of the motor, doesn't seem to do anything.

I know back EMF detection is working because when I hold the motor lightly it slows down, releasing it returns to the previous speed. I also added serial output of the back EMF detection, and on serial plotter, I can see the waves changing when I hold the motor lightly. I am also sure that this is not because of my circuit and unfortunately I didn't make a schematic of it either.

My motor is 600kv, power supply is 12v, the power supply isn't the limitation because the current doesn't exceed 2 amps, my power supply is rated for 5 amps. Unfortunately I don't have a commercial ESC to see whether my motor is the problem, but I also don't think there's any issue with my motor.

Here is the link to the original code and down below is the edited version to match my circuit. Thanks.

int AA1=5;
int AA2=3;
int BB1=9;
int BB2=6;
int CC1=10;
int CC2=11;

int enable=2; //This is not used for now, The ESC is always enabled
int emfA=A3;
int emfB=A2;
int emfC=A1;

int fase=1;
int deltaA=0;
int emA=0;
int sum=0;

int IN=A0;
int Delay=4000;

int it=0;
int it2=1;

static int delta= 0;
static int Lastdelta= -1;

unsigned long previousMillis = 0; 

void setup() {
Serial.begin(250000);
  pinMode(AA1,OUTPUT);
  pinMode(AA2,OUTPUT);
  pinMode(BB1,OUTPUT);
  pinMode(BB2,OUTPUT);
  pinMode(CC1,OUTPUT);
  pinMode(CC2,OUTPUT);

  pinMode(enable,OUTPUT);

  pinMode(IN,INPUT);
  pinMode(emfA,INPUT);
  pinMode(emfB,INPUT);
  pinMode(emfC,INPUT);
  
  //digitalWrite(enable,HIGH);
  //previousMillis = micros();
  
}

void loop() {

      
      int emA = analogRead(emfA);
      int emB = analogRead(emfB);
      int emC = analogRead(emfC);
      int sum = (emA+emB+emC)/3;  

      unsigned long currentMillis = micros();
 
  
  if(currentMillis - previousMillis >= Delay){
  
      previousMillis += Delay;
   
  //Phase1 C-B
  switch(fase){
    case 1:
      digitalWrite(AA1,LOW);
      digitalWrite(AA2,LOW);
      digitalWrite(BB1,LOW);
      digitalWrite(CC2,LOW);
      digitalWrite(BB2,HIGH);
      digitalWrite(CC1,HIGH);
      delta = emA-sum;
      
      break;
      

  //Phase2 A-B
    case 2:
      digitalWrite(AA2,LOW);
      digitalWrite(BB1,LOW);
      digitalWrite(CC1,LOW);
      digitalWrite(CC2,LOW);
      digitalWrite(AA1,HIGH);
      digitalWrite(BB2,HIGH);
      delta = emC-sum;
      break;

  //Phase3 A-C
    case 3: 
      digitalWrite(AA2,LOW);
      digitalWrite(BB1,LOW);
      digitalWrite(BB2,LOW);
      digitalWrite(CC1,LOW);
      digitalWrite(CC2,HIGH);
      digitalWrite(AA1,HIGH);
      delta = emB-sum;
    break;   
  
  //Phase4 B-C
  case 4:
      digitalWrite(AA1,LOW);
      digitalWrite(AA2,LOW);
      digitalWrite(BB2,LOW);
      digitalWrite(CC1,LOW);
      digitalWrite(BB1,HIGH);
      digitalWrite(CC2,HIGH);
      delta = emA-sum;
      break;

  //Phase5 B-A 
  case 5:
      digitalWrite(AA1,LOW);
      digitalWrite(BB2,LOW);
      digitalWrite(CC1,LOW);
      digitalWrite(CC2,LOW);
      digitalWrite(AA2,HIGH);
      digitalWrite(BB1,HIGH);
      delta = emC-sum;
      break;

  //Phase6 C-A
  case 6:
      digitalWrite(AA1,LOW);
      digitalWrite(BB1,LOW);
      digitalWrite(BB2,LOW);
      digitalWrite(CC2,LOW);
      digitalWrite(CC1,HIGH);
      digitalWrite(AA2,HIGH);
      delta = emB-sum;
  break;
  }

  if (Lastdelta < 0){
  if (delta > 0)
      {
        Lastdelta=delta; //save the last delta
        fase= fase + 1;
        if (fase > 6) {
          fase = 1;
          }
      }
  }//Zero cross from - to +  

  if (Lastdelta > 0){
  if (delta < 0)
      {
        Lastdelta=delta;
        fase= fase + 1;
        if (fase > 6) {
          fase = 1;
          }
      }
  }//Zero cross from + to - 
   
  }//Case ends


  int t =analogRead(IN); //From the potentiometer
  Delay=map(t,0,1024,1,1000); //we obtain the delay speed using the potentiometer
  //we map the values from 1 to 1000 microseaconds

  Serial.print(emA);
  Serial.print(" ");
  Serial.print(emB);
  Serial.print(" ");
  Serial.println(emC);  
 
} //loop ends

r/ArduinoProjects • • Jul 20 '24

Can i possibly transfer audio from an ISD1820 to my laptop?

0 Upvotes

My project consist of recording answers of random questions and get them on my laptop, the "recorder" i chose for my project is the "ISD1820" but i'm not sure if i can transfer the audio to my laptop through an Arduino Uno R3. Can someone help me or tell me what microphone module i can buy? Or what do i need to transfer the recordings? It's for a school proyect literally.


r/ArduinoProjects • • Aug 17 '24

Can anyone tell me how to connect Alfa romeo 156 Speedo and accelerator to arduino uno ? And also send me wiring diagram?

0 Upvotes

r/ArduinoProjects • • Aug 14 '24

Can Arduino Uno handle to control big stepper motor with driver while receiving feedback from a rotary encoder?

0 Upvotes

I'm working on an inversed pendulum, trying to implement PID control and the only microcontroller I can get my hands on is an Arduino UNO. Is there a way that I can make that work or not? If I could how? I'm working with only a Nema 24, DMA860H driver, and E6B2-CWZ6C rotary encoder. I would appreciate if someone could help me here.

I'm just trying to make the stepper work and that has already been exhausting, I tried GRBL software and after some time it works, but the problem is that it has already consumed a lot of memory of the UNO and i can't make it work with an encoder, also after some research here, I could tell that you can't do it with GRBL. The encoder has a resolution of 1000 ppr. If you need more info about the problem let me know.


r/ArduinoProjects • • Feb 22 '24

ESP32-Cam Face Recognition

0 Upvotes
I have this code that uses an ESP32-CAM for face recognition and when a smile is detected it takes a capture and sends it to my phone via Line notifications. I want to modify the code so that it sends a capture via Line when a face is detected. Can I have some help please?
 //Line Notify (Smile)
    if (P1=="happy" || P1=="neutral" || P1=="sad" || P1=="angry" || P1=="fearful"  || P1=="disgusted"|| P1=="surprised") {
      Serial.println("");
      sendCapturedImage2LineNotify(lineNotifyToken);
    }
  } else if (cmd=="resetwifi") {  //重設網路連線  
    for (int i=0;i<2;i++) {
      WiFi.begin(P1.c_str(), P2.c_str());
      Serial.print("Connecting to ");
      Serial.println(P1);
      long int StartTime=millis();
      while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          if ((StartTime+5000) < millis()) break;
      } 
      Serial.println("");
      Serial.println("STAIP: "+WiFi.localIP().toString());
      Feedback="STAIP: "+WiFi.localIP().toString();

      if (WiFi.status() == WL_CONNECTED) {
        WiFi.softAP((WiFi.localIP().toString()+"_"+P1).c_str(), P2.c_str());
        for (int i=0;i<2;i++) {    //若連不上WIFI設定閃光燈慢速閃爍
          ledcWrite(4,10);
          delay(300);
          ledcWrite(4,0);
          delay(300);    
        }
        break;
      }
    }
  } else if (cmd=="framesize") {
    int val = P1.toInt();
    sensor_t * s = esp_camera_sensor_get(); 
    s->set_framesize(s, (framesize_t)val);    
  } else if (cmd=="quality") { //畫質
    sensor_t * s = esp_camera_sensor_get();
    s->set_quality(s, P1.toInt());     
  } else if (cmd=="contrast") {  //對比
    sensor_t * s = esp_camera_sensor_get();
    s->set_contrast(s, P1.toInt());          
  } else if (cmd=="brightness") {  //亮度
    sensor_t * s = esp_camera_sensor_get();
    s->set_brightness(s, P1.toInt());   
  } else if (cmd=="saturation") {  //飽和度
    sensor_t * s = esp_camera_sensor_get();
    s->set_saturation(s, P1.toInt());          
  } else if (cmd=="special_effect") {  //特效
    sensor_t * s = esp_camera_sensor_get();
    s->set_special_effect(s, P1.toInt());  
  } else if (cmd=="hmirror") {  //水平鏡像
    sensor_t * s = esp_camera_sensor_get();
    s->set_hmirror(s, P1.toInt());  
  } else if (cmd=="vflip") {  //垂直翻轉
    sensor_t * s = esp_camera_sensor_get();
    s->set_vflip(s, P1.toInt());  
  } else {
    Feedback="Command is not defined.";
  }
  if (Feedback=="") Feedback=Command;  
}

//拆解命令字串置入變數
void getCommand(char c)
{
  if (c=='?') ReceiveState=1;
  if ((c==' ')||(c=='\r')||(c=='\n')) ReceiveState=0;
  
  if (ReceiveState==1)
  {
    Command=Command+String(c);
    
    if (c=='=') cmdState=0;
    if (c==';') strState++;
  
    if ((cmdState==1)&&((c!='?')||(questionstate==1))) cmd=cmd+String(c);
    if ((cmdState==0)&&(strState==1)&&((c!='=')||(equalstate==1))) P1=P1+String(c);
    if ((cmdState==0)&&(strState==2)&&(c!=';')) P2=P2+String(c);
    if ((cmdState==0)&&(strState==3)&&(c!=';')) P3=P3+String(c);
    if ((cmdState==0)&&(strState==4)&&(c!=';')) P4=P4+String(c);
    if ((cmdState==0)&&(strState==5)&&(c!=';')) P5=P5+String(c);
    if ((cmdState==0)&&(strState==6)&&(c!=';')) P6=P6+String(c);
    if ((cmdState==0)&&(strState==7)&&(c!=';')) P7=P7+String(c);
    if ((cmdState==0)&&(strState==8)&&(c!=';')) P8=P8+String(c);
    if ((cmdState==0)&&(strState>=9)&&((c!=';')||(semicolonstate==1))) P9=P9+String(c);
        const aiView = document.getElementById('stream')
        const aiStill = document.getElementById('get-still')
        const canvas = document.getElementById('canvas')     
        var context = canvas.getContext("2d");  
        const message = document.getElementById('message');
        const uart = document.getElementById('uart');
        const chkResult = document.getElementById('chkResult');
        const probability = document.getElementById('probability')
        var res = "";

        //Model: https://github.com/fustyles/webduino/tree/master/TensorFlow/Face-api
        const modelPath = 'https://fustyles.github.io/webduino/TensorFlow/Face-api/';
        let currentStream;
        let displaySize = { width:320, height: 240 }
        let faceDetection;
        
        Promise.all([
          faceapi.nets.tinyFaceDetector.load(modelPath),
          faceapi.nets.faceLandmark68TinyNet.load(modelPath),
          faceapi.nets.faceRecognitionNet.load(modelPath),
          faceapi.nets.faceExpressionNet.load(modelPath),
          faceapi.nets.ageGenderNet.load(modelPath)          
        ]).then(function(){
          message.innerHTML = "";
          aiStill.click();
        })  
        
        async function DetectImage() {
          canvas.setAttribute("width", aiView.width);
          canvas.setAttribute("height", aiView.height);
          context.drawImage(aiView, 0, 0, aiView.width, aiView.height); 
          if (!chkResult.checked) message.innerHTML = "";
                
          const detections = await faceapi.detectAllFaces(canvas, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks(true).withFaceExpressions().withAgeAndGender()
          const resizedDetections = faceapi.resizeResults(detections, displaySize)
          faceapi.draw.drawDetections(canvas, resizedDetections)
          faceapi.draw.drawFaceLandmarks(canvas, resizedDetections)
          faceapi.draw.drawFaceExpressions(canvas, resizedDetections)
          resizedDetections.forEach(result => {
            const { detection,expressions,gender,genderProbability,age } = result
            //message.innerHTML = JSON.stringify(result);

            res = "";
            var i=0;
            var maxEmotion="neutral";
            var maxProbability=expressions.neutral;
            if (expressions.happy>maxProbability) {
              maxProbability=expressions.happy;
              maxEmotion="happy";
            }
            if (expressions.sad>maxProbability) {
              maxProbability=expressions.sad;
              maxEmotion="sad";
            }
            if (expressions.angry>maxProbability) {
              maxProbability=expressions.angry;
              maxEmotion="angry";
            }
            if (expressions.fearful>maxProbability) {
              maxProbability=expressions.fearful;
              maxEmotion="fearful";
            }
            if (expressions.disgusted>maxProbability) {
              maxProbability=expressions.disgusted;
              maxEmotion="disgusted";
            }
            if (expressions.surprised>maxProbability) {
              maxProbability=expressions.surprised;
              maxEmotion="surprised";
            }

            if (uart.checked) {
              //當可能性最大的表情是happy時
              //if ((maxEmotion=="happy"||maxEmotion="neutral"||maxEmotion="sad" ||maxEmotion="angry" ||maxEmotion="fearful" ||maxEmotion="disgusted" ||maxEmotion="surprised")&&maxProbability>=Number(probability.value)) {
              if (maxEmotion=="happy" &&maxProbability>=Number(probability.value)) {
                var query = document.location.origin+'?uart='+maxEmotion;
                fetch(query)
                  .then(response => {
                    console.log(`request to ${query} finished, status: ${response.status}`)
                  })              
              }
            }
            
            res+= i+",age,"+Math.round(age)+",gender,"+gender+",genderProbability,"+Math.round(genderProbability)+",emotion,"+maxEmotion+",neutral,"+Math.round(expressions.neutral)+",happy,"+Math.round(expressions.happy)+",sad,"+Math.round(expressions.sad)+",angry,"+Math.round(expressions.angry)+",fearful,"+Math.round(expressions.fearful)+",disgusted,"+Math.round(expressions.disgusted)+",surprised,"+Math.round(expressions.surprised)+",boxX,"+Math.round(detection._box._x)+",boxY,"+Math.round(detection._box._y)+",boxWidth,"+Math.round(detection._box._width)+",boxHeight,"+Math.round(detection._box._height)+"<br>";
            i++;        
            new faceapi.draw.DrawTextField(
              [
                `${faceapi.round(age, 0)} years`,
                `${gender} (${faceapi.round(genderProbability)})`
              ],
              result.detection.box.bottomRight
            ).draw(canvas)
          })
          
          if (chkResult.checked) message.innerHTML = res;
          aiStill.click();
        }
        
        aiView.onload = function (event) {
          try { 
            document.createEvent("TouchEvent");
            setTimeout(function(){DetectImage();},250);
          } catch(e) { 
            setTimeout(function(){DetectImage();},150);
          } 
        }
        
        //官方式函式
        function start() {
          var baseHost = 'http://'+document.getElementById("ip").value;  //var baseHost = document.location.origin
   
          const hide = el => {
            el.classList.add('hidden')
          }
          
          const show = el => {
            el.classList.remove('hidden')
          }
        
          const disable = el => {
            el.classList.add('disabled')
            el.disabled = true
          }
        
          const enable = el => {
            el.classList.remove('disabled')
            el.disabled = false
          }
        
          const updateValue = (el, value, updateRemote) => {
            updateRemote = updateRemote == null ? true : updateRemote
            let initialValue
            if(!el) return;
            if (el.type === 'checkbox') {
              initialValue = el.checked
              value = !!value
              el.checked = value
            } else {
              initialValue = el.value
              el.value = value
            }
        
            if (updateRemote && initialValue !== value) {
              updateConfig(el);
            } 
          }
        
          function updateConfig (el) {
            let value
            switch (el.type) {
              case 'checkbox':
                value = el.checked ? 1 : 0
                break
              case 'range':
              case 'select-one':
                value = el.value
                break
              case 'button':
              case 'submit':
                value = '1'
                break
              default:
                return
            }
        
            if (el.id =="flash") {  //新增flash自訂指令
              var query = baseHost+"?flash=" + String(value);
            } else if (el.id =="servo") {  //新增servo自訂指令
              var query = baseHost+"?servo=" + pinServo.value + ";" + String(value);
            } else if (el.id =="relay") {  //新增繼電器自訂指令
              var query = baseHost+"?relay=" + pinRelay.value + ";" + Number(relay.checked);
            } else if (el.id =="uart") {  //新增uart自訂指令
              return;
            } else if (el.id =="probability") {  //新增probability自訂指令
              return;                                          
            } else {
              var query = `${baseHost}/?${el.id}=${value}`
            }
        
            fetch(query)
              .then(response => {
                console.log(`request to ${query} finished, status: ${response.status}`)
              })
          }
        
          document
            .querySelectorAll('.close')
            .forEach(el => {
              el.onclick = () => {
                hide(el.parentNode)
              }
            })
        
          const view = document.getElementById('stream')
          const viewContainer = document.getElementById('stream-container')
          const stillButton = document.getElementById('get-still')
          const enrollButton = document.getElementById('face_enroll')
          const closeButton = document.getElementById('close-stream')
          const stopButton = document.getElementById('stop-still')            //新增stopButton變數
          const restartButton = document.getElementById('restart')            //新增restart變數
          const flash = document.getElementById('flash')                      //新增flash變數
          const servo = document.getElementById('servo')                      //新增servo變數
          const pinServo = document.getElementById('pinServo');               //新增servo pin變數
          const relay = document.getElementById('relay')                      //新增relay變數
          const pinRelay = document.getElementById('pinRelay');               //新增relay pin變數          
          const uart = document.getElementById('uart')                        //新增uart變數
          var myTimer;
          var restartCount=0;    
          var streamState = false;
          
          stopButton.onclick = function (event) {   
            window.stop();
            message.innerHTML = "";
          }    
           
          // Attach actions to buttons
          stillButton.onclick = () => {
            view.src = `${baseHost}/?getstill=${Date.now()}`
            show(viewContainer);     
          }
          
          closeButton.onclick = () => {
            hide(viewContainer)
          }
          
          //新增重啟電源按鈕點選事件 (自訂指令格式:http://192.168.xxx.xxx/?cmd=P1;P2;P3;P4;P5;P6;P7;P8;P9)
          restartButton.onclick = () => {
            fetch(baseHost+"/?restart");
          }    
                
          // Attach default on change action
          document
            .querySelectorAll('.default-action')
            .forEach(el => {
              el.onchange = () => updateConfig(el)
            })
        
          framesize.onchange = () => {
            updateConfig(framesize)
          }
          
          // read initial values  
          fetch(`${baseHost}/?status`)
          .then(function (response) {
            return response.json()
          })
          .then(function (state) {
            document
            .querySelectorAll('.default-action')
            .forEach(el => {
              if (el.id=="flash") {  //新增flash設定預設值0
                flash.value=0;
                var query = baseHost+"?flash=0";
                fetch(query)
                  .then(response => {
                    console.log(`request to ${query} finished, status: ${response.status}`)
                  })
              } else if (el.id=="servo") {  //新增servo設定預設值90度
                servo.value=90;
                /*
                var query = baseHost+"?servo=" + pinServo.value + ";90";
                fetch(query)
                  .then(response => {
                    console.log(`request to ${query} finished, status: ${response.status}`)
                  })
                */
              } else if (el.id=="relay") {  //新增relay設定預設值0
                relay.checked = false;
                /*
                var query = baseHost+"?relay=" + pinRelay.value + ";0";
                fetch(query)
                  .then(response => {
                    console.log(`request to ${query} finished, status: ${response.status}`)
                  })
                */
              } else if (el.id=="uart") {  //新增uart設定預設值0
                uart.checked = false;
              } else if (el.id=="probability") {  //新增probability設定預設值0
                probability.value = 0;                                  
              } else {    
                updateValue(el, state[el.id], false)
              }
            })
          })
        }
        
        //  網址/?192.168.1.38  可自動帶入?後參數IP值
        var href=location.href;
        if (href.indexOf("?")!=-1) {
          ip.value = location.search.split("?")[1].replace(/http:\/\//g,"");
          start();
        }
        else if (href.indexOf("http")!=-1) {
          ip.value = location.host;
          start();
        }
          
    </script>        
    </body>
</html>
)rawliteral";

//設定選單初始值取回json格式
void status(){
  //回傳視訊狀態
  sensor_t * s = esp_camera_sensor_get();
  String json = "{";
  json += "\"framesize\":"+String(s->status.framesize)+",";
  json += "\"quality\":"+String(s->status.quality)+",";
  json += "\"brightness\":"+String(s->status.brightness)+",";
  json += "\"contrast\":"+String(s->status.contrast)+",";
  json += "\"saturation\":"+String(s->status.saturation)+",";
  json += "\"special_effect\":"+String(s->status.special_effect)+",";
  json += "\"vflip\":"+String(s->status.vflip)+",";
  json += "\"hmirror\":"+String(s->status.hmirror);
  json += "}";
  
  client.println("HTTP/1.1 200 OK");
  client.println("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
  client.println("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
  client.println("Content-Type: application/json; charset=utf-8");
  client.println("Access-Control-Allow-Origin: *");
  client.println("Connection: close");
  client.println();
  
  for (int Index = 0; Index < json.length(); Index = Index+1024) {
    client.print(json.substring(Index, Index+1024));
  }
}

void mainpage() {
  //回傳HTML首頁或Feedback
  client.println("HTTP/1.1 200 OK");
  client.println("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
  client.println("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
  client.println("Content-Type: text/html; charset=utf-8");
  client.println("Access-Control-Allow-Origin: *");
  client.println("Connection: close");
  client.println();
  
  String Data="";
  if (cmd!="")
    Data = Feedback;
  else
    Data = String((const char *)INDEX_HTML);
  
  for (int Index = 0; Index < Data.length(); Index = Index+1024) {
    client.print(Data.substring(Index, Index+1024));
  } 
}

void getStill() {
  //回傳JPEG格式影像
  camera_fb_t * fb = NULL;
  fb = esp_camera_fb_get();  
  if(!fb) {
    Serial.println("Camera capture failed");
    delay(1000);
    ESP.restart();
  }

  client.println("HTTP/1.1 200 OK");
  client.println("Access-Control-Allow-Origin: *");              
  client.println("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
  client.println("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
  client.println("Content-Type: image/jpeg");
  client.println("Content-Disposition: form-data; name=\"imageFile\"; filename=\"picture.jpg\""); 
  client.println("Content-Length: " + String(fb->len));             
  client.println("Connection: close");
  client.println();
  
  uint8_t *fbBuf = fb->buf;
  size_t fbLen = fb->len;
  for (size_t n=0;n<fbLen;n=n+1024) {
    if (n+1024<fbLen) {
      client.write(fbBuf, 1024);
      fbBuf += 1024;
    }
    else if (fbLen%1024>0) {
      size_t remainder = fbLen%1024;
      client.write(fbBuf, remainder);
    }
  }  
  esp_camera_fb_return(fb);

  pinMode(4, OUTPUT);
  digitalWrite(4, LOW);              
}

String sendCapturedImage2LineNotify(String token) {
  camera_fb_t * fb = NULL;
  fb = esp_camera_fb_get();  
  if(!fb) {
    Serial.println("Camera capture failed");
    delay(1000);
    ESP.restart();
    return "Camera capture failed";
  }
   
  WiFiClientSecure client_tcp;
  client_tcp.setInsecure();   //run version 1.0.5 or above
  Serial.println("Connect to notify-api.line.me");
  if (client_tcp.connect("notify-api.line.me", 443)) {
    Serial.println("Connection successful");
    
    String message = "ESP32-CAM";
    String head = "--Taiwan\r\nContent-Disposition: form-data; name=\"message\"; \r\n\r\n" + message + "\r\n--Taiwan\r\nContent-Disposition: form-data; name=\"imageFile\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
    String tail = "\r\n--Taiwan--\r\n";

    uint16_t imageLen = fb->len;
    uint16_t extraLen = head.length() + tail.length();
    uint16_t totalLen = imageLen + extraLen;
  
    client_tcp.println("POST /api/notify HTTP/1.1");
    client_tcp.println("Connection: close"); 
    client_tcp.println("Host: notify-api.line.me");
    client_tcp.println("Authorization: Bearer " + token);
    client_tcp.println("Content-Length: " + String(totalLen));
    client_tcp.println("Content-Type: multipart/form-data; boundary=Taiwan");
    client_tcp.println();
    client_tcp.print(head);
    
    uint8_t *fbBuf = fb->buf;
    size_t fbLen = fb->len;
    for (size_t n=0;n<fbLen;n=n+1024) {
      if (n+1024<fbLen) {
        client_tcp.write(fbBuf, 1024);
        fbBuf += 1024;
      }
      else if (fbLen%1024>0) {
        size_t remainder = fbLen%1024;
        client_tcp.write(fbBuf, remainder);
      }
    }  
    
    client_tcp.print(tail);
    esp_camera_fb_return(fb);

    String getResponse="",Feedback="";
    int waitTime = 10000;   // timeout 10 seconds
    long startTime = millis();
    boolean state = false;
    
    while ((startTime + waitTime) > millis()) {
      Serial.print(".");
      delay(100);      
      while (client_tcp.available())  {
          char c = client_tcp.read();
          if (state==true) Feedback += String(c);        
          if (c == '\n') {
            if (getResponse.length()==0) state=true; 
            getResponse = "";
          } 
          else if (c != '\r')
            getResponse += String(c);
          startTime = millis();
       }
       if (Feedback.length()>0) break;
    }
    Serial.println();
    client_tcp.stop();
    return Feedback;
  }
  else {
    return "Connected to notify-api.line.me failed.";
  }
}

r/ArduinoProjects • • Mar 07 '24

the LCD is not displaying the program

Post image
0 Upvotes

I tried adjusting the screw on i2c but it didn't help what's wrong here? please guide.


r/ArduinoProjects • • Mar 12 '24

Arduino based kit for espresso machine

0 Upvotes

I'm doing a 3D printed kit based on arduino to make a conventional espresso machine into a smart one. Should I keep going?

22 votes, Mar 14 '24
17 Yes!
5 Nooo... that's a dumb idea

r/ArduinoProjects • • Feb 21 '24

PIR sensor and servo project

0 Upvotes

Hi there, I'm an arduino and esp32 user that recently got a lil fed up with programming so tried to make projects but using only "pure" electronics and not programmable microcontrollers like the ones ive mentiones before, formally speaking actually i dont know anything abt electronics, just random concepts that wander through the corners of my mind but nothing really seriuos and i wanted to do a project where basically when a PIR sensor detects movement move a servo to 180° and when there's no motion detected it goes back to 0°, I dont know what to use, how to connect the pins of everything, etc(consider when i said that i formally dont know anything thati really dont know anything about connections and general)this is really drilling my head rn and i was wondering if there is any saint come down from heaven that could help me with😭😭😔.

Sorry for the huge will😔, thanks for reading and for any help


r/ArduinoProjects • • Mar 21 '24

Troubleshooting distance sensors, rotary encoder, and LCD display in Arduino project

0 Upvotes

Hello,

I'm currently working on an Arduino project where I'm encountering several issues with my code. Here's a brief overview:

Problem 1: Distance Sensors Not Reading My ultrasonic distance sensors (SR04) aren't providing any distance readings. I've checked the wiring and connections, but still no luck. Any insights on what might be causing this issue?

Problem 2: Rotary Encoder Not Functioning as Expected I'm using a rotary encoder to adjust values (groente1

and groente2

), but it seems like the values are changing without any input from the encoder. How can I troubleshoot this and ensure the encoder is working correctly?

Problem 3: LCD Display Refreshing Unnecessarily The LCD display seems to be refreshing even when there are no changes in the values displayed. This is causing unnecessary flickering on the screen. How can I optimize my code to refresh the display only when necessary?

Here's my code for reference:

#include <Wire.h>

include <LiquidCrystal_I2C.h>

include <Stepper.h>

include "SR04.h"

SR04 s1 = SR04(A1, A0); SR04 s2 = SR04(A3, A2);

LiquidCrystal_I2C lcd(0x27, 16, 2);

int groente1 = 0; int groente2 = 0;

int distanceSensor1; int distanceSensor2;

const int rightDistance = 5;

const int buttonPin = 6; const int encoderPinA = 7; const int encoderPinB = 8; const int stepSize = 50; const int stepsPerRevolution = 1500;

int delayTime;

Stepper M1(stepsPerRevolution, 9, 10, 11, 12); Stepper M2(stepsPerRevolution, 2, 3, 4, 5);

enum adjustState { GROENTE1, GROENTE2, DISPENSING };

adjustState currentState = GROENTE1;

bool displayChange = false; bool finished = false;

void setup() { Serial.begin(9600); pinMode(A0,INPUT); pinMode(A1,INPUT); pinMode(A2,INPUT); pinMode(A3,INPUT); pinMode(A4,OUTPUT); pinMode(A5,OUTPUT); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, INPUT); pinMode(7, INPUT); pinMode(8, INPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); lcd.init(); lcd.backlight(); lcd.setCursor(0, 1); lcd.setCursor(0, 0); lcd.print('hallo'); Serial.begin(9600); delay(5000); }

void loop() { lcd.clear(); lcd.print("Groente 1: "); lcd.print(groente1); lcd.print("G"); lcd.setCursor(0, 1); lcd.print("Groente 2: "); lcd.print(groente2); lcd.print("G");

int lastValue1 = groente1; int lastValue2 = groente2;   distanceSensor1 = s1.Distance();   distanceSensor2 = s2.Distance(); Serial.println(distanceSensor2 + " | " + distanceSensor1); if (currentState == GROENTE1) {     finished = false; if (digitalRead(encoderPinB) == HIGH && groente1 + groente2 + stepSize <= 600 && groente1 - stepSize >= 0) {       groente1 += stepSize; delay(50);     } if (digitalRead(encoderPinA) == HIGH) {       groente1 -= stepSize; delay(50);     } if (digitalRead(buttonPin) == LOW) {       currentState = GROENTE2;       displayChange = true; delay(100);     }   }

if (currentState == GROENTE2) { if (digitalRead(encoderPinB) == HIGH && groente1 + groente2 + stepSize <= 600 && groente2 - stepSize >= 0) {       groente2 += stepSize; delay(50);     } if (digitalRead(encoderPinA) == HIGH) {       groente2 -= stepSize; delay(50);     } if (digitalRead(buttonPin) == LOW) {       currentState = DISPENSING;       displayChange = true; delay(100);     }   }

if (currentState == DISPENSING) { lcd.clear(); lcd.setCursor(0, 0);

if (distanceSensor2 > rightDistance || distanceSensor1 > rightDistance) { lcd.print("plaats uw bakje");     } else { lcd.clear(); lcd.print("dispensing..."); if (groente1 > 0 && distanceSensor1 <= rightDistance && distanceSensor2 <= rightDistance) {         delayTime = groente1 * 1.7; rotateM1(90); delay(delayTime); rotateM1(-90);         finished = true;       } if (groente2 > 0 && distanceSensor2 <= rightDistance) {         delayTime = groente2 * 1.7; rotateM2(90); delay(delayTime); rotateM2(-90);         finished = true;       }     } if (finished) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Haal uw bakje weg");     } if (finished && distanceSensor2 > rightDistance && distanceSensor1 > rightDistance) {       displayChange = true;       currentState = GROENTE1;     }   }

if (lastValue1 != groente1 || lastValue2 != groente2) { lcd.clear(); lcd.print("Groente 1: "); lcd.print(groente1); lcd.print("G"); lcd.setCursor(0, 1); lcd.print("Groente 2: "); lcd.print(groente2); lcd.print("G");   } delay(200);

}

void rotateM1(int degrees) { int stepsToMove = degrees * (stepsPerRevolution / 360); M1.setSpeed(20); M1.step(stepsToMove); }

void rotateM2(int degrees) { int stepsToMove = degrees * (stepsPerRevolution / 360); M2.setSpeed(20); M2.step(stepsToMove); }

Thanks in advance for your help!


r/ArduinoProjects • • Mar 08 '24

How to make a Motorized Skateboard

0 Upvotes

I want to create a motorized skateboardwitbh remote control) for essentially making a Camera dolly substitute for low budget. How do I start?


r/ArduinoProjects • • Feb 23 '24

Projects idea

0 Upvotes

Our university will make an arduino competition project and the most creative project win a prize and Im really confuse what should I make to take advantage on this competition if anyone have a creative idea i will be so grateful. Thanks for ur support.


r/ArduinoProjects • • Mar 28 '24

Raspberry Pi Video Streaming Guide: Create Your Own Local Network Security Camera

0 Upvotes

Hey everyone! I recently put together a step-by-step guide on using a Raspberry Pi to set up a video streaming system within your local network. It's a great project for beginners who want to get started with Raspberry Pi and IoT, and the end result is pretty cool – you'll have your own DIY security camera!

I've created a video tutorial that walks you through the whole process. You can check it out here: https://www.youtube.com/watch?v=qs3KhLDUBmk

Oh, and keep an eye out for part two, where I'll show you how to extend this project to stream video from anywhere, not just within your local network.

If you're interested in learning more about Raspberry Pi and IoT projects, feel free to subscribe to my YouTube channel. And if you have any questions, just leave a comment under the video – I'll do my best to help out.

Thanks for reading, and I hope you find the guide useful!


r/ArduinoProjects • • May 31 '24

Can anyone give me ideas for my next project

0 Upvotes

Please help me in giving ideas for some new and unique projects, i am not able to think about any new project.


r/ArduinoProjects • • Jun 05 '24

esp32 wrooom dev kit 1 and obd 2 adapter

0 Upvotes

I want to create a android app that reads car speed, rpm , fuel level etc.

And is it possible to connect esp-32 and obd adapter to simulate a car? (esp acting like a car)


r/ArduinoProjects • • Jul 10 '24

Control Arduino car from anywhere

0 Upvotes

How can i control Arduino robot car over the internet


r/ArduinoProjects • • May 26 '24

MPU6050 Acts Strange When Roll Limit Is Exceeded

0 Upvotes

I am working with mpu6050 in my project and my axis limits are -180 degrees to +180 degrees. Only when doing the Roll movement reaches -180 or +180 degrees, (when it is upside down) other values (Yaw and Pitch) change exaggeratedly and reach their approximate maximum values. In the upside down position, all 3 values reach approximately (+ or -) 180 degrees. Can you help me, thanks!

Here is some of my codes about mpu6050:

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps612.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#endif
MPU6050 mpu;
#define OUTPUT_READABLE_YAWPITCHROLL
uint8_t mpuIntStatus, devStatus, fifoBuffer[64], teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };
uint16_t packetSize, fifoCount;
bool dmpReady = false;
Quaternion q;                        // [w, x, y, z]         quaternion container
VectorInt16 aa, gy, aaReal, aaWorld;  // [x, y, z]accel sensor measurements   // [x, y, z]  gyro sensor measurements  // [x, y, z] gravity-free accel sensor measurements // [x, y, z] world-frame accel sensor measurements               
VectorFloat gravity;                 // [x, y, z]            gravity vector
float euler[3], ypr[3];              // [psi, theta, phi]    Euler angle container,    // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

void setup() {
  Serial.begin(115200);
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif
  mpu.initialize();
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();
  mpu.setXGyroOffset(51);
  mpu.setYGyroOffset(8);
  mpu.setZGyroOffset(21);
  mpu.setXAccelOffset(1150);
  mpu.setYAccelOffset(-50);
  mpu.setZAccelOffset(1060);
  if (devStatus == 0) {
    mpu.CalibrateAccel(6);
    mpu.CalibrateGyro(6);
    Serial.println();
    mpu.PrintActiveOffsets();
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);
    Serial.println(F(")..."));
    mpuIntStatus = mpu.getIntStatus();
    dmpReady = true;
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }
}

void loop() {
  if (!dmpReady) return;
  if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) {
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[2] * 180 / M_PI);
    Serial.println();

#endif
  }
}

r/ArduinoProjects • • Jun 26 '24

ESP32-CAM_MJPEG2SD issue

Post image
0 Upvotes

For context I’m trying to make a portable camera using s60sc’s code however when compiling his “globals.h” the error in the image occurs

NOTE: I have not yet connected the ESP32 cam to the laptop, I’m hoping that’s the issue but if it’s not can any of you lot please help me to fix this issue, THANKS!


r/ArduinoProjects • • Jun 17 '24

Barcode scanner communication suspended

0 Upvotes

Hey guys while connecting the barcode to my mega with USB host Shield the barcode scanner runs into usb disabled mode or the communication is suspended, the same happens with the other scanner I tried can anyone help me with this ??


r/ArduinoProjects • • Jun 29 '24

ESP32 cam output error

Post image
0 Upvotes

So after finally completing ALL the steps to programming the camera im now on the final step where i must retrieve a set of numbers from the serial monitor. Only one issue… the serial monitor’s output is in unrecognisable hyrogliphics 😭 what do i do?


r/ArduinoProjects • • Jun 19 '24

why isn't my motor turning on?

0 Upvotes

So, I'm new to Arduino coding, robotics, etc. So far, I can turn on and off LEDS, create patterns with them, and do all the basics. So, I decided to take it up a notch and learn to work with IR infrared obstacle avoidance sensors. I want to turn off my motor once the sensor detects a black line, but remains on when there is no line. However, whether the sensor detects the black line or not, the motor does not turn on. Can anyone tell me what I'm doing wrong?

Here is a copy of my code

int IRsensorVal;
int IRsensorPin=A4;
int motor=5;
 



void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(IRsensorPin,INPUT);
  pinMode(motor,OUTPUT);

}

void loop() {
  IRsensorVal=analogRead(IRsensorPin);
  Serial.println(IRsensorVal);
  delay(250);

  if(IRsensorVal<50){
    digitalWrite(motor,HIGH);
  }//no black line detected turn on motor 

  if(IRsensorVal>1000){
    digitalWrite(motor,LOW);
  }// black line detected turn off motor 

  // put your main code here, to run repeatedly:
}

And here's a photo of my sent up:

the IRsensorVal<50 mean no black line :

And the IRsensorVal>1000 means black line:


r/ArduinoProjects • • Jun 04 '24

Controlling temperature using Arduino.

0 Upvotes

Hello, I'm working on a project due in about a week and really need help. I don't have anything but the Arduino and need to find a way to control the current it delivers to control temperature. Is that possible?


r/ArduinoProjects • • Jun 02 '24

SIM808 Module (GSM/GPS) with Raspberry Pi 4

Post image
0 Upvotes

Hello friends

I kindly ask for your assistance with my current project. I'm working on an IoT project that involves bus tracking and try to get longitude and latitude coordinates. However, I'm encountering difficulties with the SIM808 (GSM/GPS) module, when using a Raspberry Pi 4. Here are some of the issues I'm facing:

Module Not Responding to AT Commands:

On Raspberry Pi 4, I'm unable to send AT command , when I enter to picocom it doesn't give me possibility to write AT command so I can't send it .

Raspberry Pi 4 Model B Setup:

I have connected the Raspberry Pi and SIM808 module as follows:

Raspberry Pi SIM808

GND (pin 6) —-> GND

Tx (pin8/GPIO 14) —-> Rx

Rx (pin10/GPIO 15) —-> Tx

Power source: A 12V, 1A to the SIM808 module, with GSM and GPS antennas. Also I try to use 12V, 2A power source ( does the voltage and amperage necessary in this case ?! )

I've attempted to start the module by pressing the button for 3 seconds.

Terminal Emulator Issue:

The terminal emulator (picocom) is not accepting keyboard inputs as it used to. Previously, these commands yielded responses:

AT —> “OK” ( I can't receive this response to complete )

SIM Card and LED Status:

It's unclear if the SIM808 module is reading the SIM card. The LED on the module blinks fast every second instead of every three seconds. Additionally, I'm unsure if the SIM card requires prepaid SMS. The SIM card is registered and functional.

I've been troubleshooting for about 3 days now and would greatly appreciate any assistance you can provide. Thank you in advance!


r/ArduinoProjects • • Jun 10 '24

Hi everyone new to Arduino (used once)

0 Upvotes

Hi all,

I need to build something similar like the one in below in link can any experts help me out please.

https://www.facebook.com/share/v/bss3AyE1S18jUsBp/?mibextid=xfxF2i

Thanks


r/ArduinoProjects • • Jul 03 '24

Motor with feedback?

0 Upvotes

Hello,

Do anybody know what kind of motor/control is used in this video, i want to make something similar of my own. Thank you.

https://youtube.com/shorts/cSWRUvMrhIM?si=82Rv3PeWUI5xpEri