text:
No response from instrument via serial communication
I am using a Teensy 3.6 to communicate with an external instrument via a serial connection. However, I am not able to get the instrument to respond to my commands.
The idea is to send a command from the computer via the serial monitor to the Teensy, which then can send it to the instrument (I know that the Teensy is not needed with this configuration but this is just for testing of a more complex set-up).
The instrument uses an RS232 connector so I use this RS232 shifter to connect it to the Teensy. The serial communication settings of the instrument are: 38.4k baud rate, 8 data bits, 1 stop bit, no parity and a carriage return character should mark the end of the command string.
A simple example of my code to read the input from the serial monitor and send a command to the instrument:
#define FILTser Serial1
char Command;

void setup() {
  Serial.begin(9600);
  FILTser.begin(38400);
  Serial.println("<Teensy is ready>");
}

void loop() {
    Command = 'X';
    recvCmd();

    // Start sampling command
    if (Command == 'S') {
       FILTser.write("pumpctl=1\r");
       FILTser.write('\n');
       Serial.println("Sampling started");
    }
}

void recvCmd() {
    if (Serial.available() > 0) {
        Command = Serial.read();
    }
}

If I read the output from the Teensy on the Serial1 port with Putty I get the message correctly. If I send the same command directly to the instrument with Putty or Python I get the instrument to respond as I expect. This means that the instrument is working and the serial output from the Teensy is also fine so I really don't understand what could be wrong.
I know that the instrument is not responding because I would expect a pump to turn on when it receives the command. Additionally, I tried to read the answer of the instrument on the serial port and I was receiving a -1 but I would expect OK for a good command and ERR if the command is not recognized.
To read the instrument answer on the serial port I tried using both a single character with Response = FILTser.read(); and also a full string using the code from here.
An example of the Python code that I use to send commands to the instrument is the following:
import datetime
import serial
import io
import time

# =============================================================================
# Configure serial port
# =============================================================================
ser = serial.Serial()
ser.baudrate = 38400
ser.port = 'COM5'
ser.timeout = 1

#%% Define FILT functions
def FILT_send(commnd):
    ser.write(commnd.encode('ascii'))
    time.sleep(0.5)
    value_read = ser.readline().decode('ascii')
    return(value_read)

def FILT_control():
    global q
    user_input = input('Type:\n \
    - S to start sampling\n \
    - E to end sampling\n \
    - Q to quit the program\n')

    if user_input == 'S':
        FILT_send('pumpctl=1\r')
        print('Sampling started')

    if user_input == 'E':
        FILT_send('pumpctl=0\r')
        print('Sampling ended')

    if user_input == 'Q':
        print('The end')
        q = False

#%% Main
ser.open()
q = True
while q:
    FILT_control()
ser.close()

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

The Sparkfun RS232 shifter is not a great device. It relies on whatever it's connected to (on the 9-pin port) providing the negative rail for the EIA-232 voltage levels.
That's fine when you connect to something that has those voltages available, such as a computer, but many "devices" don't - they will themselves have a similar shifter inside and will rely on whatever they are plugged in to for providing the needed negative voltage.
Put the two together and no-one will provide that negative voltage.
Instead you should use a MAX232 (or MAX3232 for 3.3V operation) based converter. This has a built-in voltage doubler and voltage inverter to convert the 5V into +/-10V to give a proper EIA-232 compliant signal which the device should then be happy with.


text:
Is SoftwareSerial possible for Samd21 boards?
I have a SAMD21G18A-MUT custom board, which has 6 'grove' connectors, of which two are I2C In and out (sharing the same MCU Pins) and also has 2 'special' 8 pin connectors attaching to Particulate Matter sensors that connect to :

PA 14, (9, 8)[Sercom 2 alt]; PB8,PA6 [PWM], PB23

PA 15,(11,10)[Sercom 0]; PB9, PA7 [PWM], PB22

which implement serial interfaces with additional control wires.
The Grove ports are :

ADC 0 (A0 & A1); Pins 9,10 [accessible only to SERCOM 0]
ADC 1 (A2 & A3); Pins 47,3 [not accessible by SERCOM]
GPIO D0/D1 [SERCOM4_ALT]; (used)  Pins 21,22
UART Tx/RX [Sercom 1]. Pins 27,28
I2C Pins (SDA, SCL), (Pins 31,32)  [SERCOM 1 PAD 0 & 1]  (only one I2C port  Used)
Debug Connector, ({ins 45,46) [SERCOM 1 PAD 2 & 3]
USB Pins (D+, D-, (Pins (33,34) [SERCOM 3]  (Used when programming)

SERCOM 5 appears to be unused, but not accessible by either ADC Port.
Do not ask me how the overloading of SERCOM 1 works...IDK
So, all but 1 Sercom ports are used up and yet I need to connect up 2 additional serial devices; a Wind sensor and a Rain Gauge.
Obviously I can connect one of them to UART Tx/Rx Sercom1; but the other one can physically connect only to one of the ADC Ports. But the only available Sercom for those pins is already used.
So, I think I need to implement SoftwareSerial on (say) A0 and A1 for the second device that I need to connect.
Any thoughts on if or how this can be done ?
My only current alternative is to add a whole new MCU Board, but that brings on space and mounting considerations.

source: Stack Exchange

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

sort: votes


text:
ESP32 BLE service not visible to Node-RED
I've been trying to host a BLE-server on my ESP32 with a custom service. I'm trying to read the service data in NodeRED, but the service IDs and custom characteristics don't show up in NodeRED whenever I import the scan results of my BLE input node in NodeRED.
The device and service both show up fine on Android using NRFtool:

However, in NodeRED, the device shows up and connects just fine, but none of the characterestics are displayed at NodeRED's end:

I'm using NodeRED version 1.2.9 with the Generic BLE node. And the ESP32 sample i'm using can be found here.
I've also tried the BLE server examples included with the BLEDevice library with similar issues.
In addition to this: I'm not sure if this is just a typo in the node's error message, or if it's a typo in the node itself, but all mentions of the type "topic" are displayed as "tpoic" in NodeRED's debug log. Though i doubt this affects the functionality of the node in any way. Nowhere in my flow is there a mention of the keyword "tpoic".

Any suggestions as to how i could make my services show up in NodeRED would be appreciated.
Thank you.

Turns out BlueZ on linux no longer supports ESP32 BLE devices. I tried the same code on a bluefruit M0 and it worked just fine.

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


text:
ESP8266 AutoConnect ACSelect selection index
I'm trying to retrieve the current selected/saved index of my AutoConnectSelect Right now i'm creating a type that reads the saved json:
 AutoConnectSelect& bright = settingsAux["scr_brightness"].as<AutoConnectSelect>();

How can i get the index of the element selected in bright as an integer?
bright.value and bright.value() are both invalid in this context.
Any help or insight into how these types work would be appreciated.

After hunting through the source, I have come to the conclusion you should try bright.selected and see what that does.

Thank you! .selected works.

The member i was looking for is AutoConnectSelect.selected I just subtract the value by one to get the index, as .selected starts from 1.


text:
Generating an 8V PWM signal
I have a control module that accepts 8V PWM signals.  My goal is to send a 500Hz PWM signal from an Arduino to an 8V PWM input on the control module.  Looks like everything generated from the Arduino is 5V.  Is there a way to generate an 8V PWM output or method of manipulating that signal to reach 8V?

How much current do you need?

I'd suggest you use a power-source that delivers you 8V. Your Arduino takes anything from 7-12V to power it and it regulates it down to 5V. But you still can access the 8V from the RAW pins. Use a MOSFET like D1703L to control the 8V with an 5V Arduino digital pin.
You just connect Drain (D) to GND and Source (S) to your RAW 8V (don't forget to put your device between the Source and RAW 8V). Your Arduino digital pin goes to Gate (G), but to not draw to much current from the pin you might want to use a resistor of roughly 1kΩ.
This is the safest way that also allows for much higher voltage and also current for up to a few amps.
EDIT
You should not connect the PWM pin to Ground on your Arduino. But you have to connect both grounds together. I'm not sure where your 8V comes from so I made a sketch where the 8V is an external source and powers your device along with the MOSFET.

Mosfets don't draw current from the gate, the resistor isn't strictly needed. Depending on the application, You might want to add a pull-down resisor on the output.

I have attempted the circuit as suggested above with an N-channel MOSFET.  This isn't working and I think my circuit is wrong.  I can't use the MOSFET to switch ground, I need it to switch the 8V.  So, here is how I connected the MOSFET:  Gate to the Arduino output (with a 10k resistor to ground).  Source to +8Vdc.  Drain to the PWM input pin on the Electronic Control Module (8V PWM input).  I have a feeling that because I'm switching the 8V through the transistor instead of ground, do I need to use a P-channel MOSFET?

No, an N-Channel MOSFET is perfectly fine. Using a P-Channel would reverse the signal (Pin High -> switched off and vice versa). The MOSFET acts like a switch. It does not matter from which side you connect it as long you watch the polarity. Can you give a sketch of your circuit?

I have added a circuit sketch to the original question.  Doesn't seem like I'm able to add an image to a reply.  Ok, thanks - I understand about the P & N channel now.  Most of the circuit sketches I look at (from Google and such) are switching ground through the transistor.  Does it even work the way I'm trying to do it, or do I need to configure this circuit differently?

I updated my answer with an Image.

The ground from the ECM and ground from the Arduino are tied together.  I made a program that cycles from 0 to 255 with an AnalogWrite function (with a 50ms delay between each iteration).  With a multimeter (on voltage setting) at the Gate I can see the voltage go from approximately 0 to 5 volts.  At the Source, I have the 8V.  But, I would expect to see the Drain cycling from 0 to 8V, but I don't.  It remains at approx. 7.4V and doesn't change.  Any thoughts on what might be the problem?

I'd suggest not to trust your multimeter. The voltage does not ramp up from 0V to 5V. It switches quickly between 0V and 5V with different duty cycles. What you need to verify the output is a oscilloscope. Only those can tell you what you really get.

The other question is: Is your device that requires the 8V PWM, really requireing a PWM or an analogue signal between 0V and 8V? In the later case you'd need at least a capacitor to smooth the square wave PWM.

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

authors: Рубен Карапетян


text:
Arduino Due - using built in ADC as a DSO causes issues at high frequencies (kHz)
I am trying to use the inbuilt ADC of the Arduino Due to measure voltage signals. The frequency range I'm interested in measuring is  up to about 30 kHz.But I'm observing a strong capacitor behaviour as I increase the frequency ( from 10kHz onwards this is quite visible).
This is most visible when measuring a square wave. When I get close to 30 kHz the signal looks exactly like the text book capacitor charge/discharge wave and nothing like a square wave. Even at around 15 kHz, the square wave looks more like a sine wave/ ramp signal than a square wave.
Based on the behaviour my guess is that a capacitor in the Arduino Due ADC is causing this (as  the frequency increases, the capacitor cannot charge/discharge fast enough). But I'm not sure whether I'm correct about this.
Even if I'm correct, how can I fix this?
Any help would be much appreciated.
Thanks.
I don't have screenshots for the behaviour for a range of frequencies, but I will attach a hand drawing of what it looks like.

Also NOTE that As the frequency increases, the amplitude of the observed wave decreases ( I couldn't show this in my drawing). Think this again links back to the capacitor charge/discharge speed behaviour.
My Vin circuit : I tested by adding a voltage follower at the right most end(not shown on the schematic), but that made no difference.

What is your signal source? If the source impedance is high, it is possible that capacitive loading is reducing the rise time, or your signal source itself has poor rise time. Show a plot where the distortion is less obvious too.   My initial thought was aliasing, so do pay attention to the whole frequency range to rule that out.

I'm using a laboratory signal generator, so don't think that is the issue.
And I am simultaneously measuring the signal using  a laboratory DSO and it shows up perfectly as it is supposed to.
I also updated my original post to show the behaviour for a range of frequencies.

Fixed : The issue was with the LM324 op-amp. It has a small slew rate (0.5 v/uS) which was causing the signal to flatten out at high frequencies. So had to change to an op-amp with a better slew rate.

Well, if you have source output impedance about 1k and Sample-And-Hold capacitance is 14pF, then RC time constant is about 14us.
You need something with low output impedance. Non-inverting Voltage Follower would be perfect for this (see source):

I already have a Non-inverting follower op-amp in my input.

Which op-amp? It might be insufficient output impedance for this aplication.

I think you might be correct.
My input impedance to the ADC might be quite big because I have voltage divider resistors to allow for a bigger voltage range. I will try with a voltage follower right before the ADC input.
BTW I'm using LM324 op-amp.

LM324 seems not be symetric in sink/source capabilities. But it shouldn't be this case, because your arduino chart seems to be symetric for charge and discharge.

So I tested with the Voltage follower just before the input goes into the ADC, and it made absolutely no difference. I expected at least some improvement, but the signal did not change at all.
I will attach my Vin circuit to the original post, it might be that the resistors I have used are just too high. But a voltage follower at the very end should have fixed that anyway. So still no progress.

Any chance to use oscilloscope? Or at least connect DSO directly (without destroying DUE)?

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


text:
HW-477 Module having VS1838B IR Sensor: Help with Pins
Ordered Universal IR Receiver and I got HW-477 module with VS1838B IR Sensor.
Good thing is datasheet for VS1838B is available but not for HW-477.
VS1838B pins as: Ref
Signal | GND | VCC
while HW-477 says:
(- minus) | R | G
Can't understand which one to follow and R is for Receiver? G is for GND and what is - (minus sign) for?
So can anyone help me with ( - R G ) of HW-477 ?
Images:

These may help?!
this & this one.
Updates:
I looked to trace the Foil (PCB Board Lines) but it didn't worked because the circuit as whole is coated.
Using Connectivity (Continuity (diode test)) option of Digital Multimeter, found these to play beep:

VS1838B
HW-477

Signal
G & (minus pin of HW-477)

GND
(- minus pin of HW-477)

VCC
R

But a person in this video saying

- is of course GND

There is a huge confusion which can only be cleared if I got a reply from seniors. I have two of this and can try one (even to burn) to better understand what is going on.
(Tried contacting the vendor about datasheet but they are not responding)

The only problem I am having is: If I press one button one single time it gives, let suppose this value: Code: 1086138583 but holding it for a second it gives another value of Code: 4294967295 which I don't know is a feature or fault. lol

That's how IR works. The first code is "You pressed the button" and the second is "You're still pressing the button". Not all buttons do it, but things like volume control do.

The problem here is that HW-477 refers not to the module as a whole but a generic PCB that is re-used (in some starter kits for sure) for many different sensors. I think the idea is that whatever device is attached to the board there's a position where the output is always the same (- = GND, R = VCC, G = Signal).
On some variants of the board you can see them labelled as - + S.

Thank You Sir! It worked. Just a note IRremote library from Arduino by Armin Joachimsmeyer latest version 3.4.0 didn't worked with legacy code found all over web, so I had to install 2.6.0 version and everything is fine now. Just a note so someone will get benefited.


text:
esp32 voltage divider readings off
Trying to read from a voltage divider circuit using two 240 Ohm resistors.  Getting a reading of 6.0, when it should be 1.65.  Circuit is powered by a bench 3.3V and both the Huzzah32 and circuit are grounded.  Using USB for the Huzzah32. Any thoughts?
  void setup()
{
  Serial.begin(9600);
}
void loop()
{
  int sensorValue = analogRead(A9);
  float voltage = sensorValue * (3.3 / 1023.0);
  Serial.println(voltage);
  delay(1000);
}

Please add the schema.

My multimeter reads the correct Vout...

this gets me closer, but still low... float voltage = (sensorValue * 3.3) / (4095);

ESP32 chips have a problem with ADC and WIFI at the same time.  Maybe disable WIFI ?

both the Huzzah32 and circuit are grounded ... are the grounds joined? ... your schematic does not show a common ground

Some clarification: I picked A9 because it is a none-wifi pin.  In regards to common ground, my circuit drawing sucks.  They have a common ground.  The final answer is to subract .12 from my input values after multiplying by 3.3 and dividing the esp 12 bit increments (4095).  Thanks for input!

First, ESP32 ADC is 12-bit, not 10-bit. therefore the formula should be:
float voltage = sensorValue * (3.3 / 4096.0);

Secondly, ESP32 ADC is not really linear, and tend to have lower reading than the actual value. You will need to do some calibration if you want to get a more accurate reading. You can take a look at my github on esp32-adc-calibrate.


text:
Does the compiled binary of a sketch include uncalled functions from a library?
I am writing a GUI using a TFT display and the Adafruit GFX library and its default font on Arduino Nano.
I want to be memory efficient and I assumed that the 'optimise for size' default setting of the compiler would not compile and include all functions from all included libraries if those functions are never called in the sketch.
However I was reading this memory management guide which advises (on pager 20) to remove 'unused libraries' and 'unused functions' from your sketch to save memory.
So I have 2 related questions:

Does the Arduino IDE compiler include all the compiled binary from these library functions even if they are never called in the source sketch (I know that any global variables in a library will take space even if unused but I am specifically asking about unused functions)?

If that is the case would making my own modified, trimmed down, version of the standard libraries save space?

Thanks.

In general only the functions actually used by your code are included in the final linkage of the binary.
However it's not always possible for the compiler to know what is used and what isn't.
In the case of simple functions and classes there's no problem - the linker is intelligent enough to work it out and only link in the functions that are actually used.
However when it comes to more complex systems with polymorphism or when working with function pointers there are times when the compiler won't really know what is needed and what isn't so sometimes some code gets included that isn't actually wanted.
As the compiler advances those times are getting fewer and farther between, so unless you really have a dire need to reduce your code size there's really nothing much to gain. If you do have that need then you would gain more by reducing the complexity of the code in general and collapsing any polymorphism rather than removing unused functions.
BTW: the "optimize for size" has nothing to do with what code is included / excluded. Instead it controls such things as which function are selected for inline, and what loops are unrolled or not, amongst other things.

some Arduino cores don't use LTO. for example for the STM32 core by STM the LTO option never produces a working application binary

@Juraj It will still only include what is needed. LTO is more for pruning polymorphism. That's the "As the compiler advances..." bit - LTO improves it a massive amount, but there has always been selective inclusion and -ffunction-sections --gc-sections etc.


text:
I'm getting really unstable analog values with my B103348 joystick
I'm trying to make my B103348 joystick control a DC motor but I'm getting very unstable values from it specifically when the y axis is at 0. This is what my Serial monitor shows...

0,
21,
21,
21,
0,
22,
23,
21,
21...

This is the wiring...

And here's the code...
int y_pin = A0;
int y_val;

int in_1 = 3;
int in_2 = 4;
int clock_wise_speed;
int counter_clock_wise_speed;

int en = 2;

int dt = 500;

void setup() {
pinMode(y_pin, INPUT);

pinMode(en, OUTPUT);
pinMode(in_1, OUTPUT);
pinMode(in_2, OUTPUT);

Serial.begin(2000000);
}

void loop() {
  //Clock wise = in_1 LOW and in_2 HIGH.
  //Counter clock wise = in_1 HIGH and in_2 LOW.
  y_val = analogRead(y_pin);
  clock_wise_speed = .21994 * y_val;
  counter_clock_wise_speed = 90;

  if(y_val >= 506){
    analogWrite(en, clock_wise_speed);
    digitalWrite(in_1, LOW);
    digitalWrite(in_2, HIGH);
  }

  if(y_val >= 501 and y_val <= 505){
    digitalWrite(en, LOW);
  }

  if(y_val <= 500){
    analogWrite(en, 225);
    digitalWrite(in_1, HIGH);
    digitalWrite(in_2, LOW);
  }

Serial.println(y_val);
delay(dt);
}

Thanks in advance.

what's your question?

do you honestly believe that the picture shows clearly where each wire is connected? ... please draw a wiring diagram

"specifically when the y axis" If this is meant to imply that it behaves differently when wired to the x-axis, that should probably be spelled out.  Not being able to actually see the joystick or know its model, the distinction seems otherwise fairly meaningless.

@jsotola Is there a free software I can use to make a schematic for it?

If nothing else, you can hand draw it.  It doesn't have to be professional; just readable.  You could also retake your picture under good light, e.g. near a window during the day.

How stable to you need the values to be? You’re dealing with analog-to-digital conversion which will always bring some noise. If you need values that change less abruptly, run the raw analogRead() values through a filter (for example a simple moving average filter).

Personally I've used Express PCB for free schematics. However you could just sketch out on a bit of paper how you wired up the joystick. I would test without what looks like a motor in your photo - that might be influencing things.

Could you try a sketch that does nothing other than Serial.println(analogRead(A0)); delay(500);?

There is a video which appears to be about your joystick. Can you perhaps try what is suggested there and report what happens?

21/1023 possible readings is only 2%, perhaps that is normal for this joystick.

There is a schematic editor built into this website. Just edit your question and click the schematic button at the top of the editor.


text:
Stand alone Atmega328p-au
I'm trying to make a standalone arduino board with an OLED display using an Atmega328p. I never tried to make such a board using SMD components. I've soldered everything together except the OLED display itself. I've uploaded the ArduinoISP sketch to an Arduino Leonardo, and hooked up the SPI pins on my board there. But I simply can't upload anything, I've got 0x000000 as the device signature. I've checked all the connections from the Atmega to the exposed pins themselves, and all seems to be correct with no short circuits.
I'm a bit confused if I put C1 and C3 close enough, could those be the problem? Or is the atmega itself dead? Or did I missed something important?
Wiring between the board and the Leonardo is the following:
Board(H1 header)         Leo
1(reset pin)<----------> Pin 10
2(MISO)     <----------> Pin 12
3(MOSI)     <----------> Pin 11
4(SCK)      <----------> Pin 13
-------------------------------
Board(H2 header)         Leo
1(VCC)<----------------> 5V pin
2(GND)<----------------> GND pin

I've put a 10uF cap between GND and RESET on the Leo.
In the stock ArduinoISP sketch, the #define USE_OLD_STYLE_WIRING line is uncommented. I've tried both Arduino as ISP as a programmer (which didn't work), and Arduino as ISP (Atmega32U4) which gave me the aforementioned signature.
As for the board, I've tried selecting both Arduino Duemilanove or Diecimila/ATmega328P and Arduino Pro or Pro Mini/ATmega328P (5V, 16MHz)

Then try to swap the MISO/MOSI lines

@gbg I've tried that as well, I've got signatures like 0xFF0000, 0xF00000, kinda randomly

the crystal may be connected incorrectly

Not too sure about the crystal. Seems like the ground for the caps is only grounded via the MCU (I can't see a direct trace to ground). Is it oscillating?

@jsotola, But when the MCU is brand-new, it uses the internal oscillator.

@Mat the crystal appears to be not grounded

@Mat it is connected to ground (there is a via above pin 6 of the MCU), but I can't even flash a bootloader to the Atmega, so it should only use the internal oscillator

One thing I have found: new out-of-the-box chips need to be treated more gently than ones that have been programmed once already. You need to slow down the programming to compensate for it running from a relatively slow (1MHz) internal clock.

For Arduino Leonardo, SPI only break out at the ICSP header, not like Arduino Uno that is available at pin 11 - 13. See https://www.arduino.cc/en/Reference/SPI


text:
Renault car (2003) remote control signal is not received by rc receiver (rcswitch)
I have an arduino uno, I have set up a rf receiver as well known library rcswitch suggests I do, but I can never see something on the serial monitor in the IDE environment. I am using the example provided by the library, and did the pin set-up as described.
The key (car card) is that of an old Renault Laguna 2. I have browsed the web and am pretty sure that it sends an rf 433mhz signal, and my receiver is also listening to that frequency, so I am quite surprised that nothing pops up.
I also have a transmitter but only 1 dev board so can't really think of any way to test the receiver. Any suggestions ? In case the receiver might be broken how can it be tested? Am quite new to this.
Any help appreciated

433MHz is just the name of the band. You need the receiver to be tuned to the exact frequency the key fob transmits on - and then it needs to decode the data in the right way to make some sense of it.

Step one with any unknown transmitter is to buy a cheap USB SDR dongle and analyse the radio signal.

@Majenko thanks for the answers.but i was looking for a way to do it without buying nothing else. i was lookin thru the rfswitch lib and I don't see where it sets the frequenct on which to listen on, is this the same as setting the protocol ?

The frequency is set by the receiver module. If that doesn't match the transmitter it won't receive anything at all.


text:
How do I add Gyroscope, Accelerometer, Euler, and Temperature data to one Arduino board?
I have to use a BNO055 to get temperature/accelerometer/Euler/Gyroscope data into one Arduino board for a school project. I am very new to coding so I am not familiar with the commands. I have gotten my BNO055 to give me all the data individually but I am having problems getting them all compiled into one code file to upload. I have googled it but I keep getting links to upload them individually. Posted below is my latest attempt.

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Orientation Sensor Test"); Serial.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  Serial.print("Current Temperature: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  Serial.print("");
}

void loop(void)
{
  /* Get a new Sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(gyroscope.x());
  Serial.print(" Y: ");
  Serial.print(gyroscope.y());
  Serial.print(" Z: ");
  Serial.print(gyroscope.z());
  Serial.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(accelerometer.x());
  Serial.print(" Y: ");
  Serial.print(accelerometer.y());
  Serial.print(" Z: ");
  Serial.print(accelerometer.z());
  Serial.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(euler.x());
  Serial.print(" Y: ");
  Serial.print(euler.y());
  Serial.print(" Z: ");
  Serial.print(euler.z());
  Serial.println("");
  delay(100);
}

why can't you do all that inside one loop() ... you already have multiple statements inside loop(), just add more

Does the code below work? I have no compiler at hand, so I can not test it.
If you have to explain what you have done, you'll get into trouble. I don't know your teacher, but ... ;-). Seriously, that was very basic stuff. Try to find some documentation, how to program with the Arduino IDE and learn the basics. A good startpoint is https://www.arduino.cc/en/Tutorial/HomePage .
Then go on with SENSORs and Vector Maths.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Orientation Sensor Test"); Serial.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  Serial.print("Current Temperature: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  Serial.print("");

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(gyroscope.x());
  Serial.print(" Y: ");
  Serial.print(gyroscope.y());
  Serial.print(" Z: ");
  Serial.print(gyroscope.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(accelerometer.x());
  Serial.print(" Y: ");
  Serial.print(accelerometer.y());
  Serial.print(" Z: ");
  Serial.print(accelerometer.z());
  Serial.println("");
  delay(100);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(euler.x());
  Serial.print(" Y: ");
  Serial.print(euler.y());
  Serial.print(" Z: ");
  Serial.print(euler.z());
  Serial.println("");
  delay(100);
}

Thank you so much. My teacher only told us what to do, since classes are online he has been pretty lazy, he did not give us any references to look at so thank you for the link also. Sorry for the basic question lol im a petroleum engineering student so I am way out of my comfort zone with coding. And your code worked. I could not thank you enough for the help.

You're welcome. Generally, I do not handle the homework for others. But you were honest and told us about the background. I also know from students in my neighbourhood how studying works these days. I'm seriously concerned about that. I'm from Germany - guessing by your name I would expect you are an irish man, so it seams, other countries have the same problems. Knowledge and Education are such precious assets, we should not waste them. I'm glad, I could help you.


text:
Problems with inputting into serial monitor
I am currently working on a project where i take a frequency, and i want the code to take that value and use a formula to work out its mmh2O level. I use the Serial Monitor to input the values, but i have a problem. When writing the values e.g. "44.62352548","44.49151522". The value that is sent is wrong and displayed wrong.

I know the code i have written does not support this many signigicant figures from a float. And i have tried a few things to try and solve it but i cannot crack it.
I have tried using dtostrf() command, but i have never used this before and dont understand. Somebody from the arduino Forums had helped me out but it didnt seem to work.
I have also tried formatting aswell, and that did not seem to work.
If anyone has any help and advice it would be much appreciated.
float level;
float myValue;

String msg1 = "Enter Frequency (type 0 to exit): ";
String msg2 = "Your Frequency is: ";

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

void loop()
{
  Serial.print(msg1);

  while (Serial.available() == 0);
  {

  }
  myValue = Serial.parseFloat();
  if (myValue == 0.0)
  {
    Serial.end();
  }
  else
  {
    freqConversion();
  }
}

 void freqConversion()
{
  level = (myValue-44.712)/-0.0285493333;
  Serial.println(myValue);
  Serial.print(msg2);
  Serial.println(level);
}

What do you mean by “The value that is sent is wrong and displayed wrong”? What did you expect? What was displayed instead?

added image of the result

no images please ... add the text and format as code

You have hit a bug in the implementation of parseFloat().
This function reads the number you send as an integer, ignoring
the decimal point, and stores it in a long. It then multiplies it by a
scaling factor (a power of 0.1) in order to get the correct value. The
problem is, if you provide too many significant digits, the integer
overflows, and you get garbage. For example "44.64978683" is interpreted
as
(long) 4464978683 * 0.00000001

but (long) 4464978683 overflows and rolls over to 170011387, hence the
result you get.
Simple workaround: do not provide so many significant digits. They are
irrelevant anyway given the resolution of a float.
Edit: I did not find any bug report for this issue, so I submitted my own to the Arduino dev team.
Update: Per request of a maintainer, I submitted a pull
request with a failing unit test revealing this bug. We then worked
on a fix, which has now been merged to master. It should be published on
the next release of ArduinoCore-API.
Note, however, that the AVR core does not yet use the common API
repository. In the meantime, it may be worth submitting a pull request
to ArduinoCore-avr that cherry-picks the fix from ArduinoCore-API.


text:
SSD1306 shows static when I try to display an XBM image
This is my circuit.

This is the code.
    #include "U8glib.h" // include the universal graphcs library

    U8GLIB_SSD1306_128X64 u8g(12, 11, 10, 9, 8);  // initialise a u8g display object

    const uint8_t flux_xbm[] PROGMEM = {
       0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBF, 0x56, 0x6D, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xEF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x5F, 0x69, 0x92,
  0x6E, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xC1, 0xFF, 0xFE, 0xFF, 0xFF,
  0xFF, 0x3F, 0x80, 0x01, 0xF5, 0x7E, 0xFF, 0xFF, 0xFF, 0xFB, 0x00, 0xC2,
  0x3F, 0x21, 0xF4, 0xFF, 0xFF, 0xFF, 0x36, 0x6C, 0xBE, 0x7F, 0xFC, 0xFF,
  0xFF, 0xFF, 0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0x86, 0x61,
  0xDE, 0x4F, 0xFE, 0xFF, 0xFF, 0xFB, 0x64, 0xE4, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0x3F, 0x20, 0x04, 0xFC, 0x63, 0xFA, 0xFF, 0xFF, 0xFD, 0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xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x43, 0xD8, 0x7D, 0xFF, 0xDF,
  0xBF, 0x9B, 0xEF, 0xFF, 0x5F, 0xAF, 0xAF, 0xAF, 0xAF, 0xAF, 0xBF, 0x43,
  0x88, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFE, 0xFB, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xEF, 0x41, 0xA8, 0xFF, 0x5D, 0x77, 0x9F, 0xBF, 0xE6, 0x77,
  0xFF, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xF7, 0xEF, 0xFE, 0xEF, 0xFF, 0xFF,
  0xFF, 0xDB, 0xBF, 0xF7
    };

    void setup(void) {
    }

    void loop(void) {
      u8g.drawXBMP( 0, 0, 128, 64, flux_xbm); // send the xbm image to the display, specifying position and size
      while (1==1) {} // set the loop to only run once
    }

The image that it holds in XBM is this.

The output is this.

What is it that I am doing wrong?
Edit 1- As reported by user timemage. The xbm array was 64x128 instead of 128x64 I have changed the image added a more simpler one but that still does not solve the problem,

The image you included in the question is JPEG formatted, colored, 1920x1080 pixels and 155KB in size. How is that supposed to work with a 32KB Arduino and a 128x64 monochrome display? How did you convert the image to the format you put in your code? Does it work with much simpler and/or much smaller images?

@StarCat If you see the size of the image I have input into the code in an array of type uint8_t called flux_xbm it would be 164x64. I used these two online apps https://image.online-convert.com/convert-to-bmp to convert to a grayscale 128x64 Bitmap and then used https://www.online-utility.org/image/convert/to/XBM to convert to a hex 2-D array.

Did you try this conversion tool with simpler monochrome images? Are you able to display other things besides XBM bitmaps i.e. is the display initialized correctly and are you able to control it from your code using the U8glib?

@StarCat Yeah. I have used the same OLED display to depict three waveforms taken from 3 different sensors simul0taneously and individually displaying an image is the problem now. I was thinking about adding a menu connected to a rotary encoder or something to choose which waveform you want to see and add an image or something while the hardware calibrated.

@StarCat but as of now. Wrt the  display plus  this image no sensor is attached to the OLED and this is the code which I have used .

I'm not sure exactly what I'd do with this information, but: is the configuration of pixels you get the same each time you attempt to display the image or is the dot pattern stable?  What happens if you try to draw a solid rectangle over top of this static, does it do that successfully?

NOTE: This refers to an problem in the initial posting.  The question has since been edited.  This may be deleted later.

One problem, perhaps the problem, is that your given image appears to be 64x128 rather than 128x64:

That said, I'm not sure exactly why the screen is showing precisely what it does.
When you do get this showing in the correct resolution, I expect you'll be a bit unimpressed with the result though.

thank you for pointing that out. It was a fault at my end. I have rectified it. But still the output is the same static I see. Should I change the CBM hex array in the question? or what is the procedure?

the problem is still no resolved. I tried other images. Everything from the drivers own constructors is working just these images are being difficult to show.

I misread the your first comment above.  I don't know for sure what the correct procedure is, but I would say since the image dimensions and distortion aren't your primary problem, then yes, it makes sense for you to update your question with the corrected image array.  You may want to add a note just saying that a previous edit had incorrect image data but it wasn't the principal problem.  I may make a similar note in this answer or I may delete it. I will have to think about that.


text:
Why is my text inverted while using U8glib?
I am displaying text using this code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
int Buffer[128];int Buffer2[128];int max=0;

void pageEMG();
void recordEMG();
void pageECG();
void recordECG();
void pageBP();
void recordBP();
void clear_screen();

const int pageCount = 10;
int p;
void (*pages[pageCount])() = {clear_screen,recordEMG,pageEMG,clear_screen,recordECG,pageECG,clear_screen,recordBP,pageBP,clear_screen};
int duration [pageCount] = { 100,5000,10000,100,5000,10000,100,5000,10000,100};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop()
{
u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}
void recordEMG(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A2)*.091;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading EMG...");
}
void pageEMG() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "EMG");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void recordECG(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A0)*.08;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading ECG...");
}
void pageECG() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void recordBP(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A1)*.091;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading BP...");
}
void pageBP() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void clear_screen(void) {
  u8g.setColorIndex(0);
u8g.drawBox(1, 1, 64, 128);
}

And my text is coming inverted.
Why is this happening?

In u8x8.h change U8X8_DEFAULT_FLIP_MODE from 0 to 1. https://github.com/olikraus/u8glib/blob/master/u8g2/csrc/u8x8.h#L70

Try putting u8g.setRot180(); in the setup void.


text:
Library LiquidCrystal_I2C don't work in other class (Composition)
Good afternoon, I'm trying to use a class to streamline the writing on the LCD. In this class I have an private attribute (it's a pointer, do not know how I call him) called  LiquidCrystal_I2C* _lcd, I instantiate it in the constructor, so far so good, but when I call the _lcd-> begin (20, 4) the code below is not executed, but no error is displayed.
Display.h:
class Display{
    public:
        Display();
        ...
    private:
        LiquidCrystal_I2C* _lcd;
        ...
}

Display.cpp:
...
Display::Display() {
    _lcd = new LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    _lcd->begin (20, 4);
}
...

Program.ino
#include "Display.h"

Display lcd;

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

void loop() {
    Serial.println("test");
    delay(3000);
}

Just I noticed the error when I saw that Serial.println ("test"); was not running. If I comment the _lcd->begin (20, 4); everything works.
I tested writing everything in Program.ino and worked, has nothing to do with connections or something, just do not apply the concept of composition with this class.
Can someone help me? And sorry for the English, i'm from Brazil. Thanks.

Do you understand the concept of static access in classes?

If it is as Java, I understand

It is pretty much the same, yes.  Accessing member variables with Display:: in front of them accesses the static class members, not the object local members. I am quite surprised it compiled actually like that.

I removed the Display::, but still does not work.

Is it now: _lcd = new LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
_lcd->begin(20, 4);

@Majenko static variables in C++ have to be declared static. Just putting Display:: in front of them would not turn them from instance variables to class variables.

@JayEye That's why I was questioning if it really compiled.

Got it. Sorry.  // more characters so I can post a comment :)

Most likely cause
You are hitting an insidious problem that even experienced C++ programmers frequently miss: order of initialization of global variables. In your case, Display lcd is initialized (i.e., its constructor is called) before main() and subsequently setup() are executed. However, you almost certainly are #includeing whatever library is declaring the LiquidCrystal_I2C class, probably Wire.h, and so on. In many of these classes, a global variable of that type is also defined to make it easier to access stuff. For example, Serial (as in Serial.println("foo")) is really a global variable of the appropriate type of whatever serial implementation your particular core is using.
The problem you are hitting is that the C++ standard does not guarantee the execution order of the constructors of global variables. The order is an artifact of the compiler, the order in which object files were linked, and probably the phase of the moon :)
What is (almost certainly) happening is that the constructor for your class Display is being called, which initializes the LCD and the i2c bus, and then something else calls either the LCD constructor or the i2c constructor and messes things up.
OK, "how do I fix this?" I hear you ask. Simple: make the global lcd variable a pointer, and allocate the instance in begin(), like so:
#include "Display.h"

Display *lcd;

void setup() {
  Serial.begin(9600);
  lcd = new Display();
  // stuff
}

void loop() {
  // more stuff
  lcd->some_method(some_argument);
  // even more stuff
}

Now you are guaranteed that your code will be the last to touch any initialization code that might affect the display or the bus. Just keep accessing the class Display methods through the pointer.
A less likely cause
It is still possible that your constructors are getting executed in the right order, but your hardware does not like being initialized twice (but test that anyway!), so you may have to figure out how to reset the hardware so you can initialize it again. If I understand your posting correctly, the loop never runs, which means that a second initialization probably either causes a exception (which you would not see unless you had some kind of additional debugging channel; in the case of the ESP8266, for example, that would be the output-only Serial1 port, and even then, you'd have to explicitly turn on debugging. Each core has its own debugging stuff, I forget what the real Arduino does.)
Hope this helps.
/ji

It working! Thank You =D And sorry for the delay, I was without Internet...

Another satisfied customer :)


text:
sensor sampling frequency
I have a problem collecting data from my accelerometer/gyroscope sensor with a constant sampling rate. Is there a way to program the arduino to collect data from the sensor and store these values in a SD card with a constant frequency of 1kHz without using delay? The sensor that I am using is a MPU6050 gy-521 sensor that uses I2C with arduino. I will be reading 6 different datas from my sensor: acceleration in x,y,z directions and gyration in x,y,z directions. Thank you all in advance for the advice/help.
so my project will be making a device that collects the values from the sensors and saves them to study the data later. First, a LCD display will print out a message without having any data collection to occur. The data collection will start when a button is pushed. After the button is pushed, the display will print out another message saying that the arduino is collecting data and the Arduino will save the 6 values (x,y,z acceleration and gyration) from the accelerometer/gyroscope sensor to the SD card. The data collection will stop after the button is clicked again and the display will print out another message saying that it has stopped collecting data. Then, this process can start again if the button is clicked once again. Thanks in advance

Welcome to Arduino.SE. What have you done so far? Liberally describe your setup and post any code as well.

You may actually find if you research it in more detail that you can get the MPU6050 itself to produce regularly spaced samples, and merely poll for their availability.

You have discovered delay() does not guarantee the period of your code.  This is because the period of your code is the delay() plus the time for your code to execute.
What you need is a hardware clock to give your code an indication that a fixed period has expired.  This is one of several Arduino timer libraries. The timer library web page describes your problem in more detail with example code using delays and using the timer library features.

A quick and dirty solution is to just the right the code that does the sampling and loop it, say 10,000 times, with a short delay.  Measure the time it takes to do the 10,000 samples by recording time before and after all the samples.
The amount of time taken will be:
10,000 x (delay period -> known) + 10,000 x (actual amount of time to do the sampling)

From this data you can determine the required delay to get your 1 kHz sampling goal.


text:
Motors whining and never spinning with L298N
I have a problem involving my ESP32, a L298n module, two whining motors and a 9V battery.
I've connected the battery positive 12 VDC to VCC, and the negative to GND.
Two 9V motors are connected to OUT1, OUT2 - OUT3 - OUT4.
My ESP32 is running off its microUSB port.
IN1 -> GPIO 18
IN2 -> GPIO 19
ENA -> GPIO 21 (PWM)
IN3 -> GPIO 22
IN4 -> GPIO 23
ENB -> GPIO 25 (PWM)
GND -> GND (ESP32)

The code serial output is in Spanish.
// Definir los pines
#define IN1 18
#define IN2 19
#define ENA 21
#define IN3 22
#define IN4 23
#define ENB 25

void setup() {
  // Inicializar la comunicación serial
  Serial.begin(115200);

  // Configurar los pines como salidas
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENB, OUTPUT);

  // Inicializar los motores apagados
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(ENA, 0);
  analogWrite(ENB, 0);

  Serial.println("Setup completo, listo para comenzar.");
}

void loop() {
  // Acelerar gradualmente el primer motor
  for (int speed = 0; speed <= 255; speed += 5) {
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    analogWrite(ENA, speed);
    Serial.print("Velocidad del motor 1: ");
    Serial.println(speed);
    delay(100);
  }

  // Acelerar gradualmente el segundo motor
  for (int speed = 0; speed <= 255; speed += 5) {
    digitalWrite(IN3, HIGH);
    digitalWrite(IN4, LOW);
    analogWrite(ENB, speed);
    Serial.print("Velocidad del motor 2: ");
    Serial.println(speed);
    delay(100);
  }

  // Detener los motores
  Serial.println("Deteniendo motores...");
  analogWrite(ENA, 0);
  analogWrite(ENB, 0);
  delay(2000);
}

". . . and a 9V battery" Is this a tiny smoke detector type battery. If so, try a more appropriate power supply for driving motors.

Whoever marked this question down, please consider if it already clear to the OP why it has been marked down and, if not, provide the OP with an explanation in the form of a comment.

The 9V battery might not be able to supply enough current for both the ESP32 and the motors.

The L298 documentation shows that it drops (if my memory serves me correctly) at least 2V, up to almost 5V at higher currents. That means your motors are going to be receiving about 7V at best, down to about 4-5V at worst, assuming the battery is fresh and produces 9V in the first place.
Even if you use a better source than a PP3 type battery (see 6v6gt's comment) with a 298 you will still be short of voltage at the motor if you start with 9V regardless of how good the source is.
The 298 is decades-old technology and you should consider using a more modern device that doesn't suffer from such voltage drops. (The voltage drop manifests as heat btw, which is why those modules have heat sinks the size of a garage door.) Have a look at Pololu's site for a good range of far better drivers.


text:
How to logging Preferences library
On my esp32 project, I use Preferences.h to store some values over rebooting.
I have the issue that mypref.begin("nameSpc", false); returns 0 in one case, but works in a other part of the program.
So I'm looking for debugging and found some things like ESP_LOGI ESP_LOGE.
How I use this mechanic agains Preferences.h / mypref.begin()?
I don't understand this and have not found any examples that take me to AHA!

oh, my goodness...
it's easier as it's look's. To have some debugging output over Serial you must:
Tools->Core Debug Level -> verbose
and
#if (!PLATFORMIO)
  // Enable Arduino-ESP32 logging in Arduino IDE
  #ifdef CORE_DEBUG_LEVEL
    #undef CORE_DEBUG_LEVEL
  #endif
  #ifdef LOG_LOCAL_LEVEL
    #undef LOG_LOCAL_LEVEL
  #endif

  #define CORE_DEBUG_LEVEL 4
  #define LOG_LOCAL_LEVEL CORE_DEBUG_LEVEL
#endif

#include <esp32-hal-log.h>

Thats all, now i've got what i' looking for ;-)
Can be closed!

"Can be closed!" No, this is not how this site works, please take the [tour] to learn more. This is not a forum. -- Instead, mark your answer as "accepted" so that others seeking for help will notice this directly in the list of search results. -- However, if you think your question and answer are not worth to be kept, simply delete it.

Is your code working properly now?


text:
Set Throttle to 0 for Standard Analog Joystick on Multiwii + NRF24 Drone TX
I've been building a NRF24 Transmitter for my Multiwii 2.3 + NRF24 + BMP180 Drone. Everything looks okay, but when I want to test the NRF24L01 transmitter, I see from Serial Monitor and Mini LCD, It shows 127/128 value for Throttle. Therefore, when I arm the drone and, as soon as I release the left stick (it goes to middle-center position = throttle 127/128), the motors start spin 50% or 127/128.
WHAT TO ACHIEVE:
I want the throttle value go to 0% or 0 or 1 or 10 (even though the left stick is at middle-center position.
Here's the NRF24 Drone code Receiver (related to this case):
1. NRF24_RX.cpp
nrf24_rcData[THROTTLE]  = map(strData.throttle, 0, 255, 1000, 2000);
nrf24_rcData[ROLL]      = map(strData.roll,     0, 255, 1000, 2000);
nrf24_rcData[PITCH]     = map(strData.pitch,    0, 255, 1000, 2000);
nrf24_rcData[YAW]       = map(strData.yaw,      0, 255, 1000, 2000);
nrf24_rcData[AUX1]      = map(strData.AUX1,     0, 1,   1000, 2000);
nrf24_rcData[AUX2]      = map(strData.AUX2,     0, 1,   1000, 2000);

2. in RX.cpp file:
      #elif defined(NRF24_RX)
    if (chan < RC_CHANS) {
      data = nrf24_rcData[chan];
    } else data = 1500;

**FULL CODE for NRF24 TX:**

/*

https://www.youtube.com/@ardujimmy
*/

/******************************************************* Multiwii 2.3 NRF24L01 Transmitter ********************************************************/
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const uint64_t pipeOut = 0xE8E8F0F0E1LL; //IMPORTANT: The same as in the receiver!!!

RF24 radio(4, 3); // CE, CSN

String strAUX1;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define OLED_ADDR 0x3C

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int16_t tRoll;
int16_t tPitch;

#define trimRollUpPin 8
#define trimRollDownPin 7
#define trimPitchUpPin 6
#define trimPitchDownPin 5

struct MyData {
  byte throttle;
  byte yaw;
  byte pitch;
  byte roll;
  byte AUX1;
  int16_t rollTrim;
  int16_t pitchTrim;
};

MyData data;

void resetData() {
  data.throttle = 0;
  data.yaw = 127;
  data.pitch = 127;
  data.roll = 127;
  data.AUX1 = 0;
  data.rollTrim = 0;
  data.pitchTrim = 0;
}

void setup(){
  Serial.begin(9600);
  radio.begin();
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.openWritingPipe(pipeOut);

  for (byte address = 1; address < 127; address++) {
    Wire.beginTransmission(address);
    if (Wire.endTransmission() == 0) {
      Serial.print("I2C device found at 0x");
      Serial.println(address, HEX);
    }

    if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
      Serial.println(F("SSD1306 allocation failed"));
      //for (;;)
        ;
    }

  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  //Show in LCD
  display.clearDisplay();
  display.setCursor(0, 0); // Set cursor to top-left corner
  display.println("Hallo Ardujimmy");
  display.println("-----------------");
  display.println("Please wait .....");
  display.display();
  delay(100);
  pinMode(trimRollUpPin, INPUT_PULLUP);
  pinMode(trimRollDownPin, INPUT_PULLUP);
  pinMode(trimPitchUpPin, INPUT_PULLUP);
  pinMode(trimPitchDownPin, INPUT_PULLUP);
  resetData();
  }
}

void updateTrimValues() {
  if (digitalRead(trimRollUpPin) == HIGH) {
    tRoll += 5;  // Increase roll trim
  }
  if (digitalRead(trimRollDownPin) == HIGH) {
    tRoll -= 5;  // Decrease roll trim
  }
  if (digitalRead(trimPitchUpPin) == HIGH) {
    tPitch += 5; // Increase pitch trim
  }
  if (digitalRead(trimPitchDownPin) == HIGH) {
    tPitch -= 5; // Decrease pitch trim
  }
  // Constrain trim values
  tRoll = constrain(tRoll, -250, 250);
  tPitch = constrain(tPitch, -250, 250);
}

int mapJoystickValues(int val, int lower, int middle, int upper, bool reverse){
  val = constrain(val, lower, upper);
  if ( val < middle )
    val = map(val, lower, middle, 0, 128);
  else
    val = map(val, middle, upper, 128, 255);
  return ( reverse ? 255 - val : val );
}

void loop(){
      updateTrimValues();
      //data.throttle  = mapJoystickValues(analogRead(A0), 12, 515, 1024, true );
      data.throttle  = mapJoystickValues(analogRead(A0), 12, 515, 1024, true );
      data.yaw       = mapJoystickValues(analogRead(A1),  13, 524, 1024, true );
      data.pitch     = mapJoystickValues(analogRead(A3), 10, 512, 1024, true );
      data.roll      = mapJoystickValues(analogRead(A2),  1, 524, 1022, true );
      data.AUX1      = digitalRead(9);
      data.rollTrim  = tRoll;
      data.pitchTrim = tPitch;
      //Send all
      radio.write(&data, sizeof(MyData));
      //Show in LCD
      display.clearDisplay();
      display.setCursor(0, 0); // Set cursor to top-left corner
      display.println("NRF24 BMP180 QuadX");
      if (data.AUX1 == 1){
          strAUX1 = "AUX1 ON";
          }
       else{
          strAUX1 = "AUX1 OFF";
          }
      display.println(strAUX1);
      display.println("Throttle: " + String(data.throttle));
      display.println("Yaw     : " + String(data.yaw));
      display.println("Roll    : " + String(data.roll));
      display.println("Pitch   : " + String(data.pitch));
      display.println("t_Pitch : " + String(data.pitchTrim));
      display.println("t_Roll  : " + String(data.rollTrim));
      display.display();
      // Add delay for readability
      delay(100);
   }

Perhaps necessary:
Source: https://www.youtube.com/shorts/cfkqHvwNXHw

Re-writing the code map for specific throttle as follows:
int mapThrottleValues(int Throtval, int lower, int middle, int upper, bool reverse){
  Throtval = constrain(Throtval, lower, upper);
  if ( Throtval < middle )
    Throtval = map(Throtval, lower, middle, 0, 192);
  else
    Throtval = map(Throtval, middle, upper, 192, 255);
  return ( reverse ? 255 - Throtval : Throtval );
}

in void loop(), I re-write this:
data.throttle  = mapThrottleValues(analogRead(A0),   2, 128, 518, true );

NOTE: Since I also asked the same question at https://forum.arduino.cc/t/set-throttle-to-0-for-standard-analog-joystick-on-multiwii-nrf24-drone-tx/1335803/15, someone (https://forum.arduino.cc/u/alto777) helps me to give a clue to re-write the code.
Flying test:
https://www.youtube.com/watch?v=FOICuyzBk54
Here's the pic, tested successfully~


text:
Where to find microcontroller settings in Arduino 2.x IDE
I'm using a wrapper (https://github.com/HenniePeters/ArduinoStarter) to start the Arduino 1.8.19 IDE.
Sometimes when I haven't worked on a project, I just forget the settings to make the compiler work.
This wrapper reads the settings from the comment lines in my sketch and changes the file preferences.txt.
For instance the sketch for an Arduino Pro Mini starts like this:
//exec=arduino
//root=~/.arduino15/
//board=pro
//custom_cpu=pro_16MHzatmega328
//target_package=arduino
//target_platform=avr

Since Arduino IDE 2.0 this does not work anymore. I can't find the preferences file in the path of the 2.0 IDE and I have no idea in which file to look for it. I tried to open almost every file in the path for 2.0, in an editor, but no success.
I would like to change the code to make it work again.
Has anybody found the equivalent for the micro controller settings that were stored in the preferences file in the old version of Arduino?

Maybe this helps: https://forum.arduino.cc/t/ide-2-0-preferences-txt-path/1078505  (found by a quick Google search and there is little point in repeating the contents here. BTW, it is platform dependent)

@6v6gt, Unfortunately you can only change IDE settings in those files. Custom microcontroller settings are not available in .json or .yaml files. Probably the developers have hidden these settings in some binary file. This makes the 2.0 IDE useless to me. If somebody knows where to change controller type, clock rate and other specific settings that are only available in the tools menu, please let me know.

OK. I thinks I see what you are trying to do to add enough information into the sketch so that it automates the steps a user would normally make in the IDE to select the board and any menu controlled options that would normally be selected from the boards.txt file. Maybe then you could explore the mechanism of the CLI interface: https://arduino.github.io/arduino-cli/1.0/ .

Thanks @6v6gt,  The first line of "getting started" : "Arduino CLI provides all the features you can find in the Arduino IDE.". That sounds promising! But this will need some time to investigate :-)

Arduino IDE 2.x does this automatically.
When you open a given sketch, Arduino IDE 2.x automatically selects the board, custom board options, and port you had selected the last time you had that sketch open.

That might be of help to some of us, but not when you work in a team. I need to add settings to the .ino file for other team members. This is a serious flaw in the Arduino IDE, it really needs a project file to store settings that also need to be distributed to other team members. I keep using the wrapper and version 1.8 of the IDE. Hopefully the developers change this in the future and add a project file like all other C++ IDE's have.


text:
U8glib+ 7-pin SSD1306 gives moving text without explicitly specifying in code
This is my code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
void clear_screen();
const int pageCount = 1;
int p;
void (*pages[pageCount])() = {clear_screen};
int duration [pageCount] = {2000};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop()
{
u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}
void clear_screen()
{
  u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
  }

This is the output is a floating text which says BP starts at 20 y length and progresses towards the right after every page refresh. and moves 20 y length down as soon as it reaches the end of the OLED
Check this video out.
Video to the Error

I don't know the answer, but it's common to use the module (%) operator in p = p+1;  if (p == pageCount) p=0;. So you get p = (p + 1) % pageCount;

I have run your code, removing the (12, 11, 8, 9, 10) portion, because the display I used is I2C.  It does not show the behaviour you describe.  It shows "BP" in the upper-left corner where it remains indefinitely.

Do you understand how the code really work? Why do you call the function clear_screen while it is actually draw a string? why the need to use function pointer (*pages[p])(); when it can simply call clear_screen()? I don't use u8glib but I can tell from the code that it will always draw the string at fix location at 0, 20 as @timemage point out, if you want to screen moving across the screen, you need to pass-in a variable u8g.drawStr( 0, y, "BP");.


text:
[SOLVED]Normalization not working on input buffer. How to solve this?
I wrote a piece of code that takes input from a sensor which is called the World Famous Pulse Sensor from Analogue Pin 1 and stores it in an Array with 127 elements then finds the largest in it, divides the rest by the largest, multiplies by 64 which is the maximum y length on my OLED and prints it onto the OLED.
It still gives me pre-normalized and scaled values on Serial Plotter.
What am I doing wrong?
Here is my code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
int x, y;int Buffer2[128];
void pageBP();
const int pageCount = 1;
int p;
void (*pages[pageCount])() = {pageBP};
int duration [pageCount] = {1000};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop() {

u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}

void pageBP() {
  for(x = 0;x < 128;x++) {
Buffer2[x] =(analogRead(A1)>>2);//IP for PPG
Serial.println(Buffer2[x]);
delay(5);
}
for(int i = 1;i < 128; i++)
    {
       if(Buffer2[0] < Buffer2[i])
           Buffer2[0] = Buffer2[i];
    }
    for(int i = 1;i < 128; i++)
    {
       64*(Buffer2[i]/Buffer2[0]);
    }
  for(x = 0;x < 127;x++) {

u8g.drawLine(x, Buffer2[x], x, Buffer2[x+1]); //OP to OLED for ECG

u8g.drawLine(64, 0, 64, 63);
u8g.drawLine(0, 32, 128, 32);}
for(x=0;x<128;x+=8)
u8g.drawLine(x, 31, x, 33);
for(x=0;x<64;x+=8)
u8g.drawLine(63, x, 65, x);
u8g.drawFrame(0, 0, 128, 64);
}

Here is Garbage Graph.

64*(Buffer2[i]/Buffer2[0]); : this line does absolutely nothing. You're not storing the result of that computation anywhere.

I will point out some problems with your code:

Look at this line:
  64*(Buffer2[i]/Buffer2[0]);

It doesn't do anything. You calculate a scaled value, but you are not saving it anywhere. You need to assign that value to a variable (like an element in a new array).

With this code
  for(int i = 1;i < 128; i++)
  {
      if(Buffer2[0] < Buffer2[i])
          Buffer2[0] = Buffer2[i];
  }

You are overwriting the first value in your buffer to find the highest value. That might not be a problem for you, but to be clean here, you should just use a new variable, that holds the highest value outside of the buffer.

I'm not sure what you are trying to do with this line:
  u8g.drawLine(x, Buffer2[x], x, Buffer2[x+1]);

Normally, you would want to draw a line from one point in the graph to the next. So the second x parameter would need to be the x value for the next point. Currently you are just drawing a vertical line. I would instead write
  u8g.drawLine(x, Buffer2[x], x+1, Buffer2[x+1]);

since you already are only counting to 127 instead of 128.

Even if you get the above right, the Serial Monitor would still show the unscaled values, since you are printing to Serial directly after measuring. So to display the scaled values in the Serial Monitor, you need to move the line
  Serial.println(Buffer2[x]);

down to after the scaling, for example in the same for loop as the OLED display code.

And finally you should really fix your indentation. That will make your code way more readable and thus better understandable. The Arduino IDE even has an autoformat feature, that you could use for that.


text:
Getting Trouble in multiple ST7789 SPI LCDs (without CS) with ESP32
I am developing a product in which i have to use 5 LCDs. The LCD i am using does not contain CS pin. SO i had to use MUX for muxing of complete SPI bus from one LCD to other.
But the issue i am facing is, LCD turn off display when i change the select lines of MUX to switch the SPI bus to other LCD. sometimes it just show white screen. basically switching the MUX put the LCD in trouble.
what i am thinking is that when i switch the BUS from one LCD to other then MUX may generate some random data during switching or something like that.
so there is any way the before switching, i should put lcd in a mode that it should not update display until i send any special command again ?
All pins except RST are going through mux, i used separate GPIO for RST of every LCD so that RST should not have issues during switching.
Library i am using is TFT_eSPI.h
Basically library do not support mulitple LCDs, so i customized it by just making global variable for reset pin, when i switch the mux to specific LCD then i change the values of RST to corresponding LCD.
My LCD link is
https://megaeshop.pk/1-3-inch-ips-hd-tft-st7789-ic-unit-240-240-spi-communication-3-3v-voltage-spi-interface-full-color-lcd-oled-display.html
Controller is ESP32
MUX 74HC4051
purpose of using LCD without CS is related to pricing issues. LCDs with CS are too expensive.
I am sorry if my Question formating is not correct or i missed any information. pleas feel free to ask.
I think on all the forums and articles, this is first time i am using multiple LCDs without CS :)

yes it without CS. that's why i used mulitplexer. when i have to write data on let's say LCD 2 then i simply change the address lines of multiplexer

i am sorry, i have updated the link.

Just guessing but try using some simple logic and keep the clock line in the  non asserted state (depends on SPI mode), all the data bouncing around will have no effect, it has to be clocked in. I assume you are not actually reading data from the display.

thanks for your comment,  should i make clock pin as input of controller before switching the addresslines ?
for now i am not reading anything from display.

Thanks for the update. I was just thinking later when reading you probably will have to mux the data out of the display and again it will only be valid with a clock. The reason for the mux is all of them will probably turn on at the same time causing bus contention.


text:
Running Arduino IDE in terminal?
Is there any way to use Arduino in the terminal? I have a USB 802.15.4 board that works with Arduino, but I don't want to use the IDE with it, I want to use the terminal.

I think you need to explain what you mean the Arduino IDE (Integrated Development Environment) is the graphic interface

1.) You can configure the arduino ide to use an "external editor". This means the arduino ide runs als usual but reloads the opened file for compiling and uploading. This is when you want to keep the original arduino ide.
2.) You can use the ino projekt which gives you a cli interface to manage your arduino projects. The quickstart guide gives a good overview of the project.
ino init -t blink
ino build
ino upload
ino serial

You can of course make all needed modifcations for differend boards and communication. I think the second option is what you are looking for ;)

The most popular method these days is to use arduino-builder.
This seems to be the official Arduino command line interface now, and can do most things the IDE can do short of actually editing your code for you.
It is a set of GO scripts, so you will need GO installed.


text:
How to calibrate a load cell?
I'm working with a load cell and HX711. There was no weight on the sensor but I kept getting strange values, I thought it was broken or something so I used my second load cell but the same thing happened again.
I'm wondering what is wrong with it ?
If anyone have worked with it or have an idea how to work with it, please don't hesitate to give your opinions.
 #include "HX711.h"
#include <Wire.h>

#define DOUT  A0
#define CLK   A1

#define DEC_POINT  2
#define STABLE  1

float offset=0;
float calibration_factor = 1;
//float real_weight = 1.560;//kg
float real_weight = 0.5;//kg

HX711 scale(DOUT, CLK);

unsigned char state=0;
long  FindZeroFactor();
float get_units_kg();
void  ReadWeight();
void  FindCalibrationFactor();

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println("Auto Calibrate Program");
  Serial.println("Send 'a' to Find Zero Factor (Please Remove all weight from scale)");
  Serial.println("Send 'b' to Find Calibration Factor (Please insert know the weight on the scales)");
  Serial.println("Send 'c' Show weight on the scales");
}
void loop()
{
  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp=='a')
      state=1;
    if(temp=='b')
      state=2;
    if(temp=='c')
      state=3;
  }

  switch(state)
  {
    case 0:
    break;
    case 1:
      FindZeroFactor();
   //   ReadWeight();
      state=0;
    break;
    case 2:
     FindCalibrationFactor();
     state=0;
    break;
    case 3:
      ReadWeight();
      delay(200);
    break;
    case 4:

    break;

  }
}

long FindZeroFactor()
{
     Serial.println("Find Zero Factor");
     Serial.println("Please wait .....");
     scale.set_scale();
     scale.tare();
     long zero_factor = scale.read_average(20);
     Serial.print("Zero factor: ");
     Serial.println(zero_factor);
     return(zero_factor);
}

void FindCalibrationFactor()
{
  unsigned char flag_stable=0;
  unsigned int decpoint=1;
  for(unsigned char i=0;i<DEC_POINT+1;i++ )
    decpoint = decpoint*10;
  while(1)
  {
      scale.set_scale(calibration_factor); //Adjust to this calibration factor
      Serial.print("Reading: ");
      float read_weight = get_units_kg();
      String data = String(read_weight, DEC_POINT);
      Serial.print(data);
      Serial.print(" kg");
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();
      long r_weight      = (real_weight*decpoint);
      long int_read_weight = read_weight*decpoint;
      Serial.print(r_weight);
      Serial.print(" , ");
      Serial.println(int_read_weight);
      long x;
      if(r_weight == int_read_weight)
      {
        flag_stable++;
        if(flag_stable>=STABLE)
        {
          Serial.print("Calibration Factor is = ");
          Serial.println(calibration_factor);
          break;
         }
        }
       if(r_weight > int_read_weight)
          {
            x = r_weight - int_read_weight;
            if(x > 100)
              calibration_factor -= 1000;
            else if(x > 100)
              calibration_factor -= 10;
            else
              calibration_factor -= 1;
            flag_stable=0;
          }
          if(r_weight < int_read_weight)
          {
            x =  int_read_weight-r_weight;
            if(x > 100)
              calibration_factor += 1000;
            else if(x > 10)
              calibration_factor += 10;
            else
              calibration_factor += 1;
            flag_stable=0;
           }
  }
}

float get_units_kg()
{
  return(scale.get_units()*0.453592);
}
void ReadWeight()
{
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.print("Reading: ");
  String data = String(get_units_kg()+offset, DEC_POINT);
  Serial.print(data);
  Serial.println(" kg");
}

Could it be power fluctuations or a dodgy ground?

Or could it be your (unspecified) circuit?

The typical examples show a zeroing on startup.  Once zeroed calibration can be as simple as a known mass, or several to check linearity.  If you have another scale found objects will do, otherwise you can get a crude kit of calibration weights.  If you have a beam sensor make sure it is not upside down.  Beware there will always be noise - you probably want some filterung in what you display, again see typical examples.

@Matt i'm aware of that and I checked everything

@Majenko what do you mean ?

@ChrisStratton I found some code samples and i'm using one but now I'm getting zero even when I put a wait on the sensor. PS: i'm using a tension compression load cell

@geniusme I am saying maybe there is something wrong with the circuit you are using to interface your load cell to the Arduino - however you haven't shown us that circuit so we are unable to tell. Please show your circuit, and also your code. Without that we cannot help you.

@Majenko I'm wiring my circuit like this link

@geniusme That means nothing to me. What are those connections? Where do they go? What is the circuit you have there? I assume there must be some form of Wheatstone bridge there somewhere, yes?

@Majenko yes it is

@Majenko I'm using a load cell to weight stuff that other board represent a A/N converter and an amplifier (the variation is very small so we need to amplify it to have a noticeable result)

Could you add some sample output to the question? In the question you said you were getting strange values, but in the comments you said you were only getting 0s.

because I started using a library, now when I have nothing on the sensor t it display zero and when I put a known weight it gives me a value but not the weight. I'm trying to figure out a mathematical formula to give me the correct weight

Is the value consistent?  If it is, and you are in the linear range, then the mathematical formula is to multiply by a constant.  Are you asking how to calculate the constant?  If so, What is the known weight and what is the displayed value.

@DaveX I found the mathematical equation, thank you ! I was wondering if I have a lot of load cells, would I have to calibrate each one of them every single time?

@genuisme To get very high levels of accuracy, yes.  Load cells, and the electronics are subject to mechanical, manufacturing variation, creep, etc., and using a common calibration factor would make your systems susceptible to those factors.  For the highest levels of accuracy, you would recalibrate with known weight standards in the range of interest before measurement and then re-check afterwards for drift.

The first thing that about Load Cells that always comes to my mind is the circuit which amplifies the load cell's signal, Usually the load cell signal changes in a low mv range, so you have to put a high gain circuit in the way of the signal, which amplifies signal and NOISE. You have to use an instrumentation amplifier for this purpose, otherwise, your signal would become so noisy.
And try to implement a low pass digital filter too, it should compensate the fluctuations and would give you smoother signal.

scale.set_scale(calibration_factor);

needs to be changed to :
scale.set_scale(calibration_factor/[the reference weight you have used]);

Hi Reza, and welcome to Arduino.SE! While your answer may be correct, it is a little terse. Could you expand upon our answer and explain why that change is required?


text:
Why does my Arduino stop uploading to the Thingspeak server after several hours?
I'm using a Maduino Zero 4G SIM7600 device to upload data from 28 sensors to a ThingSpeak IoT server. It works well for a few hours, then stops uploading the data. Sometimes it starts again after an inconsistent amount of time (an hour or two), sometimes it doesn't.
I can confirm that it's only the SIM7600 and/or Thingspeak functions that are failing, as the serial monitor demonstrates the other I2C related operations on the Arduino board are still working fine even when the server uploads fail.
Here's the relevant part of the code:
void setup(){
    SerialUSB.begin(115200);
    SerialUSB.println("Serial initialized");
    Serial1.begin(115200);
    Wire.begin();

    pinMode(LTE_PWRKEY_PIN, OUTPUT);
    digitalWrite(LTE_RESET_PIN, LOW);
    delay(100);
    digitalWrite(LTE_PWRKEY_PIN, HIGH);
    delay(2000);
    digitalWrite(LTE_PWRKEY_PIN, LOW);

    pinMode(LTE_FLIGHT_PIN, OUTPUT);
    digitalWrite(LTE_FLIGHT_PIN, LOW);//Normal Mode

    delay(5000);

    sendData("AT+CCID", 3000, DEBUG);
    sendData("AT+CREG?", 3000, DEBUG);
    sendData("AT+CGATT=1", 1000, DEBUG);
    sendData("AT+CGACT=1,1", 1000, DEBUG);
    sendData("AT+CGDCONT=1,\"IP\",\"sp.mb.com\"", 1000, DEBUG);

    delay(5000);
}

void loop(){
  getData();

  //Sensors 0-6
  http_str = "AT+HTTPPARA=\"URL\",\"https://api.thingspeak.com/update?api_key=" + Apikey1 + "&field1=" + (String)hallData[0] + "&field2=" + (String)hallData[1] + "&field3=" + (String)hallData[2] + "&field4=" + (String)hallData[3] + "&field5=" + (String)hallData[4] + "&field6=" + (String)hallData[5] + "&field7=" + (String)hallData[6] + "\"\r\n";
  SerialUSB.print("Sent to Channel 1: ");
  SerialUSB.println(http_str);
  sendData("AT+HTTPINIT\r\n", 2000, DEBUG);
  sendData(http_str, 2000, DEBUG);
  sendData("AT+HTTPACTION=1\r\n", 3000, DEBUG);
  sendData("AT+HTTPTERM\r\n", 3000, DEBUG);

  //Sensors 7-13
  http_str = "AT+HTTPPARA=\"URL\",\"https://api.thingspeak.com/update?api_key=" + Apikey2 + "&field1=" + (String)hallData[7] + "&field2=" + (String)hallData[8] + "&field3=" + (String)hallData[9] + "&field4=" + (String)hallData[10] + "&field5=" + (String)hallData[11] + "&field6=" + (String)hallData[12] + "&field7=" + (String)hallData[13] + "\"\r\n";
  SerialUSB.print("Sent to Channel 2: ");
  SerialUSB.println(http_str);
  sendData("AT+HTTPINIT\r\n", 2000, DEBUG);
  sendData(http_str, 2000, DEBUG);
  sendData("AT+HTTPACTION=1\r\n", 3000, DEBUG);
  sendData("AT+HTTPTERM\r\n", 3000, DEBUG);

  //Sensors 14-20
  http_str = "AT+HTTPPARA=\"URL\",\"https://api.thingspeak.com/update?api_key=" + Apikey3 + "&field1=" + (String)hallData[14] + "&field2=" + (String)hallData[15] + "&field3=" + (String)hallData[16] + "&field4=" + (String)hallData[17] + "&field5=" + (String)hallData[18] + "&field6=" + (String)hallData[19] + "&field7=" + (String)hallData[20] + "\"\r\n";
  SerialUSB.print("Sent to Channel 3: ");
  SerialUSB.println(http_str);
  sendData("AT+HTTPINIT\r\n", 2000, DEBUG);
  sendData(http_str, 2000, DEBUG);
  sendData("AT+HTTPACTION=1\r\n", 3000, DEBUG);
  sendData("AT+HTTPTERM\r\n", 3000, DEBUG);

  //Sensors 21-27
  http_str = "AT+HTTPPARA=\"URL\",\"https://api.thingspeak.com/update?api_key=" + Apikey4 + "&field1=" + (String)hallData[21] + "&field2=" + (String)hallData[22] + "&field3=" + (String)hallData[23] + "&field4=" + (String)hallData[24] + "&field5=" + (String)hallData[25] + "&field6=" + (String)hallData[26] + "&field7=" + (String)hallData[27] + "\"\r\n";
  SerialUSB.print("Sent to Channel 4: ");
  SerialUSB.println(http_str);
  sendData("AT+HTTPINIT\r\n", 2000, DEBUG);
  sendData(http_str, 2000, DEBUG);
  sendData("AT+HTTPACTION=1\r\n", 3000, DEBUG);
  sendData("AT+HTTPTERM\r\n", 3000, DEBUG);
}

String sendData(String command, const int timeout, boolean debug){
  String response = "";
  Serial1.println(command);

  long int time = millis();
  while ( (time + timeout) > millis()){
    while (Serial1.available()){
      char c = Serial1.read();
      response += c;
    }
  }
  if (debug){
    SerialUSB.print(response);
  }
  return response;
}

All SIM7600 related operations are taken directly from the Makerfabs examples, found on this page. One thing of note is that in their example, they use the command AT+HTTPACTION=0, which, according to this page, means READ. This does work but it sometimes returns ERROR instead of OK. I've changed it to AT+HTTPACTION=1, which means POST, which seems to work a bit better - at least there are no ERROR messages. But the same problem still persists.
UPDATE #1: The ERROR messages sometimes return even with the AT+HTTPACTION=1 adjustment. Something I've noticed is that generating new API keys for each of the Thingspeak pages (there are 4 in total, 7 sensors per page) causes it to work for a while when it didn't before. No explanation for why that is.
Any advice would be greatly appreciated.
Hardware wise, I'm powering this from an AC adapter through a DC-DC 5V converter. I'm also using a 3.7 battery for backup power.

If you are using free variant, doesn't it have some daily limit of messages? Maybe you are hitting that

Good question - I am using the free version but I haven't come across a daily limitation of messages. Everything appears to be calculated yearly (they give a "daily maximum" but it appears to be just a recommendation to optimize the number of messages you can send per year).

From the ThingSpeak License Options page:

ThingSpeak is available as a free service for non-commercial small projects (<3 million messages/year or ~8,200 messages/day).

Could you be hitting that limit?

You are most likely exceeding the messages-per-period-of-time limit. Give it some time and then try again, adding some delay() in your main loop.


text:
Arduino Nano Keyboard. Keys keeps pressed
I'm new in coding with Arduino, and I am trying to make a one hand keyboard with joystick as personal project. I tried to make it print some ASCII characters, but I don't know why the button keeps pushed and don't show the ASCII I declare.
#include <Keyboard.h>
#include <Mouse.h>
//IndexFinger=IF,MiddleFinger=MF,RingFinger=RF
//LittleFinger=LF
int fingerCodes[3][4]={
  {LF_Up, RF_Up, MF_Up, IF_Up},
  {LF_Mid, RF_Mid, MF_Mid, IF_Mid},
  {LF_Down, RF_Down, MF_Down, IF_Down}
}
int asciiCodes[3][4]={
  {33, 34, 35, 36},
  {37, 38, 39, 40},
  {41, 42, 43, 44}
}
//a
int x=0;
int y=0;
const int joystickVRx1 = A0;
const int joystickVRy1 = A1;
const int joystickButton1 = 14;

// Define the FPS
const int FPS = 120;

// Initialize the last time variable
unsigned long lastTime = 5;

// Define the functions
void finger_ButtonsControl(int x, int y);
void joystickMovementControl(int joystickvrx, int joystickvry, int joystickButton1);
void setup() {
  // Initialize the serial port
  Serial.begin(115200);
  // Set the button pins as input
  pinMode(joystickVRx1,INPUT);
  pinMode(joystickVRy1,INPUT);
  for (int i = 2;i<11;i++){
    pinMode(i,OUTPUT);
  }
  Keyboard.begin();
  Mouse.begin();
}

void loop() {
  // Check if it's time to update the controls
  if ((millis() - lastTime) > 5) {
    // Update finger buttons
    finger_ButtonsControl(x,y);
    // Update the joystick movement
    joystickMovementControl(joystickVRx1, joystickVRy1, joystickButton1);
    // Reset the last time variable
    lastTime = millis();
  }
  Keyboard.releaseAll();
}

// Function to control finger buttons
void finger_ButtonsControl(int x, int y) {
  // Check if a button is pressed
  for (int x=2;x<5;x++){
    for (int y=5;y<9;y++){
      buttonState_x = digitalRead(x);
      buttonState_y = digitalRead(y);
      if (buttonState_x == HIGH && buttonState_y == HIGH){
        x=x-2;
        y=y-5;
        Keyboard.write(asciiCodes[x][y]);
      }
}

// Function to control the joystick movement
void joystickMovementControl(int joystickvrx, int joystickvry, int joystickButton1) {
  // Read the joystick values
  int x = analogRead(joystickvrx);
  int y = analogRead(joystickvry);
  if (digitalRead(joystickButton1) == LOW) {
    Keyboard.write(245);
  }
}

try defining joystick pins as INPUT_PULLUP

Not sure this is your issue, but there is definitely a problem here:
void finger_ButtonsControl(int x, int y) {
    // Check if a button is pressed
    for (int x = 2; x <5; x++) {
        for (int y = 5; y < 9; y++) {
            buttonState_x = digitalRead(x);
            buttonState_y = digitalRead(y);
            if (buttonState_x == HIGH && buttonState_y == HIGH) {
                x = x - 2;  // <-- problem here...
                y = y - 5;  // <-- ...and here
                Keyboard.write(asciiCodes[x][y]);
            }
        }
    }
}

Think of what would happen if you press buttons 2 and 5. On the first
iteration of the loops, you will have x = 2 and y = 5, the if
condition will be true, and the problematic lines will turn both x and
y to 0. Then, the inner loop will increment y and, on the next
iteration, you will read the pins x = 0 and y = 1. Since this is a
(presumably idle) serial port, both pins will read HIGH. Then the
problematic lines will turn x to −2 and y to −4. At this point
reading asciiCodes[x][y] invokes undefined behavior and anything can
happen.
I believe what you intended to write was:
void finger_ButtonsControl(int x, int y) {
    // Check if a button is pressed
    for (int x = 2; x <5; x++) {
        for (int y = 5; y < 9; y++) {
            buttonState_x = digitalRead(x);
            buttonState_y = digitalRead(y);
            if (buttonState_x == HIGH && buttonState_y == HIGH) {
                Keyboard.write(asciiCodes[x-2][y-5]);
            }
        }
    }
}

:0 Wow, I got days thinking of what to do, and you answer was so good. Thanks for helping me. I never thought that the code would take the result of the substraction as a "parameter-ish" in the loop, and giving me those negative values led to wrong values