text:
1 Button + Potentiometer
Sketch
arduino-uno programming
1 Button and 1 Potentiometer
Sketch: Each time the button is pressed, acquire the value of the potentiometer in a array of 10 positions of these values do the average and print it on the serial monitor or display.
At the end print the average (sum of values / 10)
#define BUTTON 5
#define ARRAY_SIZE 10
int counter = 0;
int valori[ARRAY_SIZE];
int pinPotenziometro = A0;
int statoPresenteBottone = LOW; //why so LOW?
float media = 0.0;
void setup() {
  Serial.begin(9600);
  pinMode(BUTTON, INPUT);
  for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
}
void loop() {
  if (counter > ARRAY_SIZE) {
    counter = 00;
    media = 0.0; // when we fill array fully - we start again
    for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
  }
  statoPresenteBottone = digitalRead (BUTTON);
  while (statoPresenteBottone == HIGH) {
    valori[counter] = analogRead(A0);
    media = media + valori[counter];
   Serial.print("Average: ");
   Serial.println(media / counter);
   Serial.print("Button pressed times: ");
   Serial.println(counter);
    statoPresenteBottone = LOW;
    counter++;
  }
}

Can u guys edit the Sketch? Cuz if u try It on tinkercad with adding a potentiometer+ a button u will see he does the average after each value we acquired but i need to do that at the end...
I dont need explaining of how i should i do It cuz the teacher did that already but these are my skills D: if u guys can edit the sketch and solve this problem would be cool thx

Duplicate of the OPs previous question: Schematic: 1 Button and 1 Potentiometer Sketch

So your teacher explained to you, how you should solve the problem? And now you are asking as to do the rest of your homework for you? And you ask us to build the project ourselves in tinkercad? Sorry, we are not here to do other peoples homework. We are not a free code writing/editing service. And when you are talking about a tinkercad simulation, you should provide a link to a public tinkercad project, that you build. I don't have an account there and I also don't want to build up the project from your description. Please provide such things in your question, if you want good answers.

basically there is AN array of 10 positions every time we press the Button he acquires the value of the potentiometer (we do that for 10 times) at the end he does the sum of values/array_size and print the average , the link of public project Is : https://www.tinkercad.com/things/cNjZS9Oz02j-progetto-media-varianza-da-finire-d-uwu-uwu-uwu-lt3/editel?sharecode=Bs8_pG7HsyANlYI4yp9W2cuaJ20dIlfdgQmPhO1U1zY

You didn't actually answer to the other things that I wrote. Though your tinkercad project doesn't seem to be public. I cannot see it without login in.

ah 1 sec i will update link

Please put that link in your original question. This one will be closed soon, since it is basically the same question, as before.

Ok but its public already the link y can edit


text:
How esp8266 gets response from server..?
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  delay(2000);
}

void printResponse() {
  String s="";
  while (ESP8266.available()) {
    s+=ESP8266.readStringUntil('\n');
  }

  Serial.println(s);
  // now here you can parse and look for "+IPD" look for another line ending (if there is) and then extract the numeric value.
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

i have run this code and i am able to get this  response from server like "+ipd 4,41".... what does it mean?
here is the response after run the code in arduino......
WIFI GOT IP
AT+CIPLUX=1

OK
AT+CHPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AR)CR5NB⸮b⸮⸮k

j⸮L⸮⸮
Recv 27 bytes

SEND OK

+IPD,4,41

Thanks in advance.....

Your seeing corruption from running software serial at 115200 baud.

There's two things to know here:

You're seeing corruption in your output because SoftwareSerial is not capable of working reliably at 115200 baud. You need to reconfigure your ESP8266 to operate at a lower baud rate (such as 9600) to be able to use it with an Arduino that doesn't have enough physical UARTs.
The response +IPD,4,41 is telling you about the response. It's not itself the response.

It means "IP Data on channel 4 of length 41". It is then your responsibility to request that data from the ESP8266 using whatever AT command the ESP8266 requires.
Personally I would scrap the AT firmware and program the ESP8266 directly. That way you solve both problems: you can choose what baud rate to communicate at (if you even need to communicate to an Arduino at all), and you have no AT commands to parse or craft. It is a far more efficient way of working with the ESP8266 that trying to fudge things with the AT firmware and an Arduino.

Thanks this answer was helpful for me...

But i want to know that when i change the baud rate in serial moniter, its changed but the response from esp8266 on AT commands not show why? if i did wrong, then what i need to to solve this issue.

secondly, i want to know which AT commands esp8266 requires to to request data from esp8266 or code which i need to used in the arduino ide....

You have to change the baud rate on the ESP itself as well as the Arduino. There's an AT command to do it, but it has been known to brick the ESP. there's different versions of the firmware and commands differ between them. There's a PDF available online somewhere that lists all the commands.

SoftwareSerial does not works well for baud rate higher than 9600bps, you need to change your Arduino and ESP8266 to operate at 9600bps.

Use the AT+UART_DEF=9600,8,1,0,0 to set the ESP8266 to 9600Baud, with 8 bit, 1 stop bit and no parity. And also remember to configure the Arduino accordingly. The AT command with _DEF suffix means it will only need to be set once and the configuration will be saved in the ESP8266. ESP8266 AT Command Set would be handy when programming the ESP8266 with AT Commands.

Add longer delay after sending AT+CIPSEND and Get request as those network activities sometime take longer time to establish.

The +IPD,4,41 means that Connect 4 (which you established with AT+CIPSTART is connected and there are 41 bytes payload waiting to be read. You can refer to ESP8266 AT Command Examples for more information.

source: Stack Exchange

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

sort: votes


text:
Differential voltage measurement using Arduino
I have a electrolysis cell in which the anode is hanging using a Structure in a electrolyte. The cathode is at the bottom of the cell with electrolyte above it and anode being dipped into this electrolyte (not completely, a portion of the anode is dipped). The cell operates at 7  volts DC and 90000 amperes of current flowing through it. This is a typical electrolysis process of producing aluminium from alumina powder in a aluminium smelter. The cell is called a pot.
Now the question is I need to measure a potential drop on the anode rod. We usually take a meter to measure the potential drop on the anode rod and typically the reading are in millivolts. As the readings are in millivolts, it just indicates the drop in rod voltage due to resistance of rod. Now can I measure this millivolts drop using Arduino provided the voltage at one point of anode is 5 volts with respect to ground and the voltage at the other point is 4.95 volts with respect to ground, however the difference between these voltages is 0.5 volts and this is voltage I need to measure using Arduino and some arrangements as add on to it. How can I do this?
Can anyone help.
If you want more details, please comment. I will also provide more details.
So far I have done is tried measuring 1.5 volts on a pencil cell using Arduino by connecting A0 analog pin on Arduino to positive directly to the positive of 1.5 volts battery and ground of Arduino to the negative of Arduino.
Can I do the same for this millivolts measurements? I understand that the ground of Arduino and the 2nd point of anode measurement will not be at same potential, so shouldn't be connected together. I am scared to burn my board, so didn't try practically and wanted to get some opinion.

90000 amps?! Are you sure? That's just over half a megawatt of power!

Lacking experience of high current applications, I'd never put an Arduino anywhere near something capable of pushing 90000 amps through it. I suspect it might be a problem to interrupt the arc current through the carbonised remains of the Arduino and nearby objects (/buildings). Maybe better qualified people can be bolder though.

Yes. An aluminium smelter typically consumes 1400MW of power for 0.5MTPA capacity.  Current wouldn't flow from Arduino as the anode is a conducting material made up of aluminium solid rods. The current flowing through Arduino would be really small i think. Because we can measure the voltage on the cell with a multimeter as well. So high amps shouldn't be a problem as far as I think.

@Majenko Smelting! Big power.

High current will always pass from the least resistance path and as the rod itself is highly conductive in nature, the dc current shouldn't pass through Arduino, however we will have to have some safety as well. I can't figure out a method to measure this potential difference. Or maybe I will have to open the existing meter and connect the measurement pin to the Arduino.

Yes smelting requires huge power. My company have another plant with 1.25 MTPA capacity and 3750 MW power plant. All big metals and mining companies have huge assets in power. For e.g rio tinto, alcoa, ega, chalco, qatalum, alba etc

Measuring a "differential" voltage is as simple as measuring two separate voltages and subtracting one from the other. As long as you have a common "ground" reference point there's no magic involved.

Consider using an isolated differential ADC

As you do it with the multimeter: connecting ground to the lower potential (4.95 Volts in your example) and the volt probe to the higher potential (in your case 5.0 V), you can also connect the Arduino between the two potentials: Arduino GND to the lower (!) potential and A0, A1, ... or A7 to the higher (!) potential.
As long as you use the correct polarisation and the difference between the potentials is less than VCC of the ADC (5V Arduino ADCs) you should be save.
The resolution of the Arduino might be a problem. I don't know what resolution you need; 5V divided by 1024 is about 5 mV per step.
You might want to provide a reference Voltage at Vin of -let's say- 1 Volt if you need a better resolution. That would improve the resolution to about 1 mV per step. But then the meassured voltage must no exceed the 1 Volt reference voltage.
EDIT (Gerben's comment)
You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))
And please let me give you a security advice: If the resistence in any part of your meassuring setup is significantly lower than the resistance between the messuring points (e.g you shorten the probe wires), then there is a chance that 90000 A running through this setup. That could burn away your hand, arm or even your life. Amperes kill; not Voltage. I've seen a wrench that was vaporized (ok, melted, ok glowing ;-) ) in a second, when it had fallen between the poles of a car battery (12 V; 300 Amps). An you operate with 90000 Amps. !

You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))

@Gerben Yes that should also be mentioned. But I think even the 5 mV resolution is good enough in the 500 mV range. I just mentioned that there could be a problem with the resolution. Oh, and you brought me to another potential problem. If the measured Voltage can be higher than 1 Volt the idea of using  an alternative reference voltage may be not the best. Thank you!

Note that the Mega2560 has an ADC that can do differential measurements, with a programmable gain of 1×, 10× or 200×. This should solve the resolution problem.

Thanks all of you. I will read more into it. Thanks peter for clarification. This cleared a lot of doubts. Further there's no need to worry as entire potline in smelters is kept highly insulated and besides it's all DC, not AC. We can touch the DC terminal of any end as long as there's no potential difference and we are good to go with proper insulation. I have seen people directly working on these structures. Only thing is that, it gets really really hot as the electrolysis happens at 960-980 degrees, otherwise molten metal will not be produced.

I now have another question, we use a manual meter with an lcd. Can we read the values from that meter's lcd pin using digital pin read. I know it has to be pwm and the frequency may not be the same, however can anyone explain that part as well. @peter.

@surendrachoudhary A human body has some MOhms of resistance, so with max 5V there is no danger. But that is no example that can be compare with a conductor with a few micro ohms. You said you work in a highly isolated environment. So there should be no problem.

@surendrachoudhar To you second question: An LCD has many pins; seven for each segment and 1 for each decimal point. And all of theses are driven with alternating polarity to keep the LCD cristals alive. I dont think there is a practicable way to read out these pins. Does your meter has UART/RS232 or Bluetooth? That would be a much better way to read the meter.

No it doesn't have any communication media. That's the problem. I am planning to open the meter and check the insights. I will update here on this thread once I get more information about meter

@surendrachoudhar Please open a new question if you want to go deeper into the topic. And be sure it is still an Arduino question. Perhaps the Meter has an internal I2C or SPI Bus you could connect to the Arduino. But I fear that would lead to a loit of investigations about the protocol and to electronic questions. If the company can afford a Power Plat with many MWatts, I would expect a new Multimeter sould be affordable too. ;-) Sorry I could not resist.

Yes. I just wanted to get it done by ourselves. Actually I have made an android app to read data from Arduino and wanted to use the same for sending field measurements directly to our servers using this app. This will eliminate the need of logging readings on paper and will automate this process. However most important part of measurement is yet to figure out. :) Maybe I am going backwards. :)

This is obviously a significant project, not something to economize on. I would recommend you use a separate difference amplifier to get a single-ended output referenced to the Arduino ground and scaled to maximize the 10-bit range use.  The diff amp can use its own supplies (+/-7.5 or +/-15, say) with the ground tied to the Arduino ground.  That way the Arduino only sees the difference, never the full 7 V no matter what.

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


text:
how do i get data from the website? using arduino uno and esp8266
i have hosted a website on the 000webhost. And i have simply written a line in paragraph tags in html file( means i have created a html file..)
so i want to know to know how i get data that data in html file on the serial moniter through esp8266.
i have written a code in the arduino ide which is....
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /index.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

and the response on the serial moniter is
AT+CIPMUX=1

OK

AT+CIPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AT+CIPSEND=4,28

OK
>
Recv 28 bytes

SEND OK

+IPD,4,412:HTTP/1.1 400 Bad Request
Date: Thu, 27 May 2021 18:07:45 GMT
Content-Type: text/html
Content-Length: 154
Connection: close
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: 2eaf3c737a5348270ebe7873cab10088

<title>400 Bad Request</title>

400 Bad Request

openresty

4,CLOSED

what does it mean?
thanks in advance.......

You need to provide a full HTTP request, not just the "GET" line. You must at the very least include the Host: header, otherwise the web server has no clue which website you want to access.


text:
What is the timing between reset and avrdude/spi communication? (re: avrdude problem)
I'm trying to troubleshoot an issue with avrdude involving a Raspberry Pi and a transistor to control the reset pin on an Arduino Pro Micro (atmega32u4).
Where can I find information on the reset/programming process for the atmega32u4 or Arduino?  The atmega32u4 data sheet provides a bit of information but some of it is above my head.
For example, avrdude (and other programmers) require the microcontroller to be reset before uploading a new program or interacting (ie. fuses) with the chip.
Why is this?
The atmega32u4 specifies a minimum reset pulse of 400ns (ie. high to low to high again), but how long afterwards is the chip available for communication to avrdude?

avrdude interacts with a program that is running on the microcontroller (bootloader)

For AtMega32U4, a hardware reset, plus setting the PE2 to low will put the chip into hardware bootloader activation(HWB). Search HWB in the datasheet for more info. Arduino Micro uses DFU bootloader which take some time to be ready after reset, you can find out more about AVR DFU implementation here.

https://arduino.github.io/arduino-cli/latest/platform-specification/#1200-bps-bootloader-reset

It all depends on how you are programming - are you using ICSP? Or DFU? Or the Arduino bootloader? It all makes a difference.


text:
12V 28BYJ-40 motor is not generating enough torque
I am attempting to use a stepper motor to rotate one of my split-flap displays. However despite the thing the motor is rotating weighing probably half a pound, it struggles to do so. It really can rotate the module at all.
Why is my motor struggling so much?
My circuit is an Arduino powered by 5V from a wall outlet, connected to a ULN2003 driver that is powered by a 12V wall outlet. The driver is connected to the stepper motor.
This is my code, it uses the Accel stepper library:
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <Stepper.h>

AccelStepper stepper2(AccelStepper::FULL4WIRE, 4, 5, 6, 7);

void setup()
{
    Serial.begin(9600);
    pinMode(0, OUTPUT);
    pinMode(1, OUTPUT);
    pinMode(A0, OUTPUT);
    pinMode(A1, OUTPUT);
    pinMode(A2, OUTPUT);
    pinMode(A3, OUTPUT);
    pinMode(A4, OUTPUT);
    pinMode(A5, OUTPUT);

    stepper2.setMaxSpeed(100);
    stepper2.setAcceleration(10);
    stepper2.moveTo(-24000000);

}
void loop()
{
    // Change direction at the limits
    //printletters();

    if (stepper2.distanceToGo() == 0)
        stepper2.moveTo(-stepper2.currentPosition());

    stepper2.run();
}

Edit: Here is the schematic, I'm sorry its terrible but I dont know how to make it better

simulate this circuit – Schematic created using CircuitLab

A stepper motor cannot start with the target speed if the torque is too high. You might need to accelerate it.

Could be lots of things. My first guess would be you're not sharing grounds, but with no circuit diagram, it's just a guess. It's also difficult to guess how much force is required to turn the thing you're turning; the weight doesn't describe the system.

Post a schematic, not a frizzy thing and calculate the required torque needed on the motor shaft. Note a schematic shows all power and ground connections. If you have a scope measure the voltage waveform at the motor connections. You are using a bipolar driver a lot of power is lost in that, about 1.4V per output pin.

@thebusybee i am accelerating it

@DaveNewton can you explain sharing grounds

The ground from the motor controller board needs to be connected to the ground of the Arduino--when dealing with potential electrical problems a schematic is a good idea.

@DaveNewton okay I added a schematic, Im sorry its not very good, I'm not very good

The grounds need to be shared.

@DaveNewton That totally fixed it thanks a ton man

Nice! Glad you worked it out.

The grounds needed to be shared. The driver board ground needed to be connected to the Arduino ground. Otherwise your putting 17V in and only taking 12V out. Thanks to DaveNewton for this answer. I made this change and the torque was immediately fixed!

The reason is because there's not a complete circuit between the Arduino output pin and the Arduino. You might be interested in https://forum.arduino.cc/t/common-ground-and-why-you-need-one/626215/5.


text:
ARDUİNO MODBUS TCP CONNECTİON
I am trying to communicate with PC by using modbus TCP communicate. When I use this code I can't communicate. Dou you know guys what is the problem? My ethernet Module is working I know that because I can ping it when I use different code from EtherCard.h library. But when I try to use Ethernet and Modbus library I can't communicate. I can't ping it.
#include <ModbusIP.h>
#include <SPI.h>
#include <Ethernet.h>
#include <Modbus.h>

int setPoint;zz
const int setPoint_IR = 100;

ModbusIP mb;

void setup() {
  Serial.begin(9600);
  byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  byte ip [] = {10, 0, 58, 37};
  mb.config (mac, ip);

  mb.addIreg(setPoint_IR);

}

void loop() {
  mb.task();
  setPoint = analogRead(A0);
  mb.Ireg(setPoint_IR, setPoint);
}

void DisplaySetPointValues(){
  String Printstr;
  Printstr = "Set point values = " + String(setPoint);
  Serial.println(Printstr);
}

you can use my EthernetENC library

remove the 3.3V wire

Ethernet.h is for W5100 based cards (Arduino Ethernet shields). You cannot use it for an ENC28J60.

Thank you so much guys.


text:
Cannot instantiate SLIPSerial object used in OSC/SLIPSerial classes for Arduino
Hey I'm trying to test out the CMAT/OSC library for Arduino and just want to get up and running sending SLIP encoded OSC messages. I've been able to observe the typical Serial monitor when sending OSC Messages that way, but I cannot seem to get the example code to compile:

    #include <SLIPEncodedSerial.h>
    #include <OSCData.h>
    #include <OSCBundle.h>
    #include <OSCBoards.h>
    #include <OSCTiming.h>
    #include <OSCMessage.h>
    #include <OSCMatch.h>
    #include <SLIPEncodedUSBSerial.h>

    SLIPEncodedUSBSerial SLIPSerial( thisBoardsSerialUSB );
    // SLIPEncodedSerial SLIPSerial(Serial);

    void setup() {
      //begin SLIPSerial just like Serial
      SLIPSerial.begin(9600);   // set this as high as you can reliably run on your platform
    }

    void loop(){
      //the message wants an OSC address as first argument
      OSCMessage msg("/address");
      msg.add("Hello World\n");
    ;

      SLIPSerial.beginPacket();
      msg.send(SLIPSerial); // send the bytes to the SLIP stream
      SLIPSerial.endPacket(); // mark the end of the OSC Packet
      msg.empty(); // free space occupied by message
      delay(20);
    }

Furthermore this is the output error I see:
error: 'SLIPEncodedUSBSerial' does not name a type; did you mean 'SLIPEncodedUSBSerial_h'?
   10 | SLIPEncodedUSBSerial SLIPSerial( thisBoardsSerialUSB );
      | ^~~~~~~~~~~~~~~~~~~~
      | SLIPEncodedUSBSerial_h
exit status 1
'SLIPEncodedUSBSerial' does not name a type; did you mean 'SLIPEncodedUSBSerial_h'?

Could someone lend some clarity on what "thisBoardsSerialUSB" and "Serial" are in this context? I thought that the SLIPEncodedSerial / SLIPEncodedUSBSerial constructors simply take a reference. This might be trivial, but I am not sure how to properly instantiate these classes within the Arduino IDE.
Cheers!

What board are you compiling for?

thisBoardsSerialUSB is merely a placeholder for whatever the USB serial connection is for your board. Some have it as Serial, some USBSerial. It's up to you to put the right thing in.

there is #if (defined(TEENSYDUINO) && defined(USB_SERIAL)) || (!defined(TEENSYDUINO) && defined(__AVR_ATmega32U4__)) || defined(__SAM3X8E__) || (defined(_USB) && defined(_USE_USB_FOR_SERIAL_))  || defined(_SAMD21_) || (defined(__PIC32MX__) || defined(__PIC32MZ__))

@Majenko Ah okay! I read into the example code a bit too literally! the board I'd like to use is the Adafruit Metro M0 Express, which uses a ATSAMD21G18 chip (an ARM Cortex M0+)

SAMD21 should work: || defined(_SAMD21_)

@Juraj Yeah I had originally thought so as well! I found a weird quirk with installing the library via the provided library manager within the arduino IDE: it pulled an out of date version of the .cpp & .h files. Pulling from the git repo itself and referencing "Serial" as the argument to the constructor rectified the situation!


text:
Clicking a mouse based on dwell time / how to code a rolling total of sensor measurements
I'm trying to write code that should result in a click of the mouse, based on dwell time. I'm getting data from a gyroscope to move the mouse around. I'm not sure what the best way is to approach this from a coding perspective.
My current thinking in pseudocode is below. Basically it should be a rolling total of the last X sensor measurements, which is then compared to a dwell size/radius variable.
On a high level, what would be a feasible approach? I tried a couple of times with for loops and different code, but didn't get anywhere close. I would really appreciate advice about whether my high-level approach is even feasible. Thank you!
update array with sensor measurements for (i =  dwell time) ();
    update sum of the array = + i measurement; - (i - size of the array) measurement at each sensor measurement
if at last element of array
    if sum of the array < dwell radius; click
    loop to the beginning of the array

Though I'm not sure if (i - size of the array) measurement is even possible to do, since it could result in negative i values.

where is the Arduino part of your question?

Well it's using an Arduino board, it is more of a C++ question but I was hoping to find an answer here because people might have dealt with similar issues on other arduino projects. Should ask in the C++ stock exchange?

you are correct, it is completely a C++ question ... i would start with long button press code ... instead of sensing a button press,  sense stop of motion ... after a time interval, desired event is asserted

Yes this is what I'm struggling with, how to sense the cessation of motion while working with the gyroscope data. I wait a bit for the suggestions here and then if required post in the other stack exchange.

that is not the problem you asked about ... please focus your question to the actual problem ... how to sense cessation of motion? ... remove all irrelevant references to mouse motion and dwell time


text:
Arduino Uno - Raspberry PI - Float Sensors - Water pumps
I am experimenting with Aquaponics and since I am a software developer I found it "smart" to use arduino/raspberry in order to control the water flow and not simply use a water pump with mechanical means.
The advantage is that I am able to expand easier the system. The disadvantage is that I haven't yet met the reliability that I would lie to have.
I am a software engineer with basic knowledge in the hardware field. That is why I thought of starting with Raspberry.
Initially I made a setup with a single raspberry PI a few float sensors like this: https://www.hellasdigital.gr/electronics/sensors/humidity-sensor/tank-pool-water-level-liquid-sensor-float-switch/
and relay like this one: https://wiki.52pi.com/index.php/DockerPi_4_Channel_Relay_SKU:_EP-0099
I saw that sometimes the system was hanging with the relays open! This had the side effect to loose water. This is the most precious in aquaponics!
Thus I thought of creating a cluster. Thus I made a cluster of three Raspberrys. The two had the relays and only one PI had the sensors. In order to open the water pump both PIs should have given the green light. This worked better and when one of the PIs hanged then we lost no water.
But again I am thinking that it was not acceptable that the system was hanging so often (at least several times per week). Thus I thought maybe if I use an Arduino for this purpose then this would be better.
Thus this is what I did. I created a simple program (no cluster and a single Arduino). Unfortunately this had even worst results!!!
For the Arduino I used normal 5 Volt relays like this one: https://www.nettop.gr/index.php/hlektronika/relay/8-channel-5v-relay-module-with-light-coupling-5v.html and the same float sensors.
I do not believe that is software related the issue but it must be hardware.
The problem is that my knowledge in the hardware field is limited!
What should I do in order to prevent this? Do you think that is related with the water pumps and the relays ?
The same erroneous behavior happens at both the Raspberry and Arduino, I mean that the relay stays open and the water overflows. For Raspberry I can tell that the system stop to respond, I am sure about it. But for Arduino I cannot say for sure if the whole system was frozen or if input only for the float did not work.
I paste a link to the quick and dirty Arduino code as well for your reference.
The temperature were the systems were operating could be quite hot (30 ~ 48 degrees Celsius) for several hours.
Here is the code for the Arduino:
#define POT_1_FLOAT_SENSOR  2
#define POT_1_RELAY_1       11

#define PIPE_1_FLOAT_SENSOR  5
#define PIPE_1_RELAY_1       9

#define PIPE_2_FLOAT_SENSOR       3
#define PIPE_2_RELAY_2      10

#define PIPE_3_RELAY_3       12
#define PIPE_3_FLOAT_SENSOR       4

// pot 1
const unsigned long POT_1_MAX_WATERING_PERIOD = 120000;
const unsigned long POT_1_DRAIN_PERIOD = 70000;

unsigned long pot1StartMillis = 0;
unsigned long pot1DelayStartMillis = 0;

// Pipe 2
const unsigned long PIPE_2_MAX_WATERING_PERIOD = 300000;
const unsigned long PIPE_2_DRAIN_PERIOD = 300000;

unsigned long pipe2DelayStartMillis = 0;
unsigned long pipe2StartMillis = 0;

// Pipe 3
const unsigned long PIPE_3_MAX_WATERING_PERIOD = 760000;
const unsigned long PIPE_3_DRAIN_PERIOD = 300000;
unsigned long pipe3DelayStartMillis = 0;
unsigned long pipe3StartMillis = 0;

// Pipe 1
const unsigned long PIPE_1_MAX_WATERING_PERIOD = 180000;
const unsigned long PIPE_1_DRAIN_PERIOD = 300000;
unsigned long pipe1DelayStartMillis = 0;
unsigned long pipe1StartMillis = 0;

bool pot1RedFlag = false;
bool pot1SetStartTime = false;

bool pipe1RedFlag = false;
bool pipe1SetStartTime = false;

bool pipe2RedFlag = false;
bool pipe2SetStartTime = false;

bool pipe3RedFlag = false;
bool pipe3SetStartTime = false;

void setup()
{
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(POT_1_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(POT_1_RELAY_1, OUTPUT);
  digitalWrite(POT_1_RELAY_1, LOW);

  pinMode(PIPE_1_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_1_RELAY_1, OUTPUT);
  digitalWrite(PIPE_1_RELAY_1, LOW);

  pinMode(PIPE_2_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_2_RELAY_2, OUTPUT);
  digitalWrite(PIPE_2_RELAY_2, LOW);

  pinMode(PIPE_3_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_3_RELAY_3, OUTPUT);
  digitalWrite(PIPE_3_RELAY_3, LOW);

  pot1StartMillis = millis();
  pipe1StartMillis = millis();
  pipe2StartMillis = millis();
  pipe3StartMillis = millis();
}

void loop()
{
  checkAbstractWateringTimer(pot1SetStartTime, pot1RedFlag, pot1DelayStartMillis,
                                POT_1_DRAIN_PERIOD, POT_1_MAX_WATERING_PERIOD,
                                pot1StartMillis, POT_1_FLOAT_SENSOR, POT_1_RELAY_1);

  checkAbstractWateringTimer(pipe1SetStartTime, pipe1RedFlag, pipe1DelayStartMillis,
                                PIPE_1_DRAIN_PERIOD, PIPE_1_MAX_WATERING_PERIOD,
                                pipe1StartMillis, PIPE_1_FLOAT_SENSOR, PIPE_1_RELAY_1);

  checkAbstractWateringTimer(pipe2SetStartTime, pipe2RedFlag, pipe2DelayStartMillis,
                                PIPE_2_DRAIN_PERIOD, PIPE_2_MAX_WATERING_PERIOD,
                                pipe2StartMillis, PIPE_2_FLOAT_SENSOR, PIPE_2_RELAY_2);

   checkAbstractWateringTimer(pipe3SetStartTime, pipe3RedFlag, pipe3DelayStartMillis,
                                PIPE_3_DRAIN_PERIOD, PIPE_3_MAX_WATERING_PERIOD,
                                pipe3StartMillis, PIPE_3_FLOAT_SENSOR, PIPE_3_RELAY_3);

  delay(200);
}

void checkAbstractWateringTimer(bool &abstractSetStartTime, bool &abstractRedFlag, unsigned long &abstractDelayStartMillis,
                                unsigned long abstractDrainPeriod, unsigned long abstractMaxWateringPeriod,
                                unsigned long &abstractStartMillis, int abstractFloatSensor, int abstractRelay) {
  if (!abstractSetStartTime || (abstractSetStartTime && millis() - abstractDelayStartMillis >= abstractDrainPeriod)) {

    if(digitalRead(abstractFloatSensor) == LOW && !abstractRedFlag) // Need one more condition in order to emulate the delay...
    {
      digitalWrite(abstractRelay, LOW);
      Serial.println("Pot 1 pump is open");

      // Set it only once at the beginning
      if (pot1SetStartTime) {
        abstractStartMillis = millis();
        abstractSetStartTime = false;
      }

      Serial.print("duration ");
      Serial.println(millis() - abstractStartMillis);

      if (millis() - abstractStartMillis >= abstractMaxWateringPeriod)  //test whether the MAX watering period has elapsed
      {
        // Close pump and do not oopen it again. Red Flag...
        Serial.println("Pot 1 pump is closed and the red flag is ON");
        digitalWrite(abstractRelay, HIGH);
        abstractRedFlag = true;
      }
    }
    else
    {
      Serial.println("Pot 1 Pump is closed");
      digitalWrite(abstractRelay, HIGH);
      abstractSetStartTime = true;
      abstractDelayStartMillis = millis();
    }
  }
}

Please any ideas, suggestions or tests that I could do are more than welcome in order to create a reliable system.
-- UPDATE --
Both when I was using Raspberry and Arduino I haven't included any resistors between the float sensor pins and the ground. Are there any chances that this is related with the instabilities that I experienced?
Maybe I should add a resistor (10K) between the float sensor pin and the ground?
Thank you

Re “for Arduino I cannot say for sure if the whole system was frozen”: make the built-in LED blink in loop(). If it stops blinking, it's frozen.

Thank you Edgar, good idea I will do.

Maybe I should add a resistor (10K) between the float sensor pin and the ground? -- No, you have (roughly) 30k internal pullup resistors. Adding a 10k pulldown resistor would just confuse everything. However adding 10k pullups to 5V would help with noise rejection.

if relays sap your psu into dropping in voltage, it can affect your sensors.

Majenko thank you about your comment. You mean that I should follow something like this: https://en.wikipedia.org/wiki/Pull-up_resistor and at the Vin I should place 5 Volts and at the Vout I should connect it to my digital input. Correct ? Sorry about confirmation but my hardware knowledge is limited.

Thank you Abel about your comment. I believe I understand what you say. I have a 12 V power supply and if I remember out of my head is rated a 1.5 Amps. My question is what should I do about it if your statement is true? Buy better power supply?

Majenko I read a bit more about the pull up resistors from this link as well: https://learn.sparkfun.com/tutorials/pull-up-resistors/all
I am connecting the float sensor like this: https://www.gadgetronicx.com/interfacing-float-sensor-arduino/
As you might have noticed in my code I use the INPUT_PULLUP. I understand that adding a 10K pullup resistor to 5V as you said will help with noise rejection while I should leave my code as it is. Correct ? I mean having the internal pull up resistor plus the external one would be fine.  Or should I adapt my code adequately as well?

Do you think it is advisable to use an external power supply for the 8-module relay ? Would this make any sense?

How long are the cable runs? Is there any electrically noisy equipment near the cable runs? Consider using some form of galvanic isolation to interface the float sensors to the MCU. The relays require 50 to 60 mA drive current but the Arduino pins can only supply 40 mA.

Hi Tim thank you for your useful input. This you suggest that I should connect the relay module to an external power supply (vin and ground I suppose will be coming from another power source). Now about the noise could be. I have a hell of a lot of cables there! The max distance for each float sensor is under five meters. I will investigate about the galvanic isolation. Thank you!!!

Tim if you have a link related to the "galvanic isolation" would be great!!!!

Hi Tim I used this link to power the relays from an external power supply correctly https://lastminuteengineers.com/two-channel-relay-module-arduino-tutorial/. Thank you

I think I will give a try with these two modifications first. External power supply and pull up resistors. Normally it should be fairly quick if this is going to work or not.

Hi guys I run the system approximately for ten hours now and it looks that this was it!!! Fingers crossed but up to now it works very well. I am really grateful for all your answers that greatly helped me. I introduced the pull up resistor and an external power supply tot the relay module. I also used the internal led as a visual heartbeat. Thank you all again once more!!!

I hope that it will not crash in the next hour or so.... :D but even if it does I know that we will be able to find the root cause in this thread!!!

Glad we could help. Texas Instruments has a great series of videos on the subject of galvanic isolation which discusses inductive, capacitive and optical isolation techniques. Something else to consider is debouncing the float sensor signal either in hardware with a low-pass RC filter or with a software debouncer. For stronger pull-ups you could try 1K resistors, though this will use more current.

Guys I would like to accept your answers (more than one as well). Is this possible? If not at least Tim's answer. You need to post an answer instead of a comment for me to accept it?

Up to now it looks ok. No overflow. The only thing that I noticed is that it stopped after several hours working. But this could be a different issue I suppose. Maybe an overflow or something else.

Hi again Tim/all unfortunately this morning we had a water overflow. It means that one specific sensor did not gave the correct signal to Arduino. I watched the galvanic isolation video from TI. That's great but I think that the relay module they already have opto couplers. Now I am considering to introduce a low pass RC filter as you said to each float sensor. Do you have any suggestions for the values of the Resistor and capacitor? The pull-up resistors are 10K. I will change them to 1K. Any other suggestions?

Does it make any difference if I use two arduinos? One to control the float sensors and one the relays? Afterwards these two will have to communicate.

Do you think that I will not have these issues that I experience now with this sensor ? https://www.hellasdigital.gr/electronics/sensors/humidity-sensor/gravity-photoelectric-water-liquid-level-sensor-for-arduino-sen0205/

You are right that the relay modules already have isolators, but you've overlooked that the sensors don't have any isolation. You need to isolate the signals in both directions - both the inputs and the outputs.

As requested, I've collated my comments into an answer.
How long are the cable runs? Is there any electrically noisy equipment near the cable runs? Consider using some form of galvanic isolation to interface the float sensors to the MCU. Texas Instruments has a great series of videos on the subject of galvanic isolation which discusses inductive, capacitive and optical isolation techniques. Isolate the signals in both directions – both the inputs and the outputs.
For stronger pull-ups you could try 1K resistors, though this will use more current.
Something else to consider is debouncing the float sensor signals either in hardware with a low-pass RC filter or with a software debouncer (which I've put on GitHub).
The relays require 50 to 60 mA drive current but the Arduino pins can only supply 40 mA, so the external power supply is a good idea.
Redundancy, i.e. having multiple sensors for the same measurement, will guard against the loss of a single sensor causing chaos in a critical system, e.g. loss of precious water in a hot climate. You could have 3 float sensors for each water level at different locations, then use a voting system of >= 2 to take action. The system should also flag when sensors disagree so that someone can investigate the issue. And also route the cables via 3 different paths. This physical separation will guard against a single localised event (e.g. a wayward tractor or lightning strike) damaging all the sensors at the same time.
Also consider the fail-safe mode. For example, this could be to switch off all water valves when sensors disagree and then send an alert to someone and/or sound an alarm.
As your aquaponic farm is outside, consider lightning strike protection such as using TVS diodes on all inputs and outputs.
You could add feedback sensors to the relays to verify whether they have actually responded to the commands from the Arduino to switch on or off, i.e. compare commanded value with FB sensor value. These sensors could be pullup/pulldown resistors.
These additional relay FB sensors and the float sensors could be incorporated into the fail-safe logic. Some examples include:

If a relay is on when it's supposed to be off, flag the discrepancy.
If it takes 5 minutes to fill a tank and the inlet relay has been on for >5 minutes, it might be overflowing or dodgy sensors.
If the float sensors say a tank is empty, but the inlet relay has been on for >5 mins, something is wrong, e.g. leaking tank or dodgy sensors.
If it takes 10 mins to drain a tank but the float sensors say it's still full after 11 mins, something is wrong, e.g. blocked drain or dodgy sensors.
Are inlet and outlet relays on at the same time? Is this a valid condition?

There are many permutations. Happy coding...

thank you for your valuable input. I can say that now the system is stabilized.
The source of my issues was a faulty sensor but I have taken into account all advices. For example I separated the signal cables from the power cables that this was one more source of issues, I have introduced the pull up resistors, I have used separate power source for the relay module.
Generally for me ALL the comments from this thread were super important.
Thank you!

Something else to consider is redundancy, i.e. having multiple sensors for the same measurement. This will guard against the loss of a single sensor causing chaos in a critical system, e.g. loss of precious water in a hot climate. You could have 3 float sensors at each location, then use a voting system of >= 2 to take action. The system should also flag when sensors disagree so that someone can investigate the issue.

I've assumed up till now that this is an indoor aquaponic farm. If it's outdoors, you should also consider hardening to lightning strikes, e.g. using TVS diodes on all inputs and outputs. And a slight correction to my previous comment: the 3 sensors per measurement should be at different locations, but at at the same water level. And also route the cables via 3 different paths. This physical separation will guard against a single localised event (e.g. a wayward tractor or lightning strike) damaging all the sensors at the same time.

Yes indeed it is outdoor on my house's roof. I will have a look at the diodes that you are talking about. Thank you again for the great hardware ideas that you give me. I appreciate them.


text:
SD Card Library interferes with Adafruit
Im currently working on a datalogger that uses oled i2c displays and current sensors. Both of them uses adafruit libraries. To write the data, im using arduino's sd library, but somehow, the sd library interferes with my i2c components that they won't work while sd card functions work. adding any sort of code from the sd library would completely make the i2c components malfunction. To test this, i tried to view 2 different text in 2 different i2c displays.
Here's the current code where the i2c components work :
#include <Adafruit_SSD1306.h>
#include "SdFat.h"

#define OLED_RESET 4
Adafruit_SSD1306 Display1(OLED_RESET);
Adafruit_SSD1306 Display2(OLED_RESET);

int i, j;

void setup()   {

  //Serial.begin(9600);

  Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  Display1.clearDisplay();
  Display1.display();

  Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
  Display2.clearDisplay();
  Display2.display();

}

void loop() {

  Display1.setTextSize(1);
  Display1.setTextColor(WHITE, BLACK);
  Display1.setCursor(0, 0 );
  Display1.println("Hello");
  Display1.display();
  Display1.clearDisplay();

  Display2.setTextSize(1);
  Display2.setTextColor(WHITE, BLACK);
  Display2.setCursor(0, 0);
  Display2.println("There");
  Display2.display();
  Display2.clearDisplay();

}

And here is the code where the components doesn't work
#include <Adafruit_SSD1306.h>
#include "SdFat.h"

#define OLED_RESET 4
Adafruit_SSD1306 Display1(OLED_RESET);
Adafruit_SSD1306 Display2(OLED_RESET);
SdFat SD;

int i, j;

void setup()   {

  //Serial.begin(9600);

  Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  Display1.clearDisplay();
  Display1.display();

  Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
  Display2.clearDisplay();
  Display2.display();

}

void loop() {

  Display1.setTextSize(1);
  Display1.setTextColor(WHITE, BLACK);
  Display1.setCursor(0, 0 );
  Display1.println("Hello");
  Display1.display();
  Display1.clearDisplay();

  Display2.setTextSize(1);
  Display2.setTextColor(WHITE, BLACK);
  Display2.setCursor(0, 0);
  Display2.println("There");
  Display2.display();
  Display2.clearDisplay();

}

Adding any sort of code that involves the sd card library like adding files or declaring the SD command itself would make the i2c components unusable, does anyone know how to fix this?

I don't see SD library in your sketch. You use SdFat

The same effects also happens with the SdFat Library

you run out of memory with the display buffers and the SD buffer

how can i test this? when i tried it with only 1 sensor and 1 display, it works well with writing the sd card. Not to mention there are no errors regarding memory when uploading the code to the nano

the memory is allocated at runtime so the build process can't evaluate it. the display library has buffer = (uint8_t *)malloc(WIDTH * ((HEIGHT + 7) / 8)))

There are no compilation errors for the memory issue, because the compiler can only calculate the global/static memory usage. The local variables are not counted there. Thags the reason why the Arduino IDE warns you at (I think) 75% memory usage. That it works with just one display supports the hypopyhsis of  running out of memory

Then how do i fix this?

A practical solution is probably to get an Arduino with more RAM.  There are a lot of those, but the Nano Every (6KB rather than 2KB) seems to make sense.  Some of the things I mentioned in answer to a similar question might be worth reading.  Even with them you might be at or over the limit though.


text:
Arduino lcd displays random chracters
I have connected arduino nano every to my lcd display. It works perfect when i put all my code in setup() part. But when i put the code in loop() it does werid things. I have to put my code in loop(), because i am reading from load cell and displaying the values that are constantly changing. The delay can't be more than 250 ms.
This works well.
#include <LiquidCrystal.h>
int Contrast=30;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup(){
    analogWrite(6,Contrast);
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);
    lcd.print("testing");
}

void loop(){

 }

When I do this next thing it works well for few seconds and then it starts to display random weird characters and stops displaying anything after some time.
#include <LiquidCrystal.h>
int Contrast=30;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup(){
    analogWrite(6,Contrast);
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);

}

void loop(){

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(millis()/1000);
  delay(250);
 }

I have tried removing lcd.clear() it didn't help.
I thought it was a problem with wiring first, but it's not.
What am I doing wrong?
Any help would be great, thanks.

What am I doing wrong? ... you are not debugging the code in a logical way ... first, display fixed text, such as hello world and increase the delay time to something like 2 seconds ... that way you eliminate the possibility that the value of millis() is somehow messing up the displayed values ... it also allows you to use a stopwatch to determine how many iterations run before the problem occurs

lcd.setCursor(0, 0); - you dont really need this funtion. lcd.clear() will always bring the cursor into the (0,0) position, automatically.

check your wiring. The code seems to be correct

Increase the delay to 500 ms or more. You don't have to write faster than 1 seconds to the LCD anyway


text:
Looking for an accurate and fast updating range sensor
I need to purchase a distance sensor that will be fixed in place and used to determine distance to the top of a fairly fast moving piston along the axial direction in line with the sensor. The top of the piston can be covered in whatever material works best for sensor accuracy, and the entire apparatus can operate in the dark if needed. Distance will range from 50mm to 500mm. Position measurement must have an accuracy range below 1.5mm. Update rate must be 1000hz or greater (i.e. update every 1ms or faster).
I see there are many options for me at high cost, but I'm limiting my budget to $500 and below for the next few days while I research more. This does not mean I won't spend whatever is needed however. As of now I've seen nothing acceptable for under that price, but it's hard to tell as many companies won't publish prices for these types of sensors.
I'm happy to explain more about the implementation if needed.
UPDATE
I wish more people were reading this post, because I have great suggestions for DIYers after researching a lot of options the past few days. Currently I'm looking at offerings from Turck.com relating to reading a magnetized strip. This would read position from the side rather than from above or below as I describe in my original question. Turck calls it their "LM-2 line" and some options look pretty affordable and quite a bit under $500. Here's a brochure they provide - it documents how they read a magnetic strip: https://www.turck.us/attachment/B1027.pdf
NOTE
There is one answer here related to a different sort of solution involving a device which reads a code every 0.5mm or 1.0mm taped to a rod which is attached to the piston. Device would read in direction perpendicular to direction of motion. This would probably be my 2nd or 3rd choice if I'm unable to find an affordable sensor as described in my question.
NOTE 2
If I had time I'd implement the following solution which I wish I had thought of a month ago: tape a 300mm strip of reflective material which varies in reflectivity along its length. shine a laser on the tape and detect amount of light which reflects. simple solution, easy to calibrate and (if I knew where to get the tape) should be low cost.

None of this discussion has any real bearing on the question. I'm moving it to chat.

Comments are not for extended discussion; this conversation has been moved to chat.

what moves the piston? ... is there any possibility to measure the motion of some other part of the device and calculate the position of the piston?

magnetic fields move magnets in the piston. the piston is attached to a long rod. i'm using that for sensor to detect piston motion. yes, i'd rather measure resistance along a linear pot. however, as accuracy is key I would need to tackle issues related to variable stray capacitance as well as resistivity as it changes wrt. temperature. or i could try my best to calculate position via accelerometer input, but there are bigger unknowns there. in any case, i'm not sure why laser sensors would need to be so expensive. but they are because industry pays for them.

here's an idea I wish I had time to implement: at every millimeter along the rod there can be a series of 1's and 0's that represent the distance value. if I had something that could read that every 0.5 ms ... i still think it would be either slow or inaccurate though. probably too slow.

If you haven't found the answer you want @John Ahearn, maybe it's time to step back.  For instance, is the piston connected to a crankshaft?  It might be easier to measure the rotation of the crankshaft than the position of the piston.  There are loads more ways of doing this as there are loads of rotation sensors for servo motors.  In fact, I'm betting this is a commodity market where the scale of manufacturing is in your favor.

You said: "could read that every 0.5 ms ... i still think it would be either slow or inaccurate though. probably too slow".  Again, step back.  What do you really need?  Why can't you use software to interpolate the position of the piston ever 0.5 ms from, say, samples taken ever 2ms?  And if linear interpolation isn't accurate enough you could curve fit it.  Also, is this a repeatable event?  If so sample a number of repeated events and phase shift the samples just a bit each time building an almost continuous representation of the piston position after a certain amount of time.

Thanks for the input. I've found this is the issue with similar forums and comments: i'm restricted to the guidelines and attitude of respondents, then the crapshoot of "anyone know the topic and want to help". The result is that I'm either too detailed or not detailed enough. My post is a result of "stepping back" at least 4 times. I understand in great detail my apparatus, requirements and most product offerings. I've posted here with what looks to me like a spot on question awaiting a response from the right person. I have options as mentioned. No need for more analysis. Just budgeting.

I'm currently considering a Wenglor OPT20XX product going for about $750 after shipping. It will work like a charm. Overkill even. I'm looking for something similar that's cheaper. I'm not sure it's ok to post the link here and I'm tired of being downvoted and/or criticized for no reason so I won't take a chance by posting it. The product is the Wenglor OPT2003 and if needed I'll have to fork out $250 more than I want.

And no, I didn't know this product before yesterday. The $750 is down from much more expensive offerings I was researching.

Rotary anything doesn't work and isn't a good solution at all even if it did. Many reasons for that.

btw - linear interpolation from 2ms samplings would be the worst case scenario. I don't see any reason at all for why I'd have to settle for that when I'm willing to spend $500. reminds me of an old line from Star Trek: Spock, who was attempting to "construct a mnemonic memory circuit using stone knives and bearskins". The difference is that I don't need stone knives and bearskins.

Regarding Note 2: What about using your favourite word processor to produce a gradient background that's 300 mm long, then print it out onto photographic paper with your printer, then tape it to the rod?

do you mean a printed surface for reflectivity gradient? what is the material that the light reflects off?

i'd worry about noise. spurious reflection.

Inside an inkjet printer, I've found a clear plastic strip with photo-engraved (loose approximation) lines perpendicular to the length of the strip. This strip passes through an optical pair, one side illuminates, the other reads. The strip stretches the entire width of the printer and if I recall correctly, the reading module is on the print head carriage. Consider that many printers are described as 600 dots per inch, which would create a resolution on the strip of 1/600" / 0.04 mm.
Additionally, I've discovered circular plastic encoders on which the rings of black/clear alternated the segment counts with each expanding ring. That is to say, the first ring was half black, half clear. The next ring out was 1/4 black/white alternating, the one following was 8 segments, then 16, etc.
This required a reader for each ring, but provided an absolute reference rather than a relative reference as is the case with the linear strip. One could create a linear strip which would work in a similar manner. One level would be half black, half clear, the next layer would be 1/4 black/clear, etc.

The requirement for 500 mm fits into a binary 512 value, which would require 9 stripes and provide for the accuracy noted in the post.
The aspect I can't answer is the speed of the encoding, although I suspect that any design based on an optical reader could be optimized to work.
I found an article at rp-photonics.com

When light is diffracted at the traveling refractive index grating in
an acousto-optic modulator, the diffracted light experiences a shift
of optical frequency which is plus or minus the acoustic (or drive)
frequency. That effect (which can be interpreted as a Doppler shift)
is exploited in acousto-optic frequency shifters.
Drive frequencies are typically between some tens and hundreds of
megahertz, rarely more than 1 GHz. The resulting change of optical
wavelength is quite small. For larger frequency shifts, or for
realizing very small frequency shifts (e.g. only a few MHz), one may
cascade two or more devices. It is also possible to use a double pass
through a single device in order to obtain twice the frequency shift.

I think from reading that excerpt that the long strip in the inkjet printer is the traveling refractive index grating. I had not considered that a low-power laser could be substituted for a simple optical pair. Doing so would provided even better resolution.
If your project allows for a strip of sufficient length to be attached to the piston, with assurance that it won't buckle under acceleration and jam in the sensor, you'd probably make it work.
But wait, there's more. I can picture the rod on the piston alternately obscuring and uncovering a digital design, which is constantly scanned by a laser. This reduces the number of parts in close contact and possibly the moving mass.

It's a great idea. I may try to implement along these lines, but as I've indicated in my comment above there's no reason to think this is more accurate or as fast as a TOF or triangulation solution setup in the manner I suggest at an affordable cost. The advantage  is a fast binary calc can turn the scanned lines into usable measurement values. The disadvantage is uncertainty of the setup which, even if calibrated perfectly, is not guaranteed to be accurate enough for my needs. Vibration is the first issue to be considered for instance.

Clarifying my comment just above: I'm referring to vibration of the rod which is attached to the piston. Not vibration of the sensor/reader which would be still.

You can mitigate vibration by having supports at both ends of the traveling rod. I suppose if you have a piston running at 1 MHz or higher, you'll have some imbalance in the entire assembly. Horizontally opposed pistons?

Sorry wasn't clear : the rod is as vibration free as is possible. That doesn't mean it won't be an issue. In fact I'm certain it will be, and if I have to spend time and money lessening it even further than I've defeated the purpose and might as well stick with the original idea of a (likely) expensive position sensor.

An alternative could be to use a Gray code instead of the binary code.

yep. that was meant to be a placeholder for "code". please see my note up top regarding magnetic strip reading


text:
Can a Windows 10 computer use Arduino IDE 1.8.10 sometimes AND use Arduino IDE 2.0.0 the rest of the time?
Can Windows 10 computer use  Arduino IDE 1.8.10 sometimes, AND use Arduino IDE 2.0.0 the rest of the time?

why are you asking? ... have you tried to use both versions?

If it collides, you can add subdirectory "portable" in 1.8.10 and everything will be stored there (boards, sketches, libraries...)

https://forum.arduino.cc/t/is-the-arduino-2-ide-installation-alongside-the-classic-ide-or-a-replacement/698588/2

I see no reason why not. I have several versions on my Linux machine however each is in its own directory, I would assume you need to do the same with windows.

i do it the other way around.


text:
Is this circuit damaging my arduino/components?
I'm building a system as follows:

There are two pumps which lower and raise the level of the water
There is an ultrasound detector which measures the level of the water
While the water is too high, water is pumped out
While it's too low, water is pumped in

There are thresholds to prevent micro-adjustments, the system doesn't flip-flop back and forth.
However after a short while the ultrasound sensor stops working, until I power the system off and on again. My electronics knowledge is extremely rudimentary, but I know motors can be nasty to other components?
I've included my circuit diagram, should I be doing anything about that? I'm using reed switches to turn them off and on, but the ground and 5v rails are all tied together, and powering the arduino too via VIN.

Motors are inductive loads (they contain coils) that generate voltage spikes when switched off. These voltage spikes can indeed be nasty to other components.
You need to add a flyback diode in parallel with the motor, with the cathode connected to Vcc.
It will normally not conduct current, but when the motor is switched off, because the voltage spike is negative, it will provide a path for the current and allow to dissipate it through the coil's internal resistance.
As pointed out in the comments, it's also a good idea to (always) add an electrolytic capacitor (> 100 µF) close to the ultrasonic detector to filter out this kind of spikes.

It might also be a good idea to put a capacitor of >100 μF between Vcc and GND, close to the utrasonic detector. Flyback diodes need to be placed between the reed relay and Vcc, in parallel with the motors, with the stripe (cathode) connected to Vcc.

Hopefully you are powering the Arduino Vin with at least 7 volts. We know the Arduino a power supply it is NOT so where does the 5V come for the motors? You need to post technical links to the hardware items you are using. Are you calling relays reed switches? D11 and D12 sound like port pins, normally they cannot drive relays unless they are designed appropriately. I would suggest you either buy another set of electronic parts or stop using it until the problems can be determined. As far as a circuit diagram does not show the information needed. A schematic, not a frizzy thing is much better.

We don't know what the OP uses, but if you use relay modules designed for use with an arduino, they include the transistor to drive the relay as well as the flyback diode, at least for the relay.


text:
How can I send 2 orders using nRF24L01
My project is to control a servo with a joystick using nRF24L01. I have this code working well, but the problem is that I want to add a lamp in the receiver side, and a switch in the transmitter side. I had tried so many codes from the internet, but nothing works. When I implement the code for the led, the servo and the joystick will stop working unfortunately.
Maybe the problem could be solved by transmitting on 2 channels each channel has a command.  But, the question is how this is the transmitter code that is working normally :
Transmitter Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";

void setup() {

  radio.begin();
  radio.openWritingPipe(address); // 00002
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
delay(5);

 radio.stopListening();
  int potValue = analogRead(A0);
  int angleValue = map(potValue, 0, 1024, 0, 23.5);
 radio.write(&angleValue, sizeof(angleValue));

  delay(5);
  radio.startListening();

}

and this is the receiver code:
Receiver Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>

RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
boolean button_state = 0;

Servo myServo;

void setup() {

    Serial.begin(9600);
  myServo.attach(5);

  radio.begin();

  radio.openReadingPipe(0, address); // 00002
  radio.setPALevel(RF24_PA_MIN);

}

void loop() {

  delay(5);
  radio.startListening();

  if ( radio.available()) {
while (radio.available()) {

      int angleV = 0;
      radio.read(&angleV, sizeof(angleV));
     myServo.write(angleV);
      }

    delay(5);
    radio.stopListening();

  }}

i had tried soo many codes from the internet ... that is your problem ... copy & paste programming ... please do yourself a favor and learn what your existing program is actually doing ... you may find that it is actually easy to add another piece of data to the transmission


text:
ATMega32u4 - Sending and receiving data through TX and RX

Hi everyone,
first time here on the forum, so, apologies if I'm doing anything incorrectly.
Long story short, I built a device that takes voltages in and transform them into midi data. I used an ATMega328P PU and midi data exit through the TX pin of the chip, into an optoisolator and then go to a jack. Everything works great.
I decided to make the next step, switching to an ATMega32u4, my main goal is to have those midi data exiting simultaneously out from the jack and from the USB which also act as a power source for the device.
The device is now recognized by my laptop as a usb device, so I assume all the USB wiring are correct, however, I have no midi data exiting from any of the jack or usb and I don't understand why. Of course I changed all the pin assignment according to the ATMega32u4 datasheet.
I use Arduino IDE for programming and the device is recognized by the IDE as "Arduino Leonardo": it has to be said that I've always used Arduino UNO and Nano, so I don't know if there are any differences in terms of code when it comes to different boards.
My assumption is that, for some reason, TX pin remains silent. I guess there must be something wrong with my code setup: I simply typed
Serial.begin(9600);

Are there any specific Leonardo libraries I have to be aware of?

Serial is the USB CDC/ACM port, not the TX/RX pins. You need Serial1 for that.

We can't really help you properly unless you show us your code. Without that we're only guessing.

Also, for what it's worth, MIDI carried over USB uses its own device class; it's not normally carried over USB via "Serial" (CDC) class.

https://arduino.stackexchange.com/tour


text:
Sending a request with a NodeMCU when a key is pressed
I want to send a request to a server with the GET method with URL parameters when a key is pressed on the NodeMCU. But I can't get this to work; I get the below error in the serial monitor:
 ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld

My main code:
#include <ESP8266WiFi.h>

const char* ssid = "MobinNet1365";
const char* password = "G12229M1Q64";
const char* host = "webhook.site";

const int button = 8;
int temp = 0;

void setup() {
  Serial.begin(115200);
  pinMode(button, INPUT);
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}

My request sending code is below:
#include <ESP8266WiFi.h>

const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "";

void setup() {
    Serial.begin(115200);
    delay(10);
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;
  Serial.print("connecting to ");
  Serial.println(host);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  String url = "/";
  /* url += "?param1=";
  url += param1;
  url += "?param2=";
  url += param2;
  */
  Serial.print("Requesting URL: ");
  Serial.println(url);
  client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

And my key press detector code is below:
const int button = 8;
int temp = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop() {
  temp = digitalRead(button);

  if (temp == HIGH) {
    Serial.println("LED Turned ON");
    delay(1500);
  }
  else {
    Serial.println("LED Turned OFF");
    delay(1500);
  }
}

My circuit is:
NodeMcu => MicroSwitch
VIN => C
D0 => NO
G => 10k => NO
How can I make it so that when the key is pressed it sends a request?

I don't quite understand--what is ypur actual code? One chunk of code never initializes "host", another does. What is the actual code that causes the error? Are you making a request between two NodeMCUs?

No its just for sending a request to a server when a key pressed but i get "ets Jan  8 2013,rst cause:4, boot mode:(3,7)
wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld" error and that code has header named main code is my actual code

Please include only the relevant code.

why do you believe that the ets Jan 8 2013,rst cause:4, boot mode:(3,7) .... message is an error message?

IMHO, some consideration :

const int button = 8;
const int button = 5; // CHANGE TO Pin "D1 GPIO5"

GPIO8 is used to connect the flash chip, you may change to Pin "D1" which is GPIO 5.

Check with your board's pinout.

to prevent non-stop keep calling within in the loop, you may use millis();

for example :
void GetUrl() {
    temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    String link = String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n";
//    Serial.println( "link : " + link );
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}

unsigned long previousMillis = 0;
const long interval = 1000 * 0.5; // 500ms (0.5 sec)

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    GetUrl();
  }
}

Reference :
https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
https://iotbyhvm.ooo/gpio-pins-esp8266/


text:
How to read from and write to rs232 device from/to Arduino
I would like to read data from a rs232 device (SL-5868P Sound Level Meter).
protocol and more : https://sigrok.org/wiki/Colead_SL-5868P.
I already have a Python script to read the data with a TTL to USB converter (without Arduino). Now I also want to be able to read the meter via the Arduino.
I've bought a RS232 to TTL Converter (MAX3232). I get either very weird characters (baud rate set correctly), or not logical numbers. With the MAX chip I get no data at all.

To see if there is data ready, 0x10 must be sent by the meter.
To get the data, send 0x20.

Would someone be willing to help me out a bit? That would be really nice. Maybe there is someone who has experience with reading (and writing to) RS232. The only thing that matters is how I can retrieve the data. I know the rest what needs to be done with software (conversion, etc.). I'm not that familiar with Arduino's .
The code below is an example from SoftwareSerial (a little bit modified). I'm using the Arduino Uno.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(2400);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(2400);
}

void loop() { // run over and over
  if (mySerial.read() == 0x10) {
    //mySerial.write(0x20);
    Serial.println("Data available");
    Serial.println(mySerial.read());
  }

  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
  //delay(300);
}

And the current schematic (sorry for my drawing skills)

you only read one byte after the 0x10. is it ok? If you send numbers from Serial Monitor they are sent as text. I doubt the meter accepts "10\r\n" (0x30, 0x31, 0x0D and 0x0A)

Joost, I have a very similar problem. Were you able to make it work?
I don't have enough reputation to comment on your post ;) therefore, I am posting my query as an answer here.

You didn't show how you connected the MAX3232, so I cannot say anything about that. But I can write something about your code and how the data gets received on the PC.

On the PC: Here it is important how you are reading the serial data on the PC. The Serial Monitor for example expects ASCII encoded text. It cannot correctly display binary data. That is the reason, that you get weird characters with the correct baudrate. The data is correctly received, but it doesn't represent ASCII characters. It is just binary data and interpreting it as ASCII characters will not make any sense.
Also it just sends ASCII encoded text, no binary data. So when you are sending "10" it will send the bytes 0x31 and 0x30, plus any line ending, that you have selected (\n aka 0x0A if you selected newline as line ending). As your device speaks in binary data you might wanna speak binary to it. So you either need to decode the ASCII data on the Arduino, before sending it to the device, or you need to use a different serial program, which can handle binary data.

Your code: First look at this line
  Serial.println(mySerial.read());

Here you are reading exactly one byte from the SoftwareSerial interface and then you are printing it. Serial.read() or SoftwareSerial.read() only read one single byte from the buffer, but the data from your device spans over multiple bytes, as described on the wiki page, that you linked. Look at the table titled "Data structure". The returned data consists of 10 bytes in total (numbered from 0 to 9), where bytes 3 to 7 contain the actual data. The rest gives configuration and status data, a header as packet start and a checksum to check for transmission errors. So reading only one byte isn't enough you need to read all of them.
Then you are Serial.print()ing the data. The print() function and its siblings are formatting the data human readable. That might help you here, but you need to make sure, that the resulting output is really readable for you, especially when you are reading multiple bytes (as you need to do, as explained above). Here you need to make a decision: Either

you could decode and format the binary data from the device on the Arduino and send the human readable format over Serial
or you could send the binary data straight to the PC and decode it there with a fitting program (either a Serial program, which can handle binary data, or your own program, for example with python or processing)

If you go the first way, you should first read the different parts of the message and then print these parts with additional text, that explains, what data means what. Otherwise you would have just a long line of numbers, which are also rather difficult to read. Also you might wanna decide on a number base. I think only decimal or hexadecimal are really relevant here. For that you could use Serial.print(value, DEC) or Serial.print(value, HEX), which tells the Serial library to use the specified number base.
Now about the actual data format: The data format is described with

BCD-encoded value, one byte per digit 0x00-0x09. 0x0a means ignored digit. The last digit represents the decimal.

on the linked wiki site. So while this is still binary data (not ASCII encoded), each byte represents a decimal digit of the actual value. You could decode it accordingly. So I guess a byte sequence of 0x01 0x00 0x02 0x09 0x07 would mean 1029.7. As you wrote, that you already know how to convert the data, I will not go deeper about this here.
And lastly you need to rethink your program structure. The workflow with your device is the following:
  Arduino waits for device to send data ready byte (0x10)
  device sends 0x10
  Arduino sends 0x20 (command to send data)
  Arduino waits for device to send at least 10 bytes of data
  device sends a complete data packet with 10 bytes
  Arduino interprets the data in the received packet and acts accordingly
  repeat

You need to follow this workflow and also anticipate, that the data transmission takes some time (especially at the really slow 2400 baud). For this a Finite State Machine (FSM) is a good fit (there are many extended descriptions about FSMs on this site, for example my answer to this question or this question, though there are many more, which you just need to search for). We just track at which part of the workflow we are currently and execute the according code. Something like this:
  enum ReceiveState {IDLE, RECEIVING};
  ReceiveState rec_state = IDLE;

  void loop(){
      if(mySerial.available()){
          switch(rec_state){
              case IDLE:
                  if(mySerial.read() == 0x10){
                      // data is ready, command to send data
                      mySerial.write(0x20);
                      // change state to receiving
                      rec_state = RECEIVING;
                  }
                  break;
              case RECEIVING:
                  if(mySerial.available() >= 10){// only read data, if a full packet was received, at least 10 bytes
                      // Here you need to decode the binary data and handle it accordingly (for example printing in the wanted format)
                      // Reset rec_state afterwards to be ready for the next time, that data is ready to read
                      rec_state = IDLE;
                  }
                  break;
              }
          }
      }
  }

That might seem like a bit of overkill, but the concept is very important in the Arduino world and it is very powerful. Also it makes it easier to accommodate workflow structures.

Thanks for the detailed explanation. This is going to help me. But I still have one problem. When I add debug printlines, it won't be printed. So, no data is coming in. I think it has to do with the MAX3232 chip. I've added a simple schematic in the main post. Maybe it isn't correct connected, or the wrong chip? Connect RS232 directly to Arduino is not a option if I understand correctly.

Hi and welcome to the wonderful world of Arduino. It appears that you have picked-up Arduino with ease. Your program is almost there. Your wiring connection diagram looks to be correct.
When I am doing a project like this, I won't write my full application first. Instead I write a series of test programs to make sure each chunk is performing exactly as I want it to.
I would start by writing a program that just passes the serial information recieved from the Sound Level Meter and displays it on the serial monitor. Something similar to this:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open USB serial communications
  Serial.begin( 2400 );
  Serial.println("USB Serial is up and running");

  // set the data rate for the SoftwareSerial port
  mySerial.begin( 2400 );
}

void loop()
{
  if ( mySerial.available() )
  {
    // Write the serial from the S.L.M. to the USB (debug) serial port
    Serial.write( mySerial.read() );
  }

  if ( Serial.available() )
  {
    // Write the serial from the USB (debug) serial port to the S.L.M.
    mySerial.write( Serial.read() );
  }
}

This program should be enough to communicate with the Sound Level Meter. But this leads me to my first concern - choice of serial monitor.
While the Arduino built in serial monitor is adequate it is only really good for sending/recieving text. (Plus it sends a CR/LF every time you hit enter.) I can see straight away that you require to send/recieve hex numbers. Hex numbers won't display well on the serial monitor.
Instead I prefer to use a terminal program by "der-hammer" called hterm. (Screenshot here). It lets you view the input in ASCII, hex, bin and decimal. Likewise it lets you send ASCII, hex, bin and decimal or a mixture of each. When sending information, you can configure it so that it finishes the data with either a line feed, a carriage return, both or none.
By the sound of it, you don't want a CR or LF at the end of the data you send. So in the "Input Options" set the "Send on enter" to "None".
For the recieved data, you need to view that in hex so make sure the "hex" box is checked just above the recieved data. (Uncheck "ASCII".)
You could create a loop-back test by removing the Sound Level Meter and instead link the RS232 Rx to the RS232 Tx. This will allow you to see on hterm exactly what the Sound Level Meter sees when you send data.

Issues with your program
  if (mySerial.read() == 0x10) {
    //mySerial.write(0x20);
    Serial.println("Data available");
    Serial.println(mySerial.read());
  }

The section of code will only read one byte of data after it has detected 0x10 (See the Serial.Read() reference page). Anything more than that will get consumed by the next time the if statement checks the serial line for 0x10.
I notice in the line Serial.println(mySerial.read()); that you are reading the data in (which is in hex format) but then trying to write it out in ASCII by using the println() function. This will not give you the output you desire.
Also, after detecting 0x10 it reads the software serial line for one more byte - meaning if there is nothing following the 0x10 then the mySerial.Read() command will hang for 1s until it timeouts.
if (Serial.available()) {
  mySerial.write(Serial.read());
}

As others have pointed out, using the serial monitor will send this as ASCII characters (and include a CR/LF character(s)) instead of the hex value that you want. Kudos is given to you, that you chose mySerial.write() instead of mySerial.println().

My Take on Your Program
The follwoing code is untested.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(2400);
  // The wait for serial port to connect is not needed for Arduino Uno
  Serial.println("USB Serial is up and running");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(2400);
}

void loop()
{
  if ( mySerial.available() )
  {
    int recievedByte = mySerial.read();
    Serial.write(recievedByte);    // Send to USB serial - assuming using hterm in hex
    if ( recievedByte == 0x10 )
    {
      mySerial.write(0x20);
    }
  }

  // You could remove the following code - data must be in hex.
  if ( Serial.available() )
  {
    mySerial.write(Serial.read());
  }
}

Thank you so much for your effort to explain this all. But as said earlier in the other post, there is totally no data coming in. Maybe there is something wrong with the MAX3232. With debugging (add println's in if-statements), there is also no result. Only when I disconnected and connect the GND again I get data from the mySerial.available() if statement.

Which GND are you referring to?

It's working for now. I've disconnected the MAX3232 chip and connected the RS232 device directly to the Arduino. I know, it's not a best practice, but it is low voltage.


text:
Arduino freezes if I do NOT do Serial.println() at least TWICE
Hii I have a big project, and found this when I tried to remove all the test code.
To summarize:

I have a variable that I use as a buffer for string operations called char internalbuffer[32] declared in my file xstrings.h, it is very important and it is used a lot in the other files.
If I call, in Setup, Serial.println(internalbuffer) twice or more, the arduino will run normally.
If I call, in Setup, Serial.println(internalbuffer) once or not at all, the arduino will NOT run any code.
I tried, with no result, referencing in other ways internalbuffer.

You can see the main.cpp file here. (you can check the entire repo here)
My setup:

Arduino Nano (Clone) Old bootloader
SSD1306 (Clone) Oled 128x32 with ss_oled library as controller
3 DIY Buttons
VS Code with platformio installed.

I've been trying to fix this myself for 2 days now, but got nothing and I'm pretty new to c++ and arduino, any tips or guidance is accepted.
Edit:
What I have tried:

Replacing the 2 Serial.println(internalbuffer) to printing any string, didn't work.
Instead of the serial prints, add a delay(x), tried from 10ms to 5000ms didn't work either.
Removing while(!Serial) seems to have no effect, so I removed it.

New things I've discovered:

Moving the serial prints out of the if (rc != OLED_NOT_FOUND) that checks for the oled initialization is not working, so that's new.
There is a special place, that if I place the prints there, the arduino keeps calling setup like it was the loop function or something.

I´ve created a pastebin showing these last 2 items more clearly.

what happens if you call Serial.println("test123") twice?

try delay(10); instead of the two prints

Is there a specific reason you have while (!Serial); at the start of your code? On a nano it should do nothing, but you never know...

Also note that the SSD1306 OLED display takes most of your RAM, leaving you very little to play with. There's a very high chance it's failing to allocate its internal buffer and crashing.

jsotola replaced the prints as you suggested, didn't work.
Juraj added delay(50) before the 2 jsotola prints, didn't work, removed the jsotola prints and left only the delay(50), also didn't work.
Majenko, I've added that while(!Serial) in a desperate moment to fix this problem. Also, I don't think that is, because it runs nice and smooth when the 2 prints with internalbuffer are ran.

then you have some error in your code, which causes 'undefined behavior'


text:
How to use 5v and 12v addressable led strip together
Hi guys I’m new to this forum and also not much experience about led lights question already asked but didn’t get any detailed answer I want to know can I provide working data signal to 2 different 5v and 12v addressable led strips or what should I do to work them in same patterns at same time it will be really big help please and thanks in advance I’m sure I’m at right forum because usually I get all my answers by you guys without even asking

Actually this is not a forum, but a Q&A site. About what LED strips are we speaking? Can you maybe provide links to the products or provide part numbers?

Welcome! Would you mind to provide some details, like links to data sheets of the LED stripes, and a (simplified) schematic? Or if this is a software problem, show us some code? -- Since you're apparently have been here some time already, you know for sure that you can [edit] your question, don't you?

use a level shifter

Thanks busybee for helping me to make my project at the moment I have little knowledge about 5v strip it’s sk6812 5050 individually addressable but soon I can send you all the information with data sheet because 12v strips still not in my hand but thanks so much helping me I promise as soon as I got the shippment I’ll provide all the details ok dear I’ll get back to you asa I get me strips


text:
Serial monitor and plotter coming up blank
I'm looking to calibrate a load cell and for some reason, when I open both the serial monitor and plotter, they both come up blank. My plotter is set to the corresponding 9600 baud, however, this doesn't seem to change anything.
here is the code below:
#include "HX711.h"
#include <Servo.h> // Include the Servo library

#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

#define LOADCELL_DOUT_PIN  3
#define LOADCELL_SCK_PIN  2
int servoPin = 5; // Declare the Servo pin

HX711 scale;

Servo Servo1; // Create a servo object
float units;

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 scale demo");

  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

  Serial.println("Readings:");

  Servo1.attach(servoPin);  // We need to attach the servo to the used pin number
}

void loop() {
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
  Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
  Serial.println();

 Serial.print("Reading: ");

 units = scale.get_units(10);
     if (units > 3.35 && units < 3.45)
     {
       Servo1.write(180);
       delay(1000);
       Serial.print("Success. Door is now OPEN!");
     }

       else
     {
       Servo1.write(0);
       delay(1000);
       Serial.print("Success. Door is now CLOSED!");
     }

}

here are screenshots of the potter and monitor:

Have you tried a simple serial test program at different baud rates? Several of my clones only work at 115200.

I don't think you can use both serial monitor and serial plotter. They use the same port. Use one at the time.


text:
AT+IPSCAN HC-05 Command
I have a HC-05 module, directly connected to an STM32 via UART interface and connected simultaneously to a mobile application in order to exchange
real time data. I am trying to reduce the power consumption of my HC-05 BT module. After few researches, I discovered that if I set the command AT+IPSCAN and
put the Query duration (2nd parameter) and the Call duration (4th parameter) to 1, the current dramatically decreases. Thus, the energy which the BT
module consumes decreases as well. My problem is I didn't understand how and why it decreases ? What are exatly the parameters AT+IPSCAN and what each one
does mean ?
Thank you for providing me a detailed description of the AT+IPSCAN command as well as its parameters.

https://s3-sa-east-1.amazonaws.com/robocore-lojavirtual/709/HC-05_ATCommandSet.pdf


text:
arduino labview basic serial communication
I am trying to have a 2way serial communication between LabVIEW and Arduino. I tried to make a basic program to grasp the concept but it does not seem to work.
Labview (2 int values) >> Arduino read
Arduino (1 int value) >> Labview read
Here, my LabVIEW program has 2 double variables which I put in numbers (they will later be cast to an int). Then, it is put into an array and converted to a comma-separated integer string. This is then written to the VISA port.
On the Arduino side, the serial port is read using the serial.parseInt function. Then the int is then converted into a 2-byte array which is then written to the serial port.
This is then read by the LabVIEW with VISA read and the string is converted to a byte array and reconstructed into an I16 integer.
Currently, the results are as follows:
The sent number are 80 and 80 and after being received by the Arduino and relayed back, the results displayed is 6961 as a string and 26977 in int form.
The arduino program works with the serial monitor where if the number 19789 was put in, it would output MM.

void setup() {
  Serial.begin(9600);
  while(!Serial){;}
  Serial.println("serial ready");
}

int input;
int input2;
void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()>0){
    input = Serial.parseInt();
    input2= Serial.parseInt();
  }

 byte buff[2];
  if (Serial.read() == -1){
    buff[1] = (byte)input;
    buff[0] = (byte)(input>>8);
    Serial.write(buff,2);
  }
  delay(100);
}

labview VI

It's not entirely clear what you're actually sending or receiving. FWIW if you shift 80 (0x50)>> 8 you're going to end up with zero. You're also throwing input2 away, perhaps that was intentional. It might be a good idea to isolate each side of the comms, e.g., test the Arduino code in isolation until it's doing what you actually want, and introduce LabView afterwards.

yes, I know that it will be removed since int is 2 bytes and I would like to split the int into 2 bytes in the array for sending. Then these 2 bytes will be reconstructed later in LabVIEW. this is done in case i am sending a number larger than 256.

It's an int, you can just check if it's > 256 and stuff 0 info buff[0]. The intent isn't particularly clear, though.


text:
How to switch HC-05 from DATA mode to AT mode?
I am asking how to enter from the data mode to the AT command mode without restarting and disconnecting any power supply. In other words, I am trying to make a driver to handle HC-05 module and now I have to switch between DATA mode to AT mode. When I try to switch backwards, it worls ( by putting off the EN pin and then send “AT+RESET” ) but from DATA mode to AT Mode I can’t reset the module. Anyhelp please ?

What Microcontroller do you use? You tagged both arduino uno and stm32

old time modems used to have an escape sequence that caused the modem to drop out of data mode into command mode ... the sequence was +++  .... the HC-05 may have something similar .... though, I suspect that a hardware pin is involved

@PythonSchlange I am using stm32

I am pretty certain there is no way to enter command mode from data mode without resetting the whole module.  The only way to enter command mode is by setting the KEY pin high, and that pin is only read during the initialization phase of the module - and that means either a power cycle / reset, or a command-initiated reset.
You could either:

Provide a power control circuit which turns the module on and off (MOSFETs are good for this), or
Modify the module to attach a wire to pin 11, the RESET pin, and pulse that LOW to reset into command mode (I assume LOW, since that's the most common, though I haven't found anything to confirm it yet).

Thank you for your response. I think that the best solution is the first one and I will search about a MOSFET type that responds to my application. Best,