text:
How to trigger NodeMCU sketch from Arduino Leonardo Micro Pro?
So this is probably a very simple question. I have my NodeMCU set up and working where it connects to wifi and sends a push notification. Currently it does that automatically when connected to power.
What I want to do is connect it to my Leonardo Micro so that at a part in the Leonardo sketch it sends a signal to the NodeMCU to run the sketch to trigger the push notification. So simply, which ports should I connect and what code should I change.
Here is my working NodeMCU code.
    #include <ESP8266WiFi.h>

// Wifi Settings
const char* ssid = "MySSID";
const char* password = "MyPassword";
// Pushover settings
char pushoversite[] = "api.pushover.net";
char apitoken[] = "MyAPIToken";
char userkey [] = "MyUserKey";
int length;
WiFiClient client;
void setup() {
  Serial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print the IP address
  Serial.print(WiFi.localIP());

}

void loop()
{
 pushover("OMG, Yes it works!!!");
 delay(60000);
}

byte pushover(char *pushovermessage)
{
 String message = pushovermessage;

 length = 81 + message.length();

if(client.connect(pushoversite,80))
 {
   client.println("POST /1/messages.json HTTP/1.1");
   client.println("Host: api.pushover.net");
   client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.print(length);
   client.println("\r\n");;
   client.print("token=");
   client.print(apitoken);
   client.print("&user=");
   client.print(userkey);
   client.print("&message=");
   client.print(message);
   while(client.connected())
   {
     while(client.available())
     {
       char ch = client.read();
       Serial.write(ch);
     }
   }
   client.stop();
 }
}

And my Leonardo code
#include <Keyboard.h>
#include <Mouse.h>
char returnKey = KEY_RETURN;
char tabKey = KEY_TAB;
void setup() {
  Keyboard.begin();
  Mouse.begin();

  delay(4000); //Testing Delay
// Language Select Screen
  Keyboard.write(returnKey);
  delay(30000);
// Welcome Screen
  Mouse.click(MOUSE_LEFT);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
// Select Keyboard
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
  TELL NODEMCU TO SEND PUSH NOTIFICATION HERE
}

void loop() {
}

As a reminder the pinout on my boards are as follows.
Leonardo:

NodeMCU:

First make it work from a button. Then replace the button with the Leonardo.

HW part:
It's like button, simply connect arduino micro pin to nodeMCU pin and GND of arduino to GND of nodeMCU.
It's also good idea to use two resistors as voltage divider because arduino micro works with 5V and ESP8266 (nodeMCU) with 3V3. 5V can destroy ESP8266 but this thing is still not really clear.
Resistor divider connect as in this link link about resistor divider for uart but instead of TX put arduino micro and instead of RX nodeMCU.
resistor divider schematic

Code part:
On the arduino micro part use:

In void setup():
pinMode(PIN, OUTPUT);

In your marked place:

digitalWrite(PIN, HIGH);
delay(100);   //short wait time
digitalWrite(PIN, LOW);

nodeMCU part:

In void setup():
pinMode(PIN, INPUT);

Remove everything from void loop() and put there this:

if(digitalRead(PIN) == 1) pushover("OMG, Yes it works!!!");

In both codes select the PIN according to your choice.

Thanks Matej, exactly what I was looking for and I think i'm beginning to understand things a bit more now too. Resisters are still something I need to read up on. I'd bought a rechargeable battery shield I was going to use to power the mini and the NodeMCU but I guess even if it's powered that way I still need the resister between the digital pins?

@DannyShepherd Resistor is simple thing, it causes voltage drop which you can calculate from ohm law (U = R*I). In this case it's not so simple because we are working with mcu pins which current consumption is really low - few micro amps.

@DannyShepherd If we want to put 5V logic to 3V3 logic, we need to have voltage drop 1.7V (5-3.3) on first resistor, that means on second resistor will be voltage drop 3V3 (between nodeMCU pin and GND). But why two resistor? Because if you use just one, current is so small that value of resistor will be so big to achieve voltage drop equal to 1.7V. So we simple take two resistor in series and they can create proper current. We can apply formula U1/U2 = R1/R2 which came from using ohm law and then trim current from it because in serial connection current is same.

@DannyShepherd So if both arduinos will have same voltage level you don't have to use voltage divider or level shifter. Als some MCUs are 5V tolerant but specially ESP8266 is not or it's not still clear. So is this answer for your question? :)

Hey @Matej, that's really well explained thanks. Just picked up a back of resisters so I will play around with this and hopefully not fry any boards!
Just to double check something if I have a shield that powers the Leonardo with 5v and the NodeMCU with 3.3v - the digital pinout from the Arduino would still try to send 5V down as well (and thus need the resister) I assume so, just checking the basics of the current flow. Thanks!

@DannyShepherd Yeah, if Leonardo is powered with 5V you will still need voltage divider from two resistors.

a little off the original topic here, but I just check my recharageble shield I want to use to power and it only had 5v out. So I presume I can wire it direct to my Pro Micro VCC port, and then I can take from the same output to the NodeMCU but use the resistors to make it 3.3v correct?

@DannyShepherd Yes but keep in my to do not power ESP8266 with 5V, you have to use stabilizer which boards like nodeMCU have included onboard. On nodeMCU you can put 5V to VIN pin, I think. And yes, for converting logic level 5V to 3V3 use resistor voltage divider.

ah I didn't know that, ok that makes life a little easier then. So just to double check the way to do it would be, for example. Pin 5 out on the Pro Micro to Pin 5 on the nodeMCU with a 10kOhm resister in better and ground on each board connected together with a 20kOhm resister in between?

@DannyShepherd I don't know if you mean this but GND will be directly connected to GND and between digital pins you will have one resistor and second between nodeMCU and GND.

Hi Matej, I got this working, one change I needed to make to the code though was to have the MCU have pinMode(PIN, INPUT); instead of OUTPUT. (Oh and I used a logic level shifter board in the end for the 5v to 3.3v to be a bit safer)

@DannyShepherd Hey, great! You are right, I had mistake in my answer. Edited.


text:
random soft wdt reset while request
i am making post requests with esp8266 on nodeMCU. i have a messy code so i dont want to annoy you with showing it here. the problem is i get soft wdt reset time to time while making request. for example i change piece of code(removing or adding some serial.println lines) and i see i get soft wdt reset right there in http.post.
i tried my best to avoid Strings. I only used a few times, without in the loop. I am only using WiFiClientSecureBearSSL with FirebaseESP8266.
do you have any idea what cause this problem?

How are you powering the board?

with usb. i am not using without cable yet i am still dealing with these resets.

Connected direct you your computer? Not through an unpowered hub?

It is connected directly to the usb port. Why is there something wrong with it?

No. Quite the opposite. I have seen WDT timeouts when the board has been under-powered, but that's not the case here.

yeah. my problem is more like random here. i get wdt resets at diffrent requests. i thought maybe stack or heap reach each other but that is not related to soft wdt reset, is it?

It was the randomness that made me think power. But that's unlikely. A watchdog timeout could be caused by anything than makes execution go wrong.

Can usage of strings a few times cause memory fragmentation? Those Strings size are less than 100 characters.

Show examples of the error - and install ESPexeption decoder to analyse the stack trace this will at least show why the wdt was caused
So the only thing as of now I can recommend
There is an issue with bearssl:
It's a WDT error caused by an extended SSL negotiation.

Change the core frequency to 160MHz (if not already done) and try again.
Use instead of LWIP1.4 (memory hog) low-mem LWIP2.0 with your program.
Since SSL negotiation can take 5 seconds even at 160MHz for some websites be sure by adding a yield() not to trigger a wdt reset

So without code/ trace and error messages its hard to guess

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How to find the time of any point on the graph on an Arduino serial plotter or Processing software?
I am plotting the graph of some sensor values on my Arduino serial plotter which looks something like this -
But what I want to do is hover over any point on the graph and display the time at that point. Is there any way to do that, if not with Arduino serial plotter, with Processing? Or any other tool is fine too. Thanks.

The Arduino Serial Plotter is not meant for this. It just directly draws, what you send. You can solve this in processing, by calculating the time from the number of the current sample (which is what you see on the x axis in your plot) via the used sampling rate.

Can I use the system time for this? I just want to find the difference between the time period of each crest or trough of the blue and red waveforms respectively. I have done it using my code but I want to verify it graphically.

What do you mean by "the system"? You want to plot the data on your PC. Processing is a tool, that is made for such situations. The difference between the plot above and what you want is just a simple factor multiplied to the x axis value: the sampling rate

why do you need system time? ... you said that you want to determine a time interval between two points

I just want to find the difference between the time period of each crest Arduino can do that for you as well

@DataFiddler >I have done it using my code but I want to verify it graphically.. I think his goal is to have a graphical useable plotter.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to print stack trace and register dumps on arduino serial monitor?
I want to debug my ESP32 module which is giving an exception using ESP32 exception decoder, but for that, I would need to have access to my stack trace to paste it. But currently, my arduino serial monitor does not print the stack trace. (as shown below)

But I would need stack trace to be printed, like in the below image to debug my exception. How can I print it on the serial monitor?

I think you will need to have access to the processor's debug port such as JTAG.  And likely you will need the particular processor's actual IDE and HW programmer.  The Arduino IDE was supposed to be simple and easy to use for learning.  But I would be interested to know if there are clever ways to get register and call stack information while only using the Arduino IDE.

The second image is on my friend's setup. He is using Arduino IDE too. Also, there are videos on how to use esp exception stack using Arduino, but I'm not sure how they are getting the stack information.

...I have not used an ESP32 yet.  I see what you are talking about.  Guessing, your friend has triggered some built in debugging capabilities of the ESP32's Arduino code on the ESP32.  Further guessing, if you run your friend's code I bet you will get the same debugging output.  Last guess, if this is a SW feature of the ESP32's Arduino code, it may be possible your program breaks in such a way or is running successfully as to not produce the debug information.

Got the required trace logs at the output. All I had to do was enable PSRAM in tools.


text:
Is there an Apple Silicon (M1) driver for CH34x devices?
I just migrated to a new computer running on an M1 CPU (the new Apple Silicon, arm64 based). I've been searching for CH34x drivers for my TTGO-Lora32 board, but can't find any around, nor can I find mentions of them existing or not. The x86_64 driver installs, but obviously can't run due to it being an incompatible architecture.
Thus, is it currently possible to use a CH34x based board on an M1 Mac?

Turns out there is such driver, but it hasn't been listed yet on the WCH website. I've posted it down below in a new answer.

It isn't working for me on Monterey. I've tried all the versions installing and uninstalling. It simply doesn't work. No idea why.

As it turns out, I found in the following post:
https://github.com/LilyGO/LILYGO-T-OI/issues/3#issuecomment-907645945
a link to a particular build of the CH340 drivers that is properly signed and can be installed on the M1 mac with no troubles.

Nice find. Now if only it were listed officially on the CH340 website so people could actually find it. Maybe now it's here it may get more attention from GoogleBot...

So they pushed a new version to GitHub late september:
https://github.com/WCHSoftGroup/ch34xser_macos
This should be the maintained version ahead of what they offer as a download on the official website.
Common other issues:

When reinstalling, make sure to first remove all old files:

sudo rm –rf /var/db/receipts/*CH34xVCPDriver*.*
sudo rm -rf /Library/Extensions/CH34xVCPDriver.kext

also don't forget to check for any related files in /dev/ and the .app file in your applications folder if these already exist.

Restart the device before reinstalling.

Restart the device after installation.

Try a different USB-Cable / USB-Hub.

Note: steps listed here were reportedly solutions I came across during my research which worked for other people and my colleagues. For me it still doesn't work; but I am using a lot of unstable builds for my OS and other software that might interfere.
Update February 2022: Now with Monterey out of closed Beta this works like a charm for me. At least for the Web IDE.

The installer is still requiring Rosetta 2, which makes me worried about the implementation of the driver. Although it might work, it is probably not written for M1 silicon.

After hours of mindless reinstalling of the drivers on M1, reboots and other magic tricks, I almost decided to switch to windows to make my arduino ide work. My NodeMCU board with CH340G would either show up as a serial port or not.
So I leave this message here as clearly many people struggling with M1 end up on this page: buy good microUSB cable. And I mean a good one. All problems disappeared right away. I had three cables at home but none was working - clearly most are only good for charging the phone, but suck at data transfer.

Indeed! In my experience, microUSB cables are the most likely to not work as expected.

✅ I can attest to this: you need a "data" cable not just a "charging cable". I tried 2 different cables that are just for charging, then I got a data cable and it worked immediately.

Big true, I just grab another microUSB cable and all works smoothly. cu.usbserial-210 port appeared right away.

The bad cables was indeed the culprit... thanks!

Worth the try. The .pkg file from here worked in my High Sierra. I've turned-on the "csrutil enable" before install, and it still worked...:
https://github.com/WCHSoftGroup/ch34xser_macos

High Sierra is not compatible with M1 macs


text:
Problem with printing keypad input to the LCD in a while loop
this is my first post here, though I have been following this forum for a while (pun intended). I am trying to write a program for a machine that will drill holes in a metal rail, and cut the rail to the desired length. This is a home project, but I am starting to think that it is a bit much for the arduino. I hope I'm wrong.
Case 1 is used to enter the length of the rail. Case 2 is used to enter the number of big holes that need to be drilled in a rail, after that it goes to Case 3 where it should, for each hole, ask the user to enter the distance, that means that this part will be in a loop, with a condition that the counter is less or equal to the number of holes. When this is done it should go to Case 4. But the problem appears with Case 3. It seems that the loop (while loop) is creating some troubles. I've tried the program without the while loop ( so basically it only asks once to enter the distance) and it works. I think that maybe the part where I need to print the message "enter the value" and then print the keypad values creates some trouble with the while loop, maybe it slows it down.
I forgot to add, when I upload the program, and I start entering the values with a keypad, as soon as it goes to Case 3, the display prints a bunch of ones (the display fills up with 1s)
Could it be that this is too much for Arduino? Should i try to program it like a regular microcontroller, using arduino IDE but not using arduino commands? What do you think? Please ask if you need some clarification about the code. And thank you in advance.
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
#include<Encoder.h>
#include<Keypad.h>

//definisanje tastera za tastaturu
LiquidCrystal_I2C lcd1(0x27, 16, 2);
LiquidCrystal_I2C lcd2(0x23, 16, 2);
const byte ROWS=4;
const byte COLS=4;
char hexaKeys [ROWS][COLS]={
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {4, 5, 6, 7};
byte colPins[COLS] = {8, 9, 10, 11};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
Encoder myEnc(2,3);

unsigned long currentTime;
unsigned long previousTime2=0;
unsigned long previousTime3=0;
unsigned long previousTime4=0;
unsigned long previousTime5=0;
unsigned long oldTime=0;
int loopTime=5;
String niz1="";
String niz2="";
String niz3="";
String niz4="";
String niz5="";
int duzina;
int br_Vrupa, br_Mrupa;
int state=1;
int debounce=400;
int i=1;
int m=1;
int j,k,n;
int zad_vrV [30], zad_vrM [30];
int start_taster, previous_state; //button that signals the start
int encoder_reading;
int prev_vr;
int zbir;
int error=5;
bool testRange1=true;
bool testRange2=true;
bool testRange3=true;
int machine_start=14; //relay that moves the rail
int relay1=15;  //relay for big holes
int relay2=16;  //relay for small holes
int relay3=17;  //relay for cutting the rail
int dt=2000;

void setup(){
  lcd1.init();  //printing values from the encoder
  lcd2.init();  //printing values from the keypad
  lcd1.backlight();
  lcd2.backlight();
  pinMode(12,INPUT_PULLUP);
  pinMode(machine_start,OUTPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
}

void loop(){
  char keyin=customKeypad.getKey();
  lcd1.setCursor(0,0);
  lcd2.setCursor(0,0);
  currentTime=millis();
  switch (state) {
    case 1:
    lcd2.print("Uneti duzinu:");
    if(keyin){
      if(isDigit(keyin)){   //proverava da li je uneta vrednost neka cifra
      niz1 += (char)keyin;    //od unetih cifara kreira niz
      lcd2.clear();
      lcd2.setCursor(0,1);
      delay(10);
      lcd2.print(niz1);
      duzina=niz1.toInt();     //konvertuje dobijeni niz u broj (int)
      }
      else if (keyin=='#'){
      niz1.remove(0);
      duzina=niz1.toInt();
      lcd2.clear();
      delay(10);
      lcd2.print(duzina);
      }

      if(keyin=='A'){
        state=2;
        lcd2.clear();
        delay(10);
    }
  }
    break;

    case 2:

    lcd2.print("Uneti br V");  //enter the number of big holes
    if(keyin){
      if(isDigit(keyin)){
        niz2+=(char)keyin;
        lcd2.clear();
        delay(10);
        lcd2.setCursor(0,1);
        lcd2.print(niz2);
        br_Vrupa=niz2.toInt();
        }
      else if (keyin=='#'){
        niz2.remove(0);
        br_Vrupa=niz2.toInt();
        lcd2.clear();
        delay(10);
        lcd2.print(br_Vrupa);
    }

    if(keyin=='A'){
        state=3;
        lcd2.clear();
        delay(10);
      }
    }
    break;

    case 3: //this case is used to enter the length to the each big hole

    while(i<=br_Vrupa);{
      j=i-1;
      if(keyin){
        if(isDigit(keyin)){
         niz3+=(char)keyin;
         lcd2.print("enter length ");
         lcd2.print(i);
         delay(10);
         lcd2.print(niz3);
         zad_vrV[j]=niz3.toInt();
        }
        else if (keyin=='#'){
          niz3.remove(0);
          zad_vrV[j]=niz3.toInt();
          lcd2.clear();
          delay(10);
          lcd2.print(zad_vrV[j]);
        }
      }
       if(keyin=='A'){
         i++;
         }
      if(i==br_Vrupa){  //when counter i reaches the br_Vrupa value, switch to the next case
        state=4;
      }
    }

      break;

      case 4:
      lcd2.clear();
      delay(10);
      lcd2.print("Uneti br M"); //enter the number of small holes
      if(keyin){
        if(isDigit(keyin)){
        niz4+=(char)keyin;
        lcd2.clear();
        lcd2.setCursor(0,1);
        delay(10);
        lcd2.print(niz4);
        br_Mrupa=niz4.toInt();
        }
        else if (keyin=='#'){
        niz4.remove(0);
        br_Mrupa=niz4.toInt();
        lcd2.clear();
        delay(10);
        lcd2.print(br_Mrupa);
        }
       if(keyin=='A'){
        state=5;
        lcd2.clear();
        delay(10);
        }
       }
      break;

      case 5: //this case is used to enter the length to the each small hole
      lcd2.clear();
      delay(10);
      while(m <= br_Mrupa){
        lcd2.print("enter length ");
        lcd2.print(m);
        n=m-1;
        if(keyin){
          if(isDigit(keyin)){
          niz5+=(char)keyin;
          lcd2.clear();
          lcd2.setCursor(0,1);
          delay(10);
          lcd2.print(niz5);
          zad_vrM[n]=niz5.toInt();
        }
        else if (keyin=='#'){
          niz5.remove(0);
          zad_vrM[n]=niz5.toInt();
          lcd2.clear();
          delay(10);
          lcd2.print(zad_vrM[n]);
        }

       if(keyin=='A'){
         m++;
        lcd2.clear();
        ;
         }
        }
      break;
  }

}
  start_taster=digitalRead(12);
  if(start_taster==LOW && previous_state==HIGH && currentTime-previousTime2 > debounce){
    previousTime2=currentTime;
    digitalWrite(machine_start,HIGH);
  }
  previous_state=start_taster;
  encoder_reading=(myEnc.read())*446/400;
  if(encoder_reading!=prev_vr){
    lcd1.clear();
    delay(10);
    prev_vr=encoder_reading;
  }
  lcd1.print(encoder_reading);

  zbir=br_Vrupa+br_Mrupa;
  for(k=0;k<zbir;k++){
    if(encoder_reading>=zad_vrV[k] && encoder_reading<zad_vrM[k]-tolerance && encoder_reading>zad_vrM[k]+tolerance && testRange1){
      digitalWrite(machine_start,LOW);
      digitalWrite(relay1,HIGH);
      previousTime3=currentTime;
      testRange1=false;
      if(currentTime-previousTime3 >= dt){
        previousTime3=currentTime;
        digitalWrite(relay1,LOW);
        digitalWrite(machine_start,HIGH);
      }
      if(encoder_reading<(zad_vrV[k]-error) || encoder_reading>=(zad_vrV[k]+error)){
        testRange1=true;
      }
    }
    else if(encoder_reading>=zad_vrM[k] && encoder_reading<zad_vrV[k]-tolerance && encoder_reading>zad_vrV[k]+tolerance && testRange2){
      digitalWrite(machine_start,LOW);
      digitalWrite(relay2,HIGH);
      previousTime4=currentTime;
      testRange2=false;
      if(currentTime-previousTime4 >= dt){
        previousTime4=currentTime;
        digitalWrite(relay2,LOW);
        digitalWrite(machine_start,HIGH);
      }
      if(encoder_reading<(zad_vrM[k]-error) || encoder_reading>=(zad_vrM[k]+error)){
        testRange2=true;
      }
    }
  }
  if(encoder_reading>=duzina && testRange3){
    digitalWrite(relay3,HIGH);
    previousTime5=currentTime;
    testRange3=false;
    if(currentTime-previousTime5>=dt){
      previousTime5=currentTime;
      digitalWrite(relay3,LOW);
    }
    if(encoder_reading<(duzina-error)){
      testRange3=true;
    }
  }
}

you don't read the keyboard in the while loop in case 3. no it is not too much for Arduino. (it is nothing compared to what it can)

I'm not sure what you meant. I thought that this part reads the keypad:
if(keyin){
if(isDigit(keyin)){
niz3+=(char)keyin;

while(i<=br_Vrupa);{ probably there is a misplaced semicolon (;) If i<=br_Vrupa the while loop is never exited an the block below is newer executed.

You are right, I've corrected that, but it still doesn't work. Now, when it enters Case3 it just keeps displaying "enter the length enter the length enter the length " over and over

customKeypad.getKey() reads the key


text:
A problem with measuring time in a for loop
I am familiar with timing using millis() function, but it seems that I have run into a problem with a for loop.
The thing is, I am comparing encoder readings with a value entered via 4x4 keypad. Since I have to enter more than one value, i placed all values from the keypad into an array. Then I created a for loop that will cycle through that array and compare each value with encoder readings, when encoder reached the entered keypad value an LED should light up for 2 seconds. This is where the problem occurs. When it reaches the set value the LED seems to light up for like a fraction of a second. My guess is that the loop is creating some trouble here. Maybe because the loop cycles so fast the LED doesn't have enough time to stay lit. What do you think?
When I tried this program without a for loop (with only one value entered from a keypad), it works fine.
The code below has two arrays with values already entered, so no need or keypad. I used it just for testing. When I solve this problem I will add a keypad.
Please ask if you need any clarification of the code , and thank you in advance
#include <Encoder.h>
#include<Wire.h>
#include<LiquidCrystal_I2C.h>

int led1=14;
int led2=15;
unsigned long encoder;
unsigned long prev_value;
int array1[]={100, 200, 300, 400, 500, 600};
int array2[]={150, 250, 420};
int i,j,k,l;
int brV=6;
int brM=3;
int tolerance=10;
unsigned long oldTime=0.0;
unsigned long newTime;
int dt=2000;
bool testRange=true;
bool testRange2=true;

Encoder myEnc(2,3);
LiquidCrystal_I2C lcd1(0x27, 16, 2);

void setup() {
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
lcd1.init();
lcd1.backlight();
}

void loop() {
  newTime=millis();
  lcd1.setCursor(0,0);
  encoder=myEnc.read()*446/400;
  if(encoder!=prev_value){
    lcd1.clear();
    delay(10);
    prev_value=encoder;
  }
  lcd1.print(encoder);
  digitalWrite(led1,LOW);
  digitalWrite(led2,LOW);

  k=brV+brM;

  for(l=0;l<k;l++){
     for(i=0;i<brV;i++){
        if(encoder>=array1[i] && encoder<=(array1[i]+tolerance) && testRange){
           oldTime=newTime;
           digitalWrite(led1,HIGH);
           testRange=false;
         }
         else if(oldTime-newTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }
         if(encoder>(array1[i]+tolerance){
          testRange=true;
         }
     }
      for(j=0;j<brM;j++){
         if(encoder>=array2[j] && encoder<=(array2[j]+tolerance) && testRange2){
           oldTime=newTime;
           digitalWrite(led2,HIGH);
           testRange2=false;
         }
         else if(newTime-oldTime >= dt){
          oldTime=newTime;
          digitalWrite(led2,LOW);
         }
         if(encoder>array2[j]+tolerance){
          testRange2=true;
         }
      }
  }

  }

how long do you think it takes to execute the for loops until the LED is switched off in loop()?

I imagine it takes a couple of milliseconds for the for loop to execute

I guess it is less then a millisecond and that is how long the LED is lit. plus the LCD code

Could the problem be solved if I use timer interrupts?

what else is allowed to happen in the 2 seconds while the LED is on?

This program is just for testing. In the main program there will be another LED that will be lit all the time, but it will turn off for those 2 seconds, and turn back on again when 2 seconds have passed

move the handling of the LED timeout out of the for loops, directly to loop()

But the LED need to light up only when encoder value is greater than array[i] . Will the program know when to turn the LED on?

in loop() replace
digitalWrite(led1,LOW);

with
if (newTime - oldTime >= dt){
   digitalWrite(led1,LOW);
}

and you can remove the
else if(oldTime-newTime >= dt){
   oldTime=newTime;
   digitalWrite(led1,LOW);
}

from the for loop

Now it works, the LED turns on for 2 seconds, and then turns off. But only for the first iteration, it works for the first value form the array, when comparing to the other values it behaves the same as before

you want to lit the LED for 2 seconds so many times how many values match? then count the matches first and then do the blinking

I have tried that. I added a counter that counts how many times those two values match. And then, in my IF  I added that whenever the newTime-oldTime >= dt && i<counter it should turn the LED off, and increment i by 1 (i++) , but it still behaves the same. For some reason it looks like it only recognizes the first iteration of the for loop

Old time and new time are wrong way round on a part where the LED'd are switched off
else if(oldTime-newTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

When simple processors reach the max or min value and continue counting, they overflow and start counting from far end: So 5-8=maxint(largest number)-3
Result is that the difference is a massive number greater then 2000 except every few weeks when millis() overflows and become larger then Unsigned large int can store and starts counting from zero. (many codes fail working on that occasion, your would only works then ;-)
Correct version:
else if(newTime-oldTime >= dt){
          oldTime=newTime;
          digitalWrite(led1,LOW);
         }

Although I have noticed that testrange (both) only returns its value onto true on limited circumstance if input from encoder increased considerably very quickly to catch-up with growing inputs, so the next values will never pass condition to switch them on
if(encoder>=array1[i] && encoder<=(array1[i]+tolerance) && testRange)
will never return true because testRange stays false. Add
testRange=true;
testRange2=true;
at the end of the loop otherwise it does return into true for next loop()iteration. I guess question is if you want other functions to run while LEDs are on or not.
It is a bad habit to make unnecessary variables like i,j,k,l global as they waste memory even when not needed you can define them within structure itself Eg: for(int i=1;... this way as soon as for, while etc loop (brackets close)finishes you get your memory back and you can use variable again

You  are right, a stupid mistake. I've changed it now, but it still doesn't seem to work


text:
using multiple hc-05 with one arduino mega
please anyone help me build my project, i want to connect multiple smart phones to arduino mega using blutooth module hc-05 , I am working on real life home automation project and i don't have idea that can i use 4 Bluetooth modules with arduino mega . Requirement is max 4 smart phone connect to system , please anyone knowing about arduino please help ,i will be grateful . if u have any other suggestions tell me .

start with the example blink sketch ... try several of the example sketches that you can find in the Arduino IDE .... work your way up to bluetooth modules

do you know how to use one HC-05 module?

Yes i do , please help me to connect 4 Hc 05 in one Arduino mega, i need to connect 4 smartphones to one Arduino mega

I am making home automation project so it needs to connect 4 smartphones , looking forward for your help

This SE is for Q/A, not a project help service!

HC-05 modules use Serial (UART) for communication with the Arduino. Thus you need 4 Serial interfaces for 4 HC-05 modules. The Arduino Mega has 4 hardware Serial interfaces, so just connect once HC-05 to each Serial interface. Then handle each module in your code the same just with a different Serial interface. If you already know, how to use one HC-05, then it should be rather easy to implement the same with all 4 modules.

can't one HC-05 communicate any number of smartphones (one at the time)?

Sure it can. But as I read the question the 4 smartphone should be connected at the same time


text:
Arduino uno wifi rev2 error compiling sketch to board
I'm having an irritating situation with my Arduino Uno wifi rev2 board.
I made an installation with an LCD, keypad and little servo motor. I first wrote the code for my regular Arduino Uno and everything worked fine. Now I migrated my installation to my new Arduino Uno wifi rev2 because I needed it to make a request. But the problem is when I try to upload my code to the wifi rev2 it gives me a compilation error. I tried to upload a blink test sketch to see if it would work and it did but somehow it doesn't want to compile this code:
#include <Wire.h>

#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#include <Keypad.h>

LiquidCrystal_I2C lcd(0x27,16, 2);
Servo myservo;
const byte ROWS = 4;
const byte COLS = 3;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {9, 8, 7};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
String value = "";

void setup(){
  lcd.begin();
  Serial.begin(9600);
  myservo.attach(A0);
 lcd.backlight();
 //myservo.write(0);

}

void loop(){
    lcd.clear();
    char customKey = customKeypad.getKey();   // get the key pressed
    value = value + String(customKey);
    lcd.print("Geef bestelcode");
     lcd.setCursor(0,1);
    lcd.print("in: " + value);
 // char customKey = customKeypad.getKey();   // get the key pressed
 if(customKey=='#'){
        if(value == "1234#"){
          myservo.write(0);
          }
     // int pos = value.toInt();             // convert value to int
     // myservo.write(pos);                 // rotate the servo
         else{exit;}                   // clear the string
    }

     if(customKey=='*'){                       // 'D' works as "enter"
      myservo.write(90);                   // rotate the servo
      value = "";                           // clear the string
    }

 /*
  if(customKey && customKey!= '#'){         // if the key pressed is not 'D'
      value = value + String(customKey);    // concatenate the number to value
      //Serial.println(value);
  }*/
   delay(175);
}

The output of my error console :
In file included from C:\Users\TONES-PC\Documents\Arduino\sketch_dec15a_parcelbox_tester\sketch_dec15a_parcelbox_tester.ino:5:0:

C:\Users\TONES-PC\Documents\Arduino\libraries\Keypad/Keypad.h: In member function 'virtual void Keypad::pin_write(byte, boolean)':

C:\Users\TONES-PC\Documents\Arduino\libraries\Keypad/Keypad.h:88:81: error: cannot convert 'boolean {aka bool}' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

  virtual void pin_write(byte pinNum, boolean level) { digitalWrite(pinNum, level); }

                                                                                ^

Several libraries found for "Wire.h"
used: C:\Users\TONES-PC\AppData\Local\Arduino15\packages\arduino\hardware\megaavr\1.8.5\libraries\Wire
Several libraries found for "LiquidCrystal_I2C.h"
used: C:\Users\TONES-PC\Documents\Arduino\libraries\Arduino-LiquidCrystal-I2C-library-master
Several libraries found for "Servo.h"
used: C:\Program
Several libraries found for "Keypad.h"
used: C:\Users\TONES-PC\Documents\Arduino\libraries\Keypad
exit status 1
Error with compiling for board Arduino Uno WiFi Rev2

Any thoughts on how to solve this?

But I don't see where I am using a boolean for pinstatus?

the library uses it Keypad.h:88:81: error: cannot convert 'boolean {aka bool}' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

So what can I do to prevent it from using a bool?

check for a new version of the library. if it is not fixed, fix your copy

I am so sorry to keep bothering you. I installed a newer version same error. I've opened up the Keypad.h file itself and these are the lines where it errors  virtual void pin_mode(byte pinNum, byte mode) { pinMode(pinNum, mode); }  virtual void pin_write(byte pinNum, boolean level) { digitalWrite(pinNum, level);   virtual int  pin_read(byte pinNum) { return digitalRead(pinNum); }   But I have no idea what I need to change to get rid of the error?

Oke update I changed the boolean to int I don't know if it was a smart choice but the error is gone?

on the low level boolean and enum values are integer numbers too. the error was only type check. so it is OK

oke thank you for everything!


text:
How can I get an Arduino Uno run the Feather9x_RX example?
How do I get this example to run on using an Arduino Uno. I've updated RFM95_RST, RFM95_CS & RFM95_INT to the relevant pins (2,4 & 3 respectively).
This is the output on the Serial Monitor when the sketch is loaded:
Feather LoRa RX Test!
ERROR: Failed to put device in LoRa mode.
RH_RF95_REG_01_OP_MODE: 0
LoRa radio init failed

I've followed this wiring set up:

#include <SPI.h>
#include <RH_RF95.h>

#define RFM95_RST     2
#define RFM95_CS      4
#define RFM95_INT     3

// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0

// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);

// Blinky on receipt
#define LED 13

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(RFM95_RST, OUTPUT);
  digitalWrite(RFM95_RST, HIGH);

  Serial.begin(115200);
  while (!Serial) {
    delay(1);
  }
  delay(100);

  Serial.println("Feather LoRa RX Test!");

  // manual reset
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);

  while (!rf95.init()) {
    Serial.println("LoRa radio init failed");
    Serial.println("Uncomment '#define SERIAL_DEBUG' in RH_RF95.cpp for detailed debug info");
    while (1);
  }
  Serial.println("LoRa radio init OK!");

  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
  if (!rf95.setFrequency(RF95_FREQ)) {
    Serial.println("setFrequency failed");
    while (1);
  }
  Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);

  // Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on

  // The default transmitter power is 13dBm, using PA_BOOST.
  // If you are using RFM95/96/97/98 modules which uses the PA_BOOST transmitter pin, then
  // you can set transmitter powers from 5 to 23 dBm:
  rf95.setTxPower(23, false);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);

    if (rf95.recv(buf, &len))
    {
      digitalWrite(LED, HIGH);
      RH_RF95::printBuffer("Received: ", buf, len);
      Serial.print("Got: ");
      Serial.println((char*)buf);
       Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(LED, LOW);
    }
    else
    {
      Serial.println("Receive failed");
    }
  }
}

look at your while (!rf95.init()) code closely ... what happens if the radio is not ready when that code is executed?

so it gets stuck. I've replaced while(1); with delay(1000);  but now it just repeats the same error haha. I kind of thought the example would work out of the box, providing the wiring was ok.

Scrap that, i was looking at a different example. Your suggestion seems to have work! Thanks

Newbie here. I'm also getting same error after connecting RFM9x LoRa module with Arduino. What did you do to address this error? I can't seem to understand the suggested way in while (!rf95.init()) part of the code. Thanks in advance...


text:
How to calculate battery usage of my arduino project?
I want to measure power consumption and calculate the mAH value to know how much time would my battery can run the circuit.
I only got a multimeter and DC power supply.(Im not sure if this is enough to measure)
My project has a temp sensor and measures it every 15 mins. It's going to deep sleep mode and wakes up again to measure.
So how to measure the mAH for this circiut?

Depending on the model in question, the Arduino can be horribly inefficient. You are better off using the IC without all the funky stuff around. I recommend you to read Nick Gammons posts on power saving and power budget computation. Most Time you can estimate the power consumption from the datasheets and the up-time.

Can you measure the duration of the measurement while waking up?

A good answer to your question (as asked) has been offered. But maybe there's unasked question: "How can I get the maximum run time"? For that, we'd need to know what board you're using. Uno, f/ex, uses a lossy power supply that is on all the time, even during sleep, so sleeping won't help much. If you build a board with an efficient power supply, or use an off-board, efficient power supply that completely bypasses the Uno's(?) on-board one, you can do very much better. If you add more of those details, we could help you more.

I suggest using a second Arduino to make yourself an "Energy Meter".
Get a very small power resistor (0.1 Ohm) and power your project through it.
Second Arduino will measure voltage drop on it and that way you can get the current that goes through it using Ohms law. You can also measure the battery/power supply  voltage. Knowing those two values and micros each loop you can calculate actual hourly power consumption of the device.

Use the multimeter to measure the current. Put it in mA current mode, and wire it in series from the DC power supply + to the Arduino positive connection. With an Uno, readings will likly be in the 10s of mA all the time, and maybe a little higher when not in deep sleep mode. This assumes you are not powering the Uno from the USB port.


text:
High frequency Driver circuit
I'm looking for a 2Mhz 24v 100mA Driver circuit for my Piezo transducer. I am not sure that MOSFET could handle that, if it could there are not much design ideas for the same on internet. And there are high frequency LED driver ICs like LT3598, but I'm not sure about those too. Somebody please help me with this.

For piezo you want an h-bridge really.

Thank you for your replay, but this is for the application of Ultrasonic Humidifier. I wrote program for generating a PWM of 1,7MHz, it is a single polarity waveform, and the Piezo transducer also a single polarity device. So an H bridge is too much and most of the components will not be doing anything at all the time.

Please provide a link to the actual device you are using. Piezo transducers are a capacitive device, and with nothing to allow the capacitance to empty after each charge cycle you will have very poor results. For low frequency (audio) a simple resistor can be used. For high frequency you want something faster at discharging like an h-bridge. If your device has its own circuitry in it then that really changes the whole thing.

https://www.aliexpress.com/item/32854394686.html     here you can find the actual device


text:
1.7MHz Square wave generator
const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

I got it from here, look down to the answers
This program supposed to generate a square-wave of frequency around 1.7MHz but it is not working for me. I have tried the simulation on Proteus 8 and there is no output. Only one error shows during the compilation which is the 'loop' function is missing, I have added one and still there is no output. Please somebody help me.

i suggest that you start by exporing the example sketches in the Arduino IDE ... pay attention to the format of the sketches

In the setup there is some settings for timer2, but no change of prescaller, so the timer stays stopped.
Obviously it was started by calling soundBuzzer() somewhere in code. But this function name is now kinda misleading. Just set prescaller in the setup and it should be working.


text:
Lock screen if I leave my seat?
Background: I change the job and in the new company you need to pay pizza for the whole team if you forget to lock your screen :-)
I want it to be automated: I walk away and the screen should lock. No additional action should be required. Keyboard shortcuts, special mouse movements or unplugging devices from USB are not valid solutions.
How could this be solved (with or without arduino)?
Please write slowly, I never worked with sensors or arduino before :-)
I need this for Mac and Ubuntu.

Windows 10 has something called Dynamic Lock, where the PC lock when your paired mobile phone gets out of range. You might be able to replicate that for Mac/Linux. Or having one of those BLE key chaines (like Tile). When it's out of range, (or the RSSI is low enough), lock the computer.

How many times have you bought pizza so far?

It would be wise to elaborate more specifically on the circumstances that you consider should engage this automation. For example, you might wheel your chair over to talk to your next door neighbour, or stand up to get the attention of someone at the other end of the office: are these acceptable triggers to lock your screen? Both false positives and false negatives in this system have the potential to have annoying consequences, so if you insist on using automation to recognise these criteria minimal ambiguity is key.

Easy: just never leave your chair.

You are seeking a technical solution to a social problem. Expect to be berated for "cheating", if you implement such a solution. Perhaps paying for the occasional pizza might be a worthwhile price to pay to be to be treated like a team member, rather than a smart ass who steals the pizza from others' mouths. Just sayin' ;-)

A social problem? I am unsure. I see it like this: there are rules. I respect the rule. I want to follow the rule. I think automation is the key to success. I like no-brainers and "don't make me think".

@Mawg This is a technical problem: The company (sensibly) doesn't want other people accessing private data on an unlocked computer. Nobody cares about how this is achieved, just that it is. The whole idea behind these policies is to get people to start taking security serious in a nicer manner than having to talk with a manager.

Hard to understand why you want to create another solution to a quick Windows+L keypress ....

The irony here is that locking your console is intended to be a security measure, while many of the proposed solutions arguably introduce vulnerabilities.

@Voo - I disagree. It is not technical, but social. In my security cleared job (I could tell you more, but ...) locking is a requirement. Don't do it and there are severe consequences, far beyond buying pizza.  Hmmm ... wait ... thinking ... maybe my government should develop such a technician solution for all of us. If they feel strongly enough, then it is theirresponsibility.  But, having worked with humans (or as close as developers can be) for a few decades now, I can assure you that the OP will be berated for "cheating" if he implements his own solution ...

... maybe best to ask the company to implement a solution for all

@Mawg Yeah the government is known for being on the forefront of technology and never makes their employees do extra work instead of implementing a simple technical solution ;) But you haven't told me yet why a technical solution that guarantees (if well done) that no desktop is unlocked would somehow be worse than relying on fallible humans to remember to press a button dozens a time a day? (Admittedly some of the solutions here are dubious)

how do you feel about putting an rfid in your hand?  when your hand leaves proxmity to your computer, lock screen. this could be done very simply.

@voo - it's the people factor (exacerbated by the fact that the OP is the FNG) - his coworkers are going to feel that "it's not fair" and that he is "cheating" them out of their pizza. I understand that they could all make their own solution, but almost all will not, and so will complain. Even if he made one for everyone on the team, they will miss the fun of random pizzas & it will all be his fault. I can think of several ways to implemet a solution, but would never be so dumb as to do so. Again, this is not a techncial; problem, but a social one.

@Mawg Having people with that attitude sounds like an awful place to work at. Here, people would be interested in the technical solution and not worried about something as trivial as a bit of free food. I can't imagine most workplaces being like that - in my experience this is just a bit of good fun if someone forgets once in a while.

We are never going to see eye to eye, so I will ask @guettli to post his coworkers' attitude after he implements his solution (for which an ESP32 would be a better choice than an Arduino; heck I bought such a device form eBay about 15 years back, and now Gerben says that Windows has built in support). I won't post again until we hear from teh OP

Sorry, no Arduino required, but you probably already have a web cam on your desktop. If you don't mind being observed like Schrodinger's Cat, you can use a small utility like YawCam in Windows or Motion on Linux to trigger the screen lock when you are no longer visible at your console.

Overall this is a good suggestion, but "you probably already have a web cam on your desktop" seems like a pretty bold assumption. Webcams may be standard equipment on laptops these days, but I can count on one hand the number of desktop computers I've encountered in a business environment that had one installed.

@jmbpiano , how about now that we've all spent 2 years shut up in our home offices Zooming?

Bluetooth!
In the same vein as Gerben's comment, it is quite easy to use your phone for this, assuming that both your PC and your phone have bluetooth (and you take your phone with you, when you leave your seat). Moreover, if your PC does not have BT, cheap BT dongle will solve this.
Next step is writing a script that gets a list of all nearby/found BT devices and if your phone is not on that list, it just sends system call to lock.
As I have actually tried this once (although with a WIN PC), I can say it works more reliably than I would have initially expected (YMMV, obviously).
The great thing is that you (potentially) do not need any extra hardware, just a bit of code.

This works well - I used to do it many years ago. The good thing about writing your own script is that you can customise it for your situation: eg. set the signal strength threshold that will lock/unlock (you don't want to go help out a workmate behind you and not have your auto-lock script trigger!)

RFID (NFC) might be the way to go.  Have an RFID tag in a wristband and an RFID reader by the side of (or under) your keyboard. As long as you keep your hands close to the keyboard the RFID reader should detect your wristband. When it doesn't sense it for a pre-defined period of time send a signal to the PC to trigger it to lock. It could then trigger the unlock when your wristband is back in range again.

The usual range of RFID/NFC will probably make that quite awkward. Using RFID/NFC, I see only two options: either you have a card with a lanyard, and whenever you leave your desk, the card must come with you, or the card and reader are somewhere that moves less that your arms e.g. the tag on your belt and the reader somewhere on the chair.

It may be easier to have a flexible NFC tag sticker type thing on a piece of paper in your back pocket, and a reader under the seat, perhaps?

If you chair has a gas cylinder to adjust height, it sinks a bit when sat in. My dip is about a centimeter. That's more than enough for a beam-interruption or reflection sensor, a hall effect sensor, or even a dead-simple magnetic reed switch, like those used by home alarms to monitor windows.
You could have the reed switch turn on/wake up a micro like an ESP8266, which uses ESP-NOW to talk to another ESP plugged into a usb serial on the desktop. Once the message is sent, the micro can go into deep sleep. The desktop's serial port is read by the lang of your choice; node.js, python, c#, etc, and runs a command or fires a key combo to lock the workstation.

Which has the downside of locking your screen every time you shift in your seat. Was my first idea as well, though. I think you need some delay on it, like if it's longer than 3 seconds or so.

This also has the disadvantage of wire trailing from your chair to computer - wheeling your chair around could end up bringing your computer with you (added benefit of you not being 'away' from the computer I guess...).

If you have a busted cylinder, like many of us do, you'll always be at the lowest point, so you won't see any sink. Or if you constantly raise your seat and it lowers over time, like mine, it could register as occupied, even though it's just failed to support you.

At a previous job we also had the rule that the screen had to be locked (usually done   by pressing Win+L).
However, there was no pizza; instead, the computer was used to send mass e-mails to colleagues. The topics of the e-mails was as varied as the imaginations of people:

invitations to various events;
invitations to various celebrations at the desk of the not locked computer;
selling of expensive items for very low prices, providing whatever reasons;
etc etc

Many times, the content of the e-mail was the result of team-work.
The only limit was that the messages should use a decent language and not be (very) offensive. Also, I have never heard of e-mails sent in order to really harm the forgetful person (e.g. termination notice, offensive language to bosses or cutomers...).

The easiest and cheapest method is to just use Win+L. After you buy pizza for everybody for a few times, and have to endure their jokes / sarcasm at the same time, you will never forget to lock it again.
It is like learning to not pee in the bed during the night. It happens a few times, until you get it right.

For a technical solution, the sky is the limit.
As an (impractical) joke, you may want to have a look at the OMGWTF and the winners.
Example: configure the screensaver to kick in and lock the screen after ~ 5 seconds of inactivity (that is roughly the time you need to stand up and walk away, before any colleague has a chance to start typing without you noticing). It will create some trouble for you also, but you are sure that the computer will never remain unlocked. No additional software, hardware or work required - besides moving the mouse and hitting buttons on the keyboard. At the same time, you will become the most productive employee in the company. :)

On a more serious note, the purpose of that rule is to make people more aware of the security needs, and the need of them being involved in the process. Usually, locking the screen is the least one can do towards security, even before choosing good passwords - screen not locked, password not needed at all.
If one fails to do even that (lock the computer screen when the computer remains unattended), then there is a big chance that the other security rules are not followed either.

+1 for "the purpose of that rule is to make people more aware of the security needs, and the need of them being involved in the process." Yes, people need to be consciously aware of security. Automated systems only work as well as the people setting them up, and all too often those people aren't very security minded or they are so security minded that people with a legit need to use something still can't do to overbearing procedures.

@computercarguy I had a boss once who had the same idea and insisted that people had to consciously install Windows updates instead of using GPOs to handle that automatically. You can guess how many PCs were rarely up to date. Humans are awful at doing things regularly without failing, I don't believe a single person who thinks they'd never forget to lock their PC (I do believe that they don't remember forgetting to lock though, absolutely)

@Voo,there's a difference between a simple key-combo to lock a computer and installing updates manually. I realize (security) people don't realize it, though. Updates should be automated, since they can be complicated and large amount of them, as well as an IT dept potentially managing them. Also, installing updates is likely not the employee's focus at work, so their time is better spent not managing updates. Not to mention that locking a computer is akin to locking the front door to a house or business when it's not occupied.

@computercarguy So you're saying you agree it's impossible for people to once a week type "check for upda" reliably, but it's trivial to remember to press win+L hundreds of times in a week without fail?

@Voo, what I'm saying is that something as potential for failure as updates should be overseen by people who should know what they're doing, which the average office worker won't. And hitting a 2 key combo on the keyboard becomes 2nd nature after doing it for a short time. I do it unconsciously anymore. There are even times when I think about leaving my seat and hit it, only to realize I had one more thing to do/check before I left the seat. You might think checking for updates is easy, but that's only because you've done it so much and so often, which is the point with Win+L.

@Voo, yes, it is very different then checking OS updates. because to press the key combination is an automatic routine mechanical move, like for example  switching the turn signal at driving a car

A single distance sensor, properly placed, should be enough to detect when you leave. That's the arduino part.
With python you can then use the serial over USB to read the output from the arduino. And run the command to activate the screen lock, according to your reading.

Facing the chair might not be good enough, it should be faced 'over' the chair, because otherwise the back of the chair is measured, and you get a false positive when you move back like 8 inches.

arduino micro with keyboard library can send the key combination to lock the screen

Place a ultrasonic distance sensor HC-05 close to your monitor, facing towards your chest. Check the distance measured against a defined threshold (potentiometer?) and send a key press to your PC to lock it if it is exceeded.
I can go into more details if wanted, it's actually a project I thought about implementing before.
Edit: Whoops, @Eduardo Trápani suggested it already, but I think I can add to that.
I would use a digispark-like chip that can emulate key presses (WIN + L), this won't get you into trouble for installing software on your PC.

The simplest solution would be using a pressure sensor (pressure pad) in your seat. Or a pressure mat if you use a standing up desk.
Ideally, you can calibrate it with an Arduino and send a "Windows Key + L" or a "Ctrl + Cmd + Q" if it is an Apple.
I reckon no other solution can be simpler to implement nor to maintain.
If you want a slightly more refined solution you can connect a scale, tare it with your weight and set a weight threshold for the Arduino to send the signal.
Edit: In ubuntu, you can set up any key combination to lock the screen. But the rest of the answer stands.

What type of pressure sensor would you recommend?

Hello @dotancohen
Manufacturing your own seems the best option https://www.tekscan.com/blog/flexiforce/how-create-pressure-sensor-pad
Or this link https://www.instructables.com/id/Use-a-DIY-Pressure-Plate-Switch-to-Automate-Your-H/

Using a key-comb manually is simpler to implement and maintain, since it'll quickly become automatic. It doesn't require any coding, batteries, wires that break or get in the way, and doesn't have to be rewritten for different OSes. It also doesn't break some IT policies against attaching personal peripherals to a computer. Then there's the modification of the chair to accommodate the sensor, which might not be welcome. Also, using an off the shelf load cell is more reliable than a homemade version.

Use an obscure window manager which other people don't know how to use.
I use i3 and like to deliberately leave my workstation unlocked, because it's funny when I come back and find people pressing various key combinations to try and activate the group chat window (sending a funny message in my name is how they would prove they've 'hacked me') which I put into a hidden buffer.
Two and a half years in this role and they still haven't figured it out...all they need to do is RTFM...

OP would still be buying pizza, as the screen would be unlocked. It also sounds more like security by obfuscation, no?

@BruceWayne "security by obfuscation" yes, definitely. Though if OP's workplace's last line of security is the screen lock on OP's computer, then OP's company has bigger things to worry about ;-)

Since this isn't actually securing their PC, this is a bad suggestion. If others just need to RTFM to get around your suggestion, then it doesn't solve any problems, but rather creates new problems.


text:
Adafruit Huzzah ESP8266 Battery Power issue
I'm trying to connect a ~5.5V (2 x 3V coin cells in series, but their voltage drops a little) to the VBat (or V+) of my Adafruit Huzzah ESP8266 module (not the black Feather one, the smaller blue one: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/pinouts)
Whenever I do that the voltage output from the 3.3V pin drops to ~0-1 V and thus the ESP stops working.
However when I use the FTDI cable (3.3 V) and connect it to my laptop, there is no problem, I get almost 3 V.
I also added a 1000mF capacitor to smooth out voltage signals and actually that also helps to increase the volt a little (without it I get almost a 0 V on the 3.3V output)
Any ideas?

After tinkering more, I figured out that the Huzzah module is happy to take in up 4.5V via a 3 AAA battery cell so I guess it's ok up to 5V since my previous battery input was over 5V.
That's a little weird considering that in Adafruit's page, it says

..to make it easier to power, we put a high-current-capable 3.3V
  voltage regulator on the board. It can take 3.4-6V in but you should
  stick to 4-6V since the ESP8288 has high current usage when WiFi is
  on.

Hope this may help someone else.


text:
passing arrays via function returns wrong values
I am trying to use the values of an array in some other function, but when I return via a function the contents is wrong.
This is the external function file I'm trying to use
#include "Arrayreturner.h"

Arrayreturner::Arrayreturner() { }

void Arrayreturner::setResults(int* res, int size) {
 int temp[size];

 for(int i=0;i<size;i++) {
  temp[i] = res[i];
 }

 results = temp;

}

int* Arrayreturner::getResults() {
  return results;
}

This is the header file
#ifndef ARRAYRETURNER_H
#define ARRAYRETURNER_H

#include <Arduino.h>
#include <Wire.h>

class Arrayreturner {
public: // some public definitions first

 Arrayreturner();

void setResults(int* res, int size);
int* getResults();
int* results;

};

#endif

And here is the main program
#include <Arduino.h>
#include "Arrayreturner.h"

Arrayreturner data;

void setup() {
 Serial.begin(9600);

}

int* returnArray(int arr[]) {
 // int arr[] = { 3, 5, 6, 7, 9 };
 int *p = arr;

 // Serial.print("rA: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");
 return p;
}

Arrayreturner testfunc() {
 Arrayreturner data;
 int arr[] = { 2,4,6,8,10};

 data.setResults(arr, 5);

 return data;
}

void loop() {

  int arr[] = { 3, 5, 6, 7, 9 };
  // int *p = arr;
  // int (*ptr)[5] = &arr;

 // Serial.print("p: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");

 // int* p1;
 // p1 = returnArray(arr);
 // Serial.print("p1: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p1[i]); Serial.print(" ");
 // } Serial.println("");

 // data.setResults(arr, 5);

 // int* res = data.getResults();
 //
 // Serial.print("res: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(res[i]); Serial.print(" ");
 // } Serial.println(" ");

 Arrayreturner ar = testfunc();
 int* res = ar.getResults();
 Serial.print("res: ");
 for(int i=0;i<5;i++) {
   Serial.print(res[i]); Serial.print(" ");
 } Serial.println(" ");

 Serial.println("--------------");

  delay(2000);

}
There is probably something wrong with the pointer declaration, but I cant figure it out.
Thanks for the help

This is a C language question. You copy a local array created on the stack of the testfunc() to other array created on the stack of Arrayreturner::setResults(). Then you store a pointer of the second array into  member variable results. But that pointer is not valid when the function setResults() returns and the array on the stack is destroyed.
Normal way is to create an array, pass it as parameter to the function and let the function fill it.

I added my own variable (Arrayreturner) before calling the "testfunc" and passed it through the called functions. The array and the other variables of the Arrayreturner now show the correct values. Thanks

Your arrays are declared locally to the functions. You cannot return local arrays from a function - as soon as you return the arrays no longer exist.


text:
Two serials can't work on the same speed
I have a device which sits on pins 10/11 of Arduino UNO. I am trying to send commands from my PC using Arduino to relay my commands to the device via Serial.
The problem is that if I use speed 9600 both for device and USB communication, then my commands gets damaged. Some letters are replaced by strange symbols, etc. The device uses 9600 baud rate.
If I change speed of the PC communication to 4800 (or any speed other than 9600), everything is fine. But I have to use different speeds for the communication.
I am not comfortable with the workaround, because I don't understand what's going on. Could somebody explain why the same serial port speeds causes problems?
Here is my code:
#include <SoftwareSerial.h>

#define rxPin 11
#define txPin 10

SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

 void setup()
 {
   digitalWrite(4,HIGH); // 1 - disable
   mySerial.begin(9600);
   Serial.begin(19200);
   while (!Serial) {;}  // wait for serial port to connect. Needed for native USB port only
   Serial.println("Begin");
 }

 void loop()
 {
  if (mySerial.available())
  {
    char c = mySerial.read();
    Serial.write(c);
  }
  if (Serial.available())
  {
    char c = Serial.read();
    mySerial.write(c);
  }
 }

SoftwareSerial is not my favorite and I didn't have a good taste with it. But, anyway, maybe you should give some more detail about the device you connect on pin 10 and 11.

@Sener The device is RMCS 2201 servo: Link to specs
It has fixed 9600 baud rate. I connected it directly to COM with a TTL converter and it works fine. So I guess, there is a problem somewhere in my code. Will try your buffering code. Thank you!
Maybe you can suggest something to replace SoftwareSerial?

Thank you for the device details. If it is working with USB to TTL module, then we should think about the code. Please give a try the code I mentioned. And even further, try to use hardware serial instead.

But, Arduino Uno has only one hardware serial with pins 0:RX, 1:TX.
Then, you can't use PC communication via USB. You may like to consider also Arduino Mega which has 4 Serial ports.

Perhaps the interrupt from the incoming byte changes something in the outgoing byte of the SoftwareSerial. It is possible. Perhaps the servo motor has some kind of software serial as well and requires perfect timing of the serial signal. To avoid collisions, you can first read a full line as the answer by @Sener shows. But you better use a hardware serial port of the arduino mega or arduino leonardo.

The baudrate of the servo motor could be a few percent higher or lower. The SoftwareSerial uses fixed baudrates, you can not change that. The hardware serial calculates the value for the uart register. I think the hardware serial can set a slightly different baud rate.

@Jot, buffered read didn't help. I ordered a Mega to solve this. Thank you!

@konstantin can you try to "sniff" the communication? I mean, when the communication is ongoing, connect the RX wire of the USB TTL to the TX pin of the Arduino, then to the RX, and check where the communication is corrupted

Software serial works only half duplex (you cannot send and receive in the same time).  AltSoftSerial is a very  good option.  https://www.arduinolibraries.info/libraries/alt-soft-serial

If you're using an UNO then why do you have this line:   while (!Serial) {;}   which even the comment in your own code says isn't necessary for your board?

I spent some time playing with your code and it seems your code actually loops the serial therefore if they are both set at 9600 as example and you print what the other one is sending like in your code you end up in a loop if you want to read what your serial is sending it is better put that values in a variable and send it
if you load your code you will get the following message in the arduino IDE once you try to connect to the serial monitor:
Error opening serial port 'COM8'. (Port busy),
your port is busy because the one serial port is reading the other all the time
one more thing I would use the following if you want to repeat a serial port:

  if (mySerial.available())
  {
    //char c = mySerial.read();
    Serial.write(mySerial.read());
  }

Hope this hels you

If you are confident with the device you connected to your Arduino Uno in terms of it has a reliable serial communication firmware running on it, You might need some buffering before relaying your commands;
#define RECORD_SIZE 100
void loop()
{
    RelayDataIfAvaliable();
}
void RelayDataIfAvaliable() {
    static char buffer[RECORD_SIZE];
    if (Serial.available())
    {
        if (readline(Serial.read(), buffer, RECORD_SIZE) > 0) {
            mySerial.write(buffer);
        }
    }
}
//Reads entire incoming data into buffer once
int readline(int readch, char *buffer, int len)
{
    static int pos = 0;//This was zero initially. But, it was missing first character!
    int rpos;
    //Serial.print(readch);
    if (readch > 0) {
        switch (readch) {
        case '\n': // Ignore new-lines
            break;
        case '\r': // Return on CR
            rpos = pos;
            pos = 0;  // Reset position index ready for next time
            return rpos;
        default:
            if (pos < len - 1) {
                buffer[pos++] = readch;
                buffer[pos] = 0;
            }
        }
    }
    // No end of line has been found, so return -1.
    return -1;
}

I have played with this approach. Buffered read doesn't help. The same problem: everything is fine until I set the same speed for both serials. I have ordered a Mega board. This should solve the problem for sure. :)
Thank you very much!

But, there is another way before going on that road. When I checked that datasheet for the motor, it can also communicate over I2C or SPI. Wouldn't you consider to do that as well?
For example, that sample is looking quite promising:
RMC220x demo

Ah, one more thing, did you give that down vote for my answer (work in progress)? it was the only place I could place a formatted coding so i did not necessarily a final answer. I believe that at least it deserves some respect.

not it's not my down vote. I've marked your answer as useful. Since I don't have enough reputation it's recorded, but not displayed. Your answers help me a lot!

Thank you for your  feedback and marking my answer. Good luck with your project.


text:
Arduino pin 3 to 7 used in serial data transfering
Good day.
I am new in Arduino so please bear with me. I need to know if Pins other than Pin 0 and 1 can be used as a serial connection. I have 3 devices that needs to be connected to Arduino via USB, but when I saw the specification of Arduino, it only implicate that only pins 0 and 1 is used for serial rx/tx. So is it possible to connect the other 2 usb connector via pin 2 to pin 5
Thank you very much for your answer

Can you explain what those three devices are? What kind of usb devices are they? The arduino uno is not a computer. Please add the extra information to your question.

The 3 devices are The Computer (which controls the system that I am making). router and then mobile phone (which are being controlled by system that I am making)

Some android smart phones recognize a usb-serial module. Such phones can be connected to a arduino board (with the usb connected to the phone). I don't know if there are routers that can do that. Is it a hacked router or router with open source firmware?

pins 0,1 are rx/tx for the hardware UART peripheral. Arduino (I assume UNO/Nano) have just one hardware UART.
there is a software library which makes use of any 2 pin to simulate hardware UART pin behavior for additional software UARTs (this is called bit banging). these "software" UARTs are not as fast as hardware ones and can't be relied on for fast baudrates (speeds). but for 9600kbps, they're good.
keep in mind, that despite they are easy to implement and versatile, they use CPU time when communicating and if you are using interrupts in your code, data flow will be affected.
https://www.arduino.cc/en/Reference/SoftwareSerial

Thank you Tirdad Sadri Nejad, This is a big help for me. I think this will answer my problem.

Btw, I tried to use software serial once for MIDI (31,250) bps, this didn't work reliable. If you need four serial ports, check the Arduino Mega.

If you need your Arduino to be a USB slave for additional serial interfaces, then you can connect FTDI Basics to hardware serial ports (such as on Mega) or to software serial ports (such as on Mega).

Try to avoid the SoftwareSerial library, it’s very unreliable, that I can tell you from experience. In exchange try AltSoftSerial or NeoSWSerial, far better.


text:
Arduino direction sensor
I am working on a school project for next week
And I need my Arduino to 'sense' at which direction it is moved is it possible? Are there any direction sensors that 'sense' at which direction the Arduino is moving?

Direction relative to itself or the absolute direction (like north or south)?

@chrisl  no I want the Arduino to sense that it goes up, down, right or left sry  that I didn't included in the question

https://playground.arduino.cc/Main/MPU-6050

@Juraj na not much help

it is, how it is done. study

As Juraj wrote, you need an MPU, which is a module, that consists of an 3-dimensional accelerometer and a 3-dimensional gyroscope. With the first you can sense acceleration in each of the 3 dimensions (up-down, left-right, forwards-backwards), with the seconds you can sense rotation around these three directions. Sometimes (depending on the module) there is also an magnetometer included, which can be used as a compass.
Note, that you cannot sense the actual speed of a device directly, without using some external reference. With an accelerometer you have to do some maths on the data to get the speed (basically integrating). But since you just want to sense the direction, without bothering about the exact speed, you don't have to think about this.
How exactly you have to program this is out of scope for this side, since it is a rather big topic. Also it depends on the module and library you use. The link, that was provided by Juraj, is a good starting point for reading about this. There are also some further links, for example to a library for controlling the MPU-6050 (if you have one of these) at this github site.
Basically you will have to regularly measure the acceleration in all three dimensions with the MPU. If for an axis the acceleration gets greater than a threshold value, you can count this as direction. To get a more precise direction (not only directly along the axis) you will have to combine the values of the dimensions as a vector. How this is to be solved depends greatly on what you want to achieve.


text:
Arduino YUN Rev. 2 power supply
I want to connect my YUN Rev. 2 to 7.4V.
I read that the older version only provides exactly 5 V at the Vin Pin. Is the Rev. 2 similar to it? I read that the power supply should be improved, but what does that mean?
I just tried to connect the Vin to regulated 5 V by a power supply board, but it didn't work. If I connect it to the 5V Pin the board is working, but I think this isn't recommended.
So has anybody experience with that board?
Thanks for your answers.

are you sure 5V pin is working and Vin is not for supplying power?

Yes, I just tried it several times. Even if I change the voltage.

For version 1 VIN is connected, through a Schottky diode, to the 5V rail.  That means you can only provide, at absolute most, 5V plus a little bit for the diode drop into VIN.  The 5V pin can only source power on the Yun, since it is also connected to the 5V rail through a Schottky diode.
In effect the two pins form the "In" and "Out" of the 5V power.
However in version 2 the 5V pin's diode has been removed, and the VIN's diode has been reversed.  VIN is now known as "5V_OUT".
So the 5V pin can be used for both in and out, and what was VIN can only be used for power out.
To provide more than 5V to the Yun you will have to first pass the voltage through a regulator of some form.  Since you want to use 7.4V it sounds like you are using 2S Li-Ion (or similar) batteries.  Because of that I'd recommend a switching regulator, rather than a linear one.  I commonly use 5V UBEC modules from my favourite RC model supplier.
For version 1 you will provide it to VIN.  For version 2 you will provide it to 5V.  Quite why they'd change something quite so fundamental as the power pin arrangement from one version to another is beyond me.  It would cause havoc with compatibility between versions with certain shields.

The regulator I just tried provides 4.9V. I just tried to use an transformer and it was the same, even when I changed the voltage. When it's connected to the 5V output the Yun is working fine...
I would try to use an other regulator, but I thought 4.9 V is in range or not?
Your right, I want to use two Li-Ion:

According to the schematics you should not be able to supply power through the 5V pin, and you should not be able to draw power from the VIN pin.  Maybe a mistake was made during manufacture and the diodes are backwards.

Hang on - yes, it's changed on V2 for some reason (why would they change something fundamental like that? Because they're idiots, that's why).

but it is good trick. if someone expects a build-in regulator, Vin would not work and supplying other then 5 V to 5V pin would be stupid

@Juraj Better would be to put an actual regulator on the board... That way VIN works like VIN on all the other boards with the same footprint...

I still didn't get the idea behind Yun and Tian

@Juraj I know, they make no sense. Why would you bother with such a thing when you can get a Pi for the same price, and get 200000x the oomph.


text:
HTTP post via GPRS (SIM808) to Azure http endpoint logic app is failing
I am using a SIM808 with a atmega2560.
I have setup the endpoint in Azure and that works when I try a http post via postman and/or an online http post tool (I get a 202 as result and see data comming into Azure)
I want to send a json package to an Azure http endpoint (smart app) using the function httpPOST in the SIMCom library from itead.
I am connecting to the network:
logging (I printed all that is written to GSM):
AT+CIFSR
DB:STARTING NEW CONNECTION
AT+CIPSHUT
DB:SHUTTED OK
AT+CSTT="provider.net","","" DB:APN OK
AT+CIICR
DB:CONNECTION OK
AT+CIFSR
DB:ASSIGNED AN IP
GPRS status=ATTACHED
AT+CIPSTART="TCP","prod-13.westeurope.logic.azure.com",443
DB:RECVD CMD
DB:OK TCP

Then call the httpPost function from the library with the following variables:
const char server[35] = "prod-13.westeurope.logic.azure.com";
const int port = 443;
const char path[200] = "/workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken";
const char parameters[100] = "{\"device\":\"alive\",\"timestamp\":\"09270845\"}";

Part of the httpPost function from the library for sending the data
    int InetGSM::httpPOST(const char* server, int port, const char* path, const char* parameters, char* result, int resultlength)
         ....
    gsm.SimpleWrite("POST ");
    gsm.SimpleWrite(path);
    gsm.SimpleWrite(" HTTP/1.1\r\nHost: ");
    gsm.SimpleWrite(server);
    gsm.SimpleWrite("\r\n");
    gsm.SimpleWrite("User-Agent: Arduino\r\n");
    gsm.SimpleWrite("Content-Type: application/json\r\n");
    gsm.SimpleWrite("Content-Length: ");
    itoa(strlen(parameters),itoaBuffer,10);
    gsm.SimpleWrite(itoaBuffer);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(parameters);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(end_c);
....

Which gives this output on the serial monitor (I printed all that is written to GSM):
AT+CIPSEND
DB:>
POST /workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken HTTP/1.1
Host: prod-13.westeurope.logic.azure.com
User-Agent: Arduino
Content-Type: application/json
Content-Length: 55

{"device":"alive","timestamp":"09270845"}

DB:SENT

And then it is waiting for a response:
Starting read..
Waiting for Data............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
CLOSED

Done..
response:
10

CLOSED

which times out I guess.
And I see nothing coming into Azure.
(I am getting data when I try a httpGet on a random site. So hardware, sim and network is working ok I guess)
Any ideas?
thx!

doesn't Azure use https?

yes it does, I am connecting to port 443 'const char server[35] = "prod-13.westeurope.logic.azure.com";
const int port = 443;'  But honestly I have never done this before so maybe I am forgetting/missing something

I don't know the AT commands for the GSM module, but it doesn't look like you would handle SSL

Juraj's comments put me on the right track, for SSL you need to do more then just select the port.
I did some searching and got it to work using a different GSM library that also supports SSL:
tinyGSM
in combination with ArduinoHttpClient
Jeroen
EDIT: It works, but there is a big downside. It looks like there is major overhead, each message seems to uses 13Kb of data...? I suspect this comes from the data that is returned by the endpoint.
This is way too much over GPRS so now looking into MQTT.


text:
I am facing a problem of firing multiple interrupts on nodemcu 1.0 on single rising edge pulse.what is problem and what are the solutions?
I am working on a project which involves counting the drops falling in a drip chamber of a IV fluid gravity based therapy bottle(saline bottle).I am using IR trans-receiver at the drip chamber to detect a drop falling. I am using a comparator to generate a pulse when ir voltage drops below a certain threshold. The output of comparator is connected to D1 of nodemcu. The ISR is called at rising pulse of comparator .But the nodemcu calls the ISR 3 to 5 times on a single drop.what should I do?plz help.

It sounds, like your circuit is producing multiple rising edges per drop. You could check that, by watching the signal through an oscilloscope or a logic analyser. The cleanest way of solving would be to tweak your circuit, so that you only get 1 rising edge per drop. Or you can turn of the interrupt for a specific time, after the first drop detection (so that you ignore the false interrupts

Seems good I'll try it.i should turn off the interrupt using micros after a drop detected and again turn on the interrupt after some milli second. I can' t stop running the main loop as it consist of sending the data volume remain, rate, etc. to the database.

what is the fastest drip rate of a saline IV?

Actually I didn't have the perfect idea .I googled it, but i didn't get the direct ans. Then I saw "dial a flow " tubing images, it has max. 250 ml/ hr mark on it. And from Google I got to know the max drop factor (drops required for 1 ml ) is 60. From this i calculated the max drip rate could be 4 to 5 drops per second.

might try a small capacitor, like 1 or 0.1uf on the ir voltage to slow it down and filter out noise. you essentially need a 10hz low pass filter. also the 8266's ADC only likes to sample about 800 times a second, asking it more might produce erratic results.

The signal is probably "bouncing" between HIGH and LOW instead of performing a clean edge, just like it happens with buttons.
Two simple solutions:

Hardware solution: use a schmidt-trigger instead of a comparator
Software solution: define a dead-time for the signal aquisition (disable the interrupt when the desired edge has been detected and enable it again after "dead-time")

I will try  both of the solutions.   was first using the adc on the nodemcu.but for that the nodemcu was missing the drops .so to use the interrupt I have to use comparator.

Sim Son,I can disable the interrupt in isr .but how to reenable it without stopping the main loop because checking the condition that deadtime is completed will not allow to do other things? I am not able to write code for that can u elaborate.


text:
delayMicroseconds not working on STM32F103C8T6
Due to the fake STM32F103C8T6 module in the market, the delayMicroseconds function is working qucker than expected, when I expect a delay of 1000 us , I get a delay of 500 us. Is there a better method, like to create separate module for counting in microseconds using micros timer? Or there are other proper bootloaders than this one . I use Arduino IDE for programming STM32F103C8T6

Being off by a factor of 2 seems to be way too much. I have no experience with ARM processors, but I've seen such problems with AVR based microcontrollers, when the frequency set by the fuses was different, that what was set in the Arduino IDE. So the microcontroller ran on a different frequency. Are you sure, that you run on the right frequency?

Have you considered using a RTC? Something like a DS1307 breakout with I2C communications will provide you with accurate timing.
https://www.bobmixon.com/2020/03/real-time-clock-and-arduino/

How would you do a 1,000 µs delay with a DS1307?

Good point... the OP wrote "µs" and I read "ms". lol


text:
How to update data to xml file
I have search lots, and finally I was able to get my project moving!
I have learned to create an xml file and get data from it using XMLRequest vía "get".
I'm using a Nodemcu 12e v.1 I believe, have the WiFi and server running. The index.html and xml file are both in a spiff format folder and running!
My question is:
Can Data let's say from a sensor be loaded to the xml file?
If so, can someone guide me in the right direction?
Thank you all!

Welcome to Arduino:SE. You might find this post on our Meta site helpful: How to ask a good question for Arduino Stack Exchange.

why xml? for Java Script JSON format is native

I spend the whole day, learning about Json! I was using samples from different websites that’s why used what they had. But now I know how to get data out of json. But I can not find any guide regards updating data every 1 second to json from Arduino.

use the Java Script setTimeout function https://www.w3schools.com/jsref/met_win_settimeout.asp to call the function which makes the AJAX request and applies the data from the response to the page


text:
Can the ESP-1 use SPI to communicate with sensors?
I wonder if I can use SPI to communicate between ESP-1  ESP8266 module and SPI sensors and other slaves.
If so, do I need to install a library?

sure it can - do you know how to use a soldering iron? esp8266 arduino framework comes with SPI library, so, you won't need to install one

ESP-01 was designed as WiFi network adapter, not as a controller board. The are 4 pins on esp-01. RX (io 3), TX (io 1), io 0 and io 2.
SPI requires 3 pins: clock, MISO, MOSI plus one pin for every device connected to the bus. So you could in theory use one SPI device on this 4 pins. The esp8266 Arduino SPI library works only with hardware SPI on esp8266 pins io 12, 13, 14 so you would have to use some software SPI implementation for esp8266.
To connect sensors, actuators or display to the esp-01, I2C is a feasible option. It requires only two digital pins and the esp8266 Arduino Wire library can work on any pair of io pins.
To use esp8266 as MCU with Arduino, there are many development boards with all usable pins broken out (9 pins) and USB chip for simple connection to computer and flashing (Wemos, NodeMCU). Or you can use an esp8266 module with more or all pins of the esp8266 (esp-07, esp-12).

Thanks. Do you know any software spi library that might work?


text:
How many PIR Motion Sensors can I connect to my Arduino-Uno R3?
I am doing a school project where I intend to measure the cafeteria line with motion sensors and the send that information with a WiFi module to a server. This is my first time using Arduino and I am not sure how many motion sensors does it support.

for both simple and good, use one per GPIO you have that supports interrupts. for simple and not as good, use one per GPIO. you can eventually add more with port expanders, charlie plexing, even shift registers.

Most PIR sensors provide a simple relay output. That means they are nothing more than a switch as far as the Arduino is concerned.
You can connect hundreds of switches to an Arduino. With judicious use of diodes and a matrix arrangement you can hundreds with not many IO pins.  For example an 8x8 matrix of switches gives you 64 PIR sensors with just 16 IO pins.  For n pins you can have (n/2)² switches with a balanced (n/2 by n/2) matrix.


text:
ESP32 Bluetooth SPP Max Speed
I am trying to understand the maximum BT SPP transmission speed that can be achieved using ESP32.
What my project requires is to send 2bytes of data every 200us (5kHz) AND additional 15bytes of data every 50ms(20Hz) via BT.
I am trying to achieve that using BT SPP, however, I could not understand the speed of BluetoothSerial::write AND BluetoothSerial::print.
Based on my testing for 5kHz, the BluetoothSerial::write freezes after 2-3 seconds of connection.
BluetoothSerial::println function doesn't seem to freeze, however, the time taken for the function to complete doesn't seem to be constant. Please refer to the code below on how I measure the time taken for the function to complete.
The picture below shows the time in microseconds each time the function (dataFormat()) takes place. If you look through, there are 2 instances where the time duration is more than an average 0f 80us.
I would like to know, ESP32 BT SPP can achieve such a speed or there is another way I could achieve this.
Thank you for your time and assistance in this matter.
I have asked the same question in ESP32 Forum as well here.
void dataFormat(record r){
  serialBtPrint_dur = micros();
  char msg[20];
  sprintf(msg,"%04d%05d%05d%05",r.e, r.r, r.p, r.y);
  SerialBT.println(msg);
  serialBtPrint_dur = micros() - serialBtPrint_dur;
  }
}

void loop() {
  char msg[20];
  uint8_t testMsg[20] = "abcdefghijklmnop\n";
  if(!structs.isEmpty()){
    dataset[local_rd_ptr].yawData);
    data::dataFormat(structs.shift());
    Serial.println(serialBtPrint_dur);
  }
}

This seems more like an overflow issue with something than an actual delay.  If you look at the time in the log, it seems you aren't skipping seconds in the log (aka, 19:12:32.234 in two sequential log entries when you claim a delay).  I think it's an error of working with larger than 8-bit data sizes.  I know this is an old question, but I was looking for info and came upon it and figured I'd ask.

Thanks actually for having a thought on this. It has not been solved which lead me to use a different mechanism. For this particular scenario, the overflow would only happen if the micros difference is bigger than 8bit data size, which in theory shouldn't happen.