text:
execute if function in a timed loop
I have a school project where I had to make a piece of code work for 1 minute and then return. I first used a RFID reader which didn't work for me so I decided to use the serial monitor. I did this through a switch function and if it was the correct number you had 1 minute to push in the buttons.
But now to the problem for me is that in the timed loop I made it can't look for if functions and because of that I can't look if the buttons are pressed.
I hope it was a
clear explanation and someone can help me.
Thanks in advance.

Pasted code can be formatted correctly by selecting it and clicking the {} button in the question editor (or pressing Control+K).

Your problem is not clear to me. But I think you should actually read the switches via digitalRead() inside the loop.

Why did you again removed your pasted code, that I formatted for you?

Because the code had no spaces or next lines and thus wasn't readable. I also had no idea how to change it to make it look readable. But your comment about digitalRead() was very helpful, I had a digitalRead() for my buttons but I had put it in a different loop but now that I moved the digitalRead() to the Right() it work now. So thank you very much.

Normally, a timed loop is a bad design in Arduino projects. Rather use the given void loop() function and non-blocking functions inside.

As chrisl mentions,  you should use digitalRead.
Assign this to the correct variables:
switchState1 = digitalRead(…) // Fill in the correct pin here
switchState2 = digitalRead(…) // Fill in the correct pin here

Also, you can separate the first part of the if, so you get:
if (switchState1 == HIGH)
{
    if (switchState2 == HIGH)
    {
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        digitalWrite(4, HIGH);
    }
    else if (switchState2 == LOW)
    {
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
    }
}

Since the inner condition only depends on switchState2 and the pins are equal, you can write:
if (switchState1 == HIGH)
{
    digitalWrite(2, switchState2 == HIGH);
    digitalWrite(3, switchState2 == HIGH);
    digitalWrite(4, switchState2 == HIGH);
}

And you can use instead of the switchState2 a switchState2High (Boolean), and only check it when switchState 1 == HIGH.
if (switchState1 == HIGH)
{
    switchState2High = (digitalReadState(…) == HIGH);
    digitalWrite(2, switchState2High);
    digitalWrite(3, switchState2High);
    digitalWrite(4, switchState2High);
}

You also could use a for loop for the last part so you get:
if (switchState1 == HIGH)
{
    switchState2High = (digitalReadState(…) == HIGH);
    for (int pin = 2; pin < 5; pin++)
    {
        digitalWrite(pin, switchState2High);
    }
}

The code works now so thank you very much for your time and help

You are welcome / good luck with your project


text:
Hook Arduino up with thermal printer and power both externally
Disclaimer: I have no connection to adafruit.
A friend and me want to build a little project. We want to connect an arduino to a thermal printer and then print out little fortune-cookie like messages, when a button is pressed. The whole setup should not be stationary and thus we need external, mobile power like batteries.
Since this is our first time using an arduino as well as a thermal printer and we have no clue about electronics, I am asking for help to set everything up without frying the arduino or the thermal printer.
We are using a standart arduino uno rev3 and the Adafruit Tiny Thermal Reciept Printer.
First question: Setting up the power supplies
So the idea was to power the arduino via a 9v battery pack to it's 2.1mm DC port. I think this should work, right?
What I am confused about is the Adafruit Tiny printer. It says it takes 5-9 V, 1.5-2A. Can I just hook up a 9V battery packand clip the caples to the printer? Or what setup do I need so that the printer will recieve enough amperes when printing?
And how would I connect both tools to a single ( larger ?) battery pack?
So that we can turn the power off easily?
Second question: Finding a good button compatible with an arduino and setting it up in the project.
So we have a gerneal idea of how things should work. Somehow we need to connect the button to the arduino which then can register a click via one of it's pins. This click I can then register with my code and from there on things get easy for me. But getting to this point is hard for us.
We don't know which buttons will work and neither how to connect it to the right pin. Which pin should we adress? Digital? Analog?
Does the button need an external power supply as well? Since otherwise the arduino would not register a change of current on a pin, right? Or do we need to connect the button to the whole circuit?
I do a lot of high language engineering and have no real idea about circuits and electronics and my friend is more of a craftsmen so we really appreciate your ideas, setups and help in general!
I am not sure if this is too much to ask but a sketch of the whole setup with a single power source and button would be awesome! Thanks. Really!

I'd suggest getting a USB powerbank that can supply 2A. A 9V battery can't supply that much current.

Also check out the Adafruit guide

If you don't want to accidentally print multiple messages on a "single" button press, also make sure that you use either a software or a hardware "debounce" for the button. If you activate the input pullup using the pinMode(pin_number, INPUT_PULLUP) command, a hardware debounce can be implemented with a capacitor and a resistor. See https://hackaday.com/2015/12/09/embed-with-elliot-debounce-your-noisy-buttons-part-i for details on this.

Setting up the power supplies

As Gerben already stated in the comments, a 9V block battery isn't capable of supplying enough current for the thermal printer, so you cannot simply use one of them (these are meant for low power applications, like a smoke alarm). There are many different types of batteries, that you can use for this. Probably some kind of LiPo or LiIon pack would be suitable. (I'm sure you can find information about pros and cons of different battery types on the web). But the easiest way for you would be an USB power bank, that can supply at least 2.5A. A power bank incorporates mostly a LiIon pack and also already the mandatory smart charging electronics (to charge and discharge correctly and also to monitor the charge level), and - every important - a 5V voltage regulator. You can supply the 5V from the USB power bank directly to the Arduino and thermal printer in parallel. If you need to switch them on and off together (and the power bank doesn't already incorporate some kind of switch), you can use a simple switch between the positive lead from the power banks USB port and the positive leads for Arduino and printer.

Finding a good button compatible with an arduino

Every normal button is compatible with Arduino. A button is nothing more as a switch, that automatically opens again, if you are not pressing it. Just two pieces of conductive material, that get's pressed together, if you press the button. A normal button has 2 pins (you might see more pins on the button, but mostly some of these are electrically connected together, so that you effectively have only 2 pins). Connect one pin to ground and the other to a digital input pin of the Arduino. Then in your sketch use pinMode(pin_number, INPUT_PULLUP); in your setup() function. This will enable the Arduinos internal pullup resistor, which pulls the pin to HIGH, if the button isn't pressed. If you press the button, the pin will be pulled to LOW. Keep this inverted logic in mind (LOW means pressed, HIGH not pressed).
There are also many button examples for Arduino on the web, since using a button is the second thing to learn with Arduinos (after blinking an LED). Button example code via digitalRead() is also incorporated into the Arduino IDE (look for examples in the menu).

a sketch of the whole setup

Even, if someone wanted to write the code for you (and this is not a free coding service, so you cannot expect someone to simply do it), you haven't given us enough information, what behavior you want. But please don't add that here, to get this free code. What you are asking (single power source and button) is not difficult. Surely - currently you don't know much about this stuff, but it's not rocket science and there are many many Arduino tutorials on the web to help you. About the code for the thermal printer: Adafruit always provides dedicated guides for the devices they sell. There you can find a description, how the device works and is connected and used. They also provide example code and in most cases complete Arduino libraries, that hide most of the complexity of a task.
You should start by connection the Arduino to the power bank. Then you should go on and get the button going (you can write a sketch to turn the onboard LED on and off with it to learn how it works). Then you can connect the printer. Try adafruits example code. If it works, you can extend your sketch with the printers code.

Note: Some power banks turn of the power completely, if only a small current is flowing out of if. With such a power bank your Arduino might turn of as the power bank cuts the power. It normally does not draw enough current for the power bank. I think this shouldn't happen, when the printer is connected, but this depends on the current, that it draws (considering the minimal current, that it draws while idling), and the current, that is the minimal limit for your specific power bank.

Thanks for your answer! I wasn't asking for a code solution! I want to figure that out myself. Thanks for all the insight, highly appreciated.

source: Stack Exchange

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

sort: votes


text:
How to make a dynamic menu with a sub-menu ( Arduino mega or Arduino Uno)
I have an arduino mega with a LCD shield (from keyestudio KS2056). I am trying to create a menu with a submenu that would have addable and removable strings based on inputs from a RFID scanner(addable) and buttons(to remove selected strings). I am not so sure how I could possibly do this. Any assistance would be great.

I will skip the RFID part, that is unrelated to the menu.
What you can do is creating two variables:
int menuLevel1 = 0;
int menuLevel2 = 0;

Assuming you have 2 levels, if you have more levels consider an array.
Now you can print the screen based on the values of these two variables (use a switch statement for menuLevel1 which calls new functions, each with their own switch statement for menuLevel2.
Note there are more solutions, but this is a rather simple solution.
The RFID scanner just changes the values, so going to a different menu screen.
A slightly different solution is to not use numbers, but an enumeration (or one for the main level, and x for the second level etc). This can add up, so you can also use a single enum value (with one entry per possible menu page).
The last example looks like:
enum EMenuPage
{
   StartPage,
   MainMenu,
   FirstMenu,
   DisplayX,
   SetY,
   …
}

enum EMenuPage _menuPage;

Displaying like:
switch (_menuPage)
{
case StartPage:
   // Fill LCD with start page
   break;

case …

And when an RFID messages comes in:
if (RFID... == Back)
{
  _menuPage = MainMenu;
}
else …

[State machines][1]. it's the general form of the solution provided by michael above. it's a big help on situations when the application have to answer to, or act on many states (e.g. a menu). the good part is you can draw them on a piece of paper , draw a graph, manage input/output and write a general routine to act in various states. the state names themsevles can be represented by an integer variable and represented better by enumeration. after that, there should be a routine to act based on the current state, and the input from current state to go to another state. in it's easiest form, it's just a if-else block.
depsite the idea is the same as the bare variable solution provided in the other answers, ignoring state machine related techniques (e.g. just drawing state graphs down on a piece of paper) makes a big application unmanageable.

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


text:
How can I read this digital pin for Nano by using AVR's Atmel Studo?
How can I read digital pin 6 in AVR?
I set the pin as input as follows:
DDRD = B0100000; //this will set pin 6 as input
But how can I now digital read this pin?:
Another way of putting it: how can I convert this Arduino code to be used in Atmel Studio?:
digitalRead(DATA_PIN);
Edit:
while (1) {

        unsigned long data = 0;//32 bit variable to store encoder data

        for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
        data <<= 1;//shift all read data left one bit
        PORTD &= ~(1 << 5);//clock pin goes low
        _delay_us(2);
        PORTD |= (1 << 5);//clock pin goes high
        _delay_us(2);

        data |= digitalRead(DATA_PIN);//cat the new read bit to the whole read data
        }

I want to use usual C code for AVR instead of using digitalRead above. data is an 32 bit array storing 25 bit encoder data. It is bit by bit filled by digitalRaed.
I think I found it:
while (1) {

        unsigned long data = 0;//32 bit variable to store encoder data
        uint8_t val;

        for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
        data <<= 1;//shift all read data left one bit
        PORTD &= ~(1 << 5);//clock pin goes low
        _delay_us(2);
        PORTD |= (1 << 5);//clock pin goes high
        _delay_us(2);

        if ( (PIND & (1 << PIND6)) == (1 << PIND6) ) {
            val = 1;
            } else {
            val = 0;
        }

        data |= val;//cat the new read bit to the whole read data
        }

Did you read the tutorial?

Im a bit in a hurry. But basically my code line in Arduino is: data |= digitalRead(DATA_PIN); ..... Now I need to get the state of DATA_PIN which is  pin 6 in Nano. I would like to learn in more detail but I think it will take long time before I need to convert this.

@Juraj I cant see in that tutorial how I can read the pin state as one or zero.

See the update edit

Read the port state with PIND
Isolate the bit you want with &
Profit

if (PIND & 0b0100000) {
    val |= 1;
}

Or, as a ternary:
val |= ((PIND & 0b01000000) ? 1 : 0);

Thanks I will try this but what could be the data type for val ? For the sake of speed

uint8_t (or unsigned char if you prefer)

Thanks a  lot! One last question. This will be in a for loop like val |= ((PORTD & 0b01000000) ? 1 : 0); and then data |= val; . Do you think I should declare val at the very beginning of the code(before the main) as uint8_t val = 0; or volatile uint8_t val = 0;? Does that matter on this case?

If all you're doing is data |= val then replace val with data

Not really data is a 32 bit array unsigned long type. I store incoming bits to this data variable as array 25 bits of encoder data. The incoming bit is the pin state val in this case.

There is data <<= 1; at the beginning of the for loop

PORTD & 0b01000000 is a "true or false" for if the pin is high or low. 1 : 0 are the two alternative values to use in either case. What you assign that result to is entirely up to you. If you want the pin to be associated with bit 12 of data just go data |= ((PORTD & 0b01000000) ? (1 << 12) : 0);

Since you want to associate it with bit 0 it's just either 1 or 0 that you want to OR with data.

@ty_1917 Actually, I made a mistake (not been using AVR enough) - use PIND not PORTD.

Somehow it doesnt  work I will upload the code sction to the question

Please see my update thanks


text:
String to float on Arduino
I'm trying to convert a String to a float but I'm running into issues with precision, even with the Arduino's own String example I'm getting bad results.
Example 0:
Input string: 1.234567  After conversion to float: 1.2345669
Example 1:
Input string: 60.123456 After conversion to float: 60.1234512
Example 2:
Input string: 9.876543  After conversion to float:9.8765430
Why is this happening and how do I get rid of this?

You get this, because a float uses a certain number of bytes (I don't have an Arduino at hand), I think it is 4 bytes.
In these bytes, only a certain accuracy can be stored, so the least significant digits gets rounded (binary, resulting in different end digits).
Only for e.g. Arduino Due: You can use doubles instead, see https://www.arduino.cc/reference/en/language/variables/data-types/double/
You might check for the strtod function, but I'm not sure if it is handled by the Arduino:
https://www.techonthenet.com/c_language/standard_library_functions/stdlib_h/strtod.php
If this doesn't work, you can use a function to split the '.' and process the left/right part to convert to an unsigned long and combine it together. But if there are exponential and minus signs involved it might get more difficult.

A float is 32 bits. On AVR boards, double is just a synonym of float.

@EdgarBonet Thanks for that remark, I updated my answer (Only for Arduino Due).

There are two issues at play here:
1 – Limited precision of the float data type
A float has a precision of roughly 10−7, and any number that
is not an exact float is supposed to be rounded to the nearest float.
For example, the two floats closest to 1.234567 are
10356298 × 2−23 = 1.2345669269561767578125 and
10356299 × 2−23 = 1.23456704616546630859375.
The latter is the closest.
2 – Naive string to float implementation in the Arduino core
The Arduino core aims at being small and consume few resources.
Sometimes it cuts corners, at the cost of accuracy. In this case,
although a correct implementation is supposed to round 1.234567 up,
because the nearest float is above that number, the actual
implementation ends up rounding down. Thus you end up with roughly
1.234566927, which is off by 0.61 ULPs (units of the last place), instead
of the expected error of 0.39 ULPs.

It seems that I must convert to string first then use atof.

If you are using atof() to convert the string to a floating-point number, you would only get 6 or 7 digits of precision. And the numbers in your examples already have that much precision.


text:
Which one is IR led?
I've ever been so confused in my life. I'm new to Arduino and electronics but I just can't figure it out which diode is IR transmitter/receiver or even if it is IR. I know that IR is not visible to human eye but I'm really clueless and I need help distinguishing them. I think the black one is a receiver but when I connect the white/transparent one it lights up so I guess It's not IR diode, right? How do I test them to see it anyways?

The black one is probably receiver. If the other one lights up then it's a normal LED. You don't have an IR led...

If you connect one of these and you can see it light up with your naked eye then it is not an IR LED, it's a visible-light LED. It's also not an IR sensor.
If you want to see IR, point a digital camera (like in your phone) at it and apply power. The sensors in digital cameras almost always detect some IR, so you can see a faint light on the screen. To test this, point your phone at a TV remote and press the button. If you see a flashing light in your phone's screen, you know it can "see" IR (Most digital cameras have an IR filter to get rid of most of the IR going into the camera, but they generally allow enough IR through that if you point them directly at an IR LED you can usually see it, at least faintly.)
Note that you should be able to use a visible light LED as a light source for an IR photoresistor/photodiode/phototransistor, since visible light LEDs will also give off some IR. However, an IR LED will put out a WHOLE LOT more IR than a visible light LED at of the same power.
The black one is probably an IR receiver. The color of the lens probably blocks visible light but not IR.
All the IR LEDs I've seen have looked clear, but I could not see any visible light when I powered them up.

The dark coloured one is an IR photodiode.
Osram SFH203-FA
Hope that hemps.
:)


text:
How to connect ESP32 to HC-06?
I am making a small project (BT controlled "tank") and need to connect ESP32 with HC-06 (ESP32 will be in controller and HC-06 in the vehicle). Android phone communication with both ESP and HC-06 works prefectly, I can not just figure out, how to pair/connect these two modules. Any ideas?
EDIT: Just to clarify, I can not connect them, because the HC-06 has PIN and I can not figure out how to remove that PIN or connect to it with PIN from ESP32...

The HC-06 can just communicate over the SPP protocol (UART/Serial). Your phone (it isn't an iPhone, as it is not able to use this protocol) can search for this service. So, you have to set a GATT server or client and search for a characteristics with the SPP GUID (you can find something here: https://www.oreilly.com/library/view/getting-started-with/9781491900550/ch04.html). It isn't so easy and you are very limited. Why not use directly 2 ESP32 with ESP NOW for example?

You can either use a breadboard Or Female to Female Jumber wires.
Ofoucrse you can always solder yourself the two modules together with wires.
PS. Too low reputation to comment, so i insert this as answer

Yeah, I know that my question was a bit unclear, I meant connect / pair WITH BLUETOOTH, but thanks anyways.. :)


text:
motor shield directly to PC? WITHOUT ARDUINO!
Is there a way to connect and control motor shield board WITHOUT Arduino at all.
can i connect it directly to my PC ?
i'm getting confused since i red lot of topics that people use existing pins on motherboard.

Is there a reason, why you would want to do this? Misusing a motherboard like that (if it is really possible) does only make sense, if you are doing it for the fun of hacking your motherboard. It would be way more complicated and would definitely don't cost much more, than the typical arduino/microcontroller solution. If an original Arduino costs too much, you can buy a china clone, which are way cheaper.

It's educational.
why can not we just use UBS output to control something like motor shield board,
can get's it's ones and zeroes from USB instead of arduino, since we have all the computing power we need on PC?
is there any USB version of motor control boards? and why not..

This superuser post might help.
Raspberry Pis have GPIO pins that you can use to communicate with a motor shield, but regular (intel-based) PCs usually don't. In any case, you wouldn't want to mess with motherboard pins anyway; a short circuit might easily fry your computer.
If you don't want to use an Arduino, you can use a USB-to-serial converter (such as a small FTDI circuit) along with a motor driver that uses serial communication.
However, this wouldn't be any simpler or cheaper than just using an Arduino.

To a normal PC? No. You can't. A PC doesn't have the GPIO pins etc that are needed.
You could wire it to a Pi though.

If you have a PC with a real Parallel Port ( LPT1: ) and you don't run an Operating System on it, ( or perhaps MS-DOS ) ... you can connect some leds, but you cannot use an Arduino shield directly.

Re “If [...] you don't run an Operating System on it”: You can do it on Linux from a privileged process, if you first request access to the port's IO registers with ioperm(0x378, 3, 1);.


text:
default parameter class method
I have this function (which works fine):
String Esper::rtcTimeString() {
  DateTime now = rtc.now();
  char buf[] = "MM/DD/YY hh:mm:ss";
  return now.toString(buf);
}

I'd like to have a default value of "MM/DD/YY hh:mm:ss" but also pass an argument to a parameter such as "MM/DD/YYYY" if I want to override this default behavior.
Typically, in the definitions .h file I would do something like:
String rtcTimeString(char ts[] = "MM/DD/YY hh:mm:ss");

and subsequently in the .cpp:
String Esper::rtcTimeString(char ts[]) {
  DateTime now = rtc.now();
  return now.toString(ts);
}

However that results in the same returned time string every time.
e.g.
1/6/2020 12:01:12
1/6/2020 12:01:12
1/6/2020 12:01:12

How can I implement a parameter such that the functionality is the same as in the first code block?

I would expected char ts[] to be passed as reference (you could change the argument into char* but I doubt it will improve ... What I suggest is to use a PC compiler (e.g. free Visual Studio 2019 C++) and use the internal debugger to see what actually is passed and exactly where it goes wrong. Than move the corrected code back to Arduino.

You cannot pass an array of characters as an argument (implicit or not)
to a function. When you write
String rtcTimeString(char ts[] = "MM/DD/YY hh:mm:ss");

The array notation is implicitly converted to a pointer. The line above
is then equivalent to:
String rtcTimeString(char *ts = "MM/DD/YY hh:mm:ss");

And this is incorrect: you are initializing a pointer to modifiable
characters using the address of an array of constant characters. The
compiler should have warned you about this... if you enabled compiler
warnings. The correct prototype should be
string rtcTimeString(const char* ts = "MM/DD/YY hh:mm:ss");

But then you cannot pass this pointer to DateTime::toString(), as this
method expects the template string to live in a buffer it can overwrite:
that's where it will write the formatted string.
I suggest this solution:
string rtcTimeString(const char* ts = "MM/DD/YY hh:mm:ss") {
    DateTime now = rtc.now();
    char buf[strlen(ts)+1];  // allocate a fresh buffer
    strcpy(buf, ts);         // copy the template there
    return now.toString(buf);
}

Well explained. Thank you!

This basic C++ (and GIYF).
What about
String Esper::rtcTimeString(std::string dateTimeForamt = "MM/DD/YY hh:mm:ss")
{
  DateTime now = rtc.now();

  return now.toString(dateTimeForamt );
}

See, for instance, this question. Hope this helps :-)


text:
cast double to long leads to unexpected results
I wrote a little program to show my problem:
void setup()
{
  Serial.begin(9600);

  double K=39.85;
  double a=K*100;
  Serial.print("a= ");
  Serial.println(a);

  long val_long = 0;
  val_long = a;
  Serial.print("val_long= ");
  Serial.println(val_long);
}

void loop() {
}

I get this back from my Arduino uno:
a= 3985.00
val_long=3984

I've been pondering for a long time and can't find the mistake! Why is the long value decremented by one? Can anybody help me please?

upvote for uncluding minimal sketch

The problem is that float numbers are seldom an exact representation. So the float is stored as the closest number that is exactly representable as a float, namely
10446438 × 2−18 = 39.84999847412109375.
When you multiply this by 100, you get 16322559 × 2−12 = 3984.999755859375.
And than casting to an int or long results in 3984, not 3985.
so whenever you cast a value from a float or double to an int or long, you always should add 0.5 (so all values from [x - 0.5, x + 0.5) are rounded to x assuming x >= 0, thus:
val_long = int(a + 0.5);

Beware of negative values, see therefore https://www.cs.cmu.edu/~rbd/papers/cmj-float-to-int.html
Better is to use the round function, see comment of Edgar Bonet below.
UPDATE
See comment of Lightness Races with Monica
In case it's not wanted to round up, but you still want 39.84999847412109375 to be 39.85, than you have to add a value that has the value of the least significant bit (actually slightly less but that is impossible to define). In most cases, it's best to add half the significance you want. So if you need two decimal accuracy, add 0.005.

Thank you so much, you made my day! Now everything works fine.

Serial.println(a,5); might have revealed that issue already. Especially on 8bit Arduinos with double being only 32 bit wide. (Same as float)

I edited the answer to add the exact numbers. 2. You can use round(), from the Arduino core. It's a macro that adds ±0.5 (depending on the sign) before casting to long.

@EdgarBonet Thank you very much.  I will also add in my answer a note to your comment.

"so whenever you cast a value from a float or double to an int or long, you always should add 0.5" If rounding is what you want. Sometimes it isn't, then you need another workaround for little inaccuracies. Your solution will change the behaviour when K==39.856, for example. Your answer should address this.

@LightnessRaceswithMonica I'm not sure I understand what you mean … when K == 39.856, adding half and rounding (down) gives 40, which is the normal way of converting. What (other little inaccuracies) you mean exactly?

@MichelKeijzers If K is 39.856 then a is 3985.6, so program's output is 3985, which is presumably deliberate. Your suggestion changes the output to 3986. You've changed the meaning of the program without mentioning it. An alternative is to use "another workaround for [these] little inaccuracies [like the one causing this bug]", such as epsilons. That being said, if K will only ever have max 2 meaningful decimal places, then this is moot.

Ah ok, you  mean it's rounding up while that is not always what is wanted... I will add this indeed. good point.


text:
HX711 - Inconsistent Readings

simulate this circuit – Schematic created using CircuitLab
Wiring is based on the scheme presented below -

(Reference: https://electronics.stackexchange.com/a/174580)
I am using Arduino Mega 2560, HX711 and four load cells to build a weighing scale but having a hard time calibrate the unit. I have tried different libraries and calibration schemes but none of them seem to help. I have found that the raw values corresponding to any given weight (including zero load) are not consistent. Firstly, the readings do not settle even after 10 minutes, and even if I take an average, the next time I put the same weight, I get an entirely different reading making the last average useless. I am seeing errors of the order of +/- 30 lbs when I put a known weight.
I first thought that maybe my load cells are the root cause but when hooked them up directly to Arduino and read the voltage across the bridge, I read stable constant values. Verified the voltage readings with a Voltmeter. (Yes, their resolution is not as good as HX711 but at least they are stable and consistent). I get the voltage reading close to my hand calculations.
Next, I tried testing the HX711 in different ways. In one test, I created a full-bridge using resistors other than load cells, forced the bridge out of balance but cannot read anything other than 16777215. Next, I wanted to see if the board is reacting to any voltage at all, so, I removed the bridge and did not connect anything to E+ and E- pins but supplied known voltages from a DC power supply (from 0 to 4.5V) to the A+ and A- (GND) pins. Now, it is reading only 8388607, no matter what voltage I supply. If I supply +5V or +3.3V from Arduino to the A+ and A- (GND) pins instead of DC Power supply, it then only reads 16777215.
I don't know how to interpret this behavior. How can I resolve the issue and bring the error down? Thanks for your help.
I have included the schematic below. All four Load Cells (LCs) are 3-wired (White, Black & Red). Resistance between W & B wires is around 1980 ohms while that between R & W or R & B is around 990 ohms. SO I connected the four LCs in the manner shown in the schematic. Wire colors have been labelled.
Code:
Code is pretty straightforward as I am simply reading raw values from the HX711 using the following HX711 library - github.com/queuetue/Q2-HX711-Arduino-Library.git
#include <Q2HX711.h>

const byte hx711_data_pin = 4;
const byte hx711_clock_pin = 8;

Q2HX711 hx711(hx711_data_pin, hx711_clock_pin);

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

void loop()
{
  Serial.println(hx711.read());
  delay(500);
}

Can you draw as a schematic or wiring diagram how everything is connected? And please provide your code in your question. Maybe there is something wrong with one of them

I have included both of them in the post. I think the variation in the values that I am seeing is because of residual strain and hysteresis but not sure of that. I have been noting the scale readings for past four days. I have not put any load at all and these are the readings I have obtained -
Day 1: 84442XX
Day 2: 84447XX
Day 3: 84442XX
Day 4: 84447XX
If zero lbs weight correspond to 84442XX, the same empty scale starts reading a different weight the other day. This is the problem I am trying to solve. I expect variation in readings since HX711 is 24-bit but what I have is too high.

If you getting readings at the limit of the HX711, (2^24=16777216) the load cells might not be close enough to identical, and you might have to bias them closer to zero.  Do you have a high resolution voltage meter that you can test the voltage difference between the signal+ versus signal-?  If it's more than 10-20mV, you could add a trim pot to bias a leg of the wheatstone bridge higher or lower.  //  Zero could move around significantly from day to day dependent on temperature and creep. Most use-cases of cheap load cells/scales have a means of zeroing them out immediately before use.

Here is is a picture of how I have seen the sensors connected.  Is this how your is?

When you connected the cells directly to the board, did you do it one at a time or all at once?  Is the board combining the weight values or is it done with the sensors/library?

Hi! Thanks for your response. I have tried many and currently am using the following HX711 library -
https://github.com/queuetue/Q2-HX711-Arduino-Library.git
And the code is simply reading raw values from ADC using hx711.read().
If I use a full-bridge of 4 load cells, I get continuously changing values and if I connect a full-bridge of one load cell and two external resistors, I only read 16777215 and nothing else.

I have connected them both ways. If I use a full-bridge of 4 load cells, I get continuously changing values and if I connect a full-bridge of one load cell and two external resistors, I only read 16777215 and nothing else, even if I put weights on the load cell.

My last piece of advice is to go over your connections for stray what ever.  Look at all the solder joints on EVERYTHING and see if you can find a bridge or something touching that should not.

Thanks for your time. I have checked it a number of times. Couldn't find any unintended connections plus all GND connections are also good.

Questions for clarity or similar belong to the comments under the question. When leaving that out, the question is reduced to "Try calibration". Please either use the comments (if you have enough reputation), or elaborate more about the calibration.

I understand, but it don't have the ability to comment yet, but I was trying to give help and ask questions.  I can delete the answer since no help full information was figured out.

@PriyeshSharma. Is your schematic accurate to how you have it wired?  The schematics I have seen have the sensors wired in a bridge configuration, you show a weird potentiometer setup that will probably result in the weird settings you see as the current is going to be doing wacky things as what you have will never balance out and show anything consistent.

@JeffA: Yes, this is how I have wired the load cells. The way I see it is these particular load cells are equivalent to variable resistors with their resistances changing as load is exerted and strain changes. Hence, the excitation is applied to and voltage is read from red wires (which equivalent to wiper of a potentiometer).

what is the part number for your load cells?

Bought them from Amazon. Do not have any part number or datasheet available. Looks like they are from a manufacturer called CJRSLRB. Not sure if they are the actual manufacturer or just the seller calling himself a manufacturer.

I am starting to think your HX711 is bad

Each of the cheap commodity three-wire red-white-black load cells has two strain gauges in it, configured as a half-bridge.  Under normal loading conditions, one strain gauge is compressed while the other is extended.  You can hook two of the cells up as two half-bridges and 4 strain gauges like your diagram if wire the half-cells white-to-black and black-to white to make sure they unbalance under load instead of balance.  Or you can hook 4 cells up per Priyesh's schematic with two strain gauges in series in each leg. See https://arduino.stackexchange.com/a/18698/6628

@PSharma have you ever been able to resolve the issue? If so, how ?


text:
HC-06 Arduino UNO not working
Trying to get my HC-06 to work. The idea is to control a addressable RBG LED strip in the future. Currently I'm using a Arduino UNO, some wires and a HC-06. I connect the VCC pin to 5V, GND to GND, RXD to TX and TXD to RX. The module has a red light flashing for a second and after that nothing happens. Any idea what I should do next?

What have you tried to connect to the HC-06 over bluetooth? Is your phone (or whatever you are using) actually connected to the HC-06? How do you know, that it is not working? What do you think should happen? What are you doing with the HC-06 (you didn't include your code)

I can't see the HC-06 on my phone, so I can't connect to it. I also found out that the RX pin can only accept 3.3V (previously I only used jumper wires and connected HC-06 directly to Arduino, luckily I have 1k and 2k Ohm resistors if they are needed).The RXD pin on HC is connected to TX (1) on Arduino, TXD is connected to RX (0) on Arduino. For the code I used this: https://i.imgur.com/MhUev3R.png

Probably need to get a breadboard and watch a video if I need to connect the resistors. Maybe if you could help me with a code? Later on I'll have 28 LED's connected to pin ~6 and I'd like to control it via bluetooth on my phone.

2 things: 1. Please copy&paste the code as text into your question. 2. Where did you get that code? It uses pin 0 and 1 for software serial, which cannot work, since hardware serial is on these pins. Also I don't see, why the delay should be needed

Is it required to use resisistors since RX pin needs 3.3V, I'm using USB atm but will use a 5V power bank in the future?

This question might be helpful for this. Your specific module might be 5V tolerant, but I think most HC-06 modules aren't. Look at what your seller says and then decide, if you wanna trust him with this. Or just add the voltage divider, since it doesn't hurt.

Voltage divider didin't work. So I'm connecting HC-06 to Arduino, the module flashes like 10 times and then stops (the light turns off). Isn't it supposed to keep flashing until a device gets connected to it? Currently just want my phone to be able to see this BT module. Any ideas what I should do?

Starting to think that the module is not working. Literally following Youtube guides, they are able to see the HC-06 bluetooth right after connecting the wires. Also their module keeps flashing...

https://i.imgur.com/mTlJ7fK.png This is what it currently looks like, using 1k and 2k resistors (followed this video https://www.youtube.com/watch?v=F6E5mP70jaw&t=1s). Do I need to give the Arduino a code for the module to start working? Currently is still just flashes and then the light turns off.

I don't know, how your module is set up. You should first implement the communication between Arduino and HC-06 (and the communication to the PC for forwarding). Then you can test, if the HC-06 is still alive at the point, that it stops flashing. You can communicate with the HC-06 with AT commands like described at this site. But for that, first fix your wiring. In your photo you are using hardware RX and TX pins, whereas the video tutorial uses different pins. Thats essential

I ordered a new module (also HC-06), this one is working. Guess the old one was sold to me in a broken state...

But thank you all so much for the help, can continue with the project now.


text:
Arduino Uno Rev3 Internal Quartz
I'm using an Arduino Uno Rev3 Board and need to send a trigger signal at a certain frequency (20-50Hz).
This trigger signal should be as accurate as possible (+/- 0.01 ms).
The Arduino site states that the arduino uno has a 16MHz Quartz Crystal, but I'm measuring a frequency accuracy of about 0.35% (which would be typical for a ceramic resonator) instead of what i could expect from a quartz (0.001%).
I'm using the micros() function to measure time.
Am I doing something wrong? How is my frequency so inaccurate?
Thanks for your help! :)

Edit: Indeed when I have a look at the schematics, I see the ceramic resonator (Blue circle). However, there seems to be another 16 MHz part (red circle). could that be a quartz oscillator?

Can you please provide the measurement code by editing your question?

I don't know why they say it has a quartz crystal - it doesn't - it has a ceramic resonator.  This one: https://uk.farnell.com/murata/cstce16m0v53-r0/resonator-ceramic-16mhz-smd/dp/2443265

@Majenko omg are you sure? My whole project relies on this accuracy. Why would they make a false statement on the official website? Is there even an arduino board (alternative) with a quartz crystal?

Yes, I am sure. That is the part from the schematic. I have emailed the webmaster to try and get the error corrected on the product page. There are plenty of other better boards with crystals - more powerful boards generally, such as Teensy, chipKIT, etc.

alright. Thank you :)

All the boards I make with 328P, 1284P, 2560, all use quartz crystals.  0.01mS = 10uS, yes? You can get down to 4uS with micros(), but you have to write code that runs within loop() and doesn't have jitter introduced by loop() background code.  For example, I needed to load 45 shift registers with 8 MHz SPI; to do so I had to disable interrupts and write 45 discrete SPI.transfer lines (spdr = array[0]; 15 no-ops, then spdr = array[1]); 15 no-ops, etc.)  If interrupts were on, I could see (on logic analyzer) that the micros() interrupt would disrupt the timing flow. loop() made is worse.

The Arduino Uno Rev3 has an ATmega328P.
@Majenko as far as I can interpret the schematic, there are two components, the one you sent (ceramic resonator) and another one, possibly the quartz? I try to attach the image

@MarayJay The Uno R3 has a quartz crystal to run the ATMega16U2, not the ATMega328P. It's the one for the ATMega328P that you care about.  Quartz is required for USB for the accuracy, but not for UART since it's more forgiving.

Ok so there is no possibility to get the accuracy of the quartz to control an output pin with this board?

@MarayJay No, I'm afraid not.

@MarayJay If you are good with soldering, there is no reason why you can't replace the resonator on the board with a 16 MHz crystal and two ceramic capacitors (22 uF). Something like this: https://images.app.goo.gl/x5KSXfUf9y1Q9K6e6

The ATMega328P chip is, indeed, clocked by a ceramic resonator. The website is misleading in stating that it has a crystal (I have emailed the webmaster to try and get this corrected, though I don't hold out much hope).
The 16MHz crystal in the schematics is part of the USB interface circuitry and has nothing to do with the timing of your running code. It is purely used to clock the ATMega16U2 chip which provides USB connectivity (USB requires a higher accuracy for stable communication).
There are other boards available with better crystals - most often boards that have native USB connections, such as the Arduino Due or Leonardo, or any of the myriad of boards by other manufacturers, like Teensy or chipKIT.

Thank you very much for the clarification!
I struggle finding an alternative that provides the following specs:

5V Output (I need a 5V signal)
Quartz crystal
RS-232 communication possible
USB connection to connect computer

Would you have a suggestion?

@MarayJay The Arduino Leonardo may be your best bet.

do i understand this right: The leonardo just has one quartz oscillator, because there is no second processor for the usb communication? And you are 100% sure that this is a quartz oscillator, right? I don't trust the arduino page anymore, so i trust you. (you're saving my day btw)

@MarayJay The Leonardo has a direct ("native") USB connection. It comprises the functionality of both the chips on the Uno in one. USB requires the accuracy of a quartz crystal. You can also use the Arduino Micro if you want a smaller footprint. Same chip, just a smaller board.

Thank you so much :)


text:
nRF24L01 : transmission fail when receiver is connected in Serial
I have two Arduino Nano communication with radio.
One is a transmitter and send simple message :
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

//RADIO RF24 PINS
#define RF_CE    7
#define RF_CSN   8

//Radio
RF24 radio(RF_CE,RF_CSN);
const byte address[6] = "00001";

//Communication structure
struct Data {
  long type;
  float value;
} data;

/**************************************************************************/
/*
    Displays some basic information on this sensor from the unified
    sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/

void initRadio() {
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPALevel(RF24_PA_MIN);
  radio.openWritingPipe(address);
}

void setup() {
    Serial.begin(9600);
    // Set delay between sensor readings based on sensor details.
    initRadio();
}

void sendMessage(long type, float value){
  Serial.println("sendMessage");
  data.type = type;
  data.value = value;
  if(radio.write(&data, sizeof(Data))){
    Serial.println("Send SUCCESS");
  }else {
    Serial.println("Send FAIL");
  }
  delay(100);
}

void loop() {
  // Delay between measurements.
    delay(1000);

    sendMessage(0, 20.10);
    sendMessage(1, 45.3);
    sendMessage(2, 1033);

}

The other is a receiver and get the message from the transmitter Arduino and send message with Serial via USB to a computer :
#include <SPI.h>

#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

#include <ArduinoJson.h>

#define RF_CE    7
#define RF_CSN   8

//Radio RF24
RF24 radio(RF_CE,RF_CSN);
const byte address[6] = "00001";

//JSON
const int capacity = JSON_OBJECT_SIZE(8);

//Communication structure
struct Data {
  long type;
  float value;
} data;

long previousMillis = 0;
long interval = 3000;
bool refresh = false;

void sendValue(String source, String type, float value) {
  DynamicJsonDocument doc(capacity);
  doc["type_message"] = "measure";
  doc["source_id"] = source;
  doc["value_type"] = type;
  doc["value"] = value;
  Serial.write(0x11);
  serializeJsonPretty(doc, Serial);
  Serial.write(0x12);
  Serial.println("");
  doc.clear();
}

void initRadio() {
    radio.begin();
    radio.setRetries(15, 15);
    radio.openReadingPipe(0, address);
    radio.setPALevel(RF24_PA_LOW);
    radio.startListening();
}

void readRadio(){
  if(radio.available()){
    while(radio.available()) {
      radio.read(&data, sizeof(data));
      Serial.print("type:");
      Serial.print(data.type);
      Serial.print("value:");
      Serial.println(data.value);
      sendValue("remote", "test_radio", data.value);
    }
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  //Init RF24 Radio
  initRadio();
}

void loop() {
  // put your main code here, to run repeatedly:
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;
    float humidity = 45.60;
    float temperature = 21.30f;
    sendValue("local", "humidity", humidity);
    sendValue("local", "temperature", temperature);
  }
  readRadio();

}

The issue that I have is that when I connect my computer via the Serial port COM to the receiver, every radio message sent by the transmitter fail. But before I connect to the receiver, the messages sent by the transmitter are in success.
I don't know what can cause this issue.

does the RF24L01 use an UART for its serial interface?

@jsotola, it is SPI


text:
How many UNO pins have internal pull up resistors?
As the title implies.
thank you in advance.

All of them have.

which pins are you referring to?

all Digital I/O pins
0 to 13 and A0 to A5.

just wanted to be sure

Note that you need to initialize the pins as INPUT_PULLUP to actually enable the pullup resistor. (Just in case this isn't clear.)

no i dont think it does because it didnt for me

All of them. It's a standard feature on all IO pins in the AVR range.

Thank you very much :)
This is NOT the case in other Microcontrollers am I right?

Not all microcontrollers have them, that is true (low-end PIC for example). Some only have them on some pins (such as older PIC32MX chips). They are getting more and more popular though (now all modern PIC32MX chips and PIC32MZ chips have them), so more modern chips tend to have them rather than not.

That's a great answer, thank you very much again :)

Also some MCUs (such as STM32) have also pull down resistors.

@MichelKeijzers So do modern PIC32 chips (anything since the release of the MX1 / MX2 series).

#Majenko thanks for the addition (I'm quite unfamiliar with PIC32 chips).

Note that while all all AVR chips offer pull-up resistors, you have to turn them on. To do that, use the command pinMode(pin, INPUT_PULLUP) to activate the pullup resistor on the pin pin


text:
"Serial" does not name a type -> How to solve this problem?
I'm trying my best to solve this problem but it didn't changed
The red line was drawn on the last Serial.println */
int cds = A0;
int led = 12;
int trig1 = 2;      // Left Trig
int trig2 = 3;      // Right Trig
int trig3 = 4;      // Front Trig
int trig4 = 5;      // Upside Trig
int echo1 = 6;      // Left Echo
int echo2 = 7;      // Right Echo
int echo3 = 8;      // Front Echo
int echo4 = 9;      // Upside Echo
int vib1 = 10;      // Left vib
int vib2 = 11;      // Right vib

void setup() {
        pinMode(led, OUTPUT);

        pinMode(trig1, OUTPUT);
        pinMode(trig2, OUTPUT);
        pinMode(trig3, OUTPUT);
        pinMode(trig4, OUTPUT);
        pinMode(echo1, INPUT);
        pinMode(echo2, INPUT);
        pinMode(echo3, INPUT);
        pinMode(echo4, INPUT);
        pinMode(vib1, OUTPUT);
        pinMode(vib2, OUTPUT);

        Serial.begin(9600);
}

void loop(){
  long duration1, value1;
  long duration2, value2;
  long duration3, value3;
  long duration4, value4;

  // Ultra Sonic Sensor Part1
  digitalWrite(trig1,LOW);                           // Trigger Output
  delayMicroseconds(2);
  digitalWrite(trig1,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig1,LOW);
  duration1 = pulseIn(echo1,HIGH);                   // Read Pulse Duration
  value1 = microsecondsToCentimeters(duration1);     // Count Distance
  delay(10);

  // Ultra Sonic Sensor Part2
  digitalWrite(trig2,LOW);
  delayMicroseconds(2);
  digitalWrite(trig2,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig2,LOW);
  duration2 = pulseIn(echo2,HIGH);
  value2 = microsecondsToCentimeters(duration2);
  delay(10);

  // Ultra Sonic Sensor Part3
  digitalWrite(trig3,LOW);
  delayMicroseconds(2);
  digitalWrite(trig3,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig3,LOW);
  duration3 = pulseIn(echo3,HIGH);
  value3 = microsecondsToCentimeters(duration3);
  delay(10);

  // Ultra Sonic Sensor Part4
  digitalWrite(trig4,LOW);
  delayMicroseconds(2);
  digitalWrite(trig4,HIGH);
  delayMicroseconds(5);
  digitalWrite(trig4,LOW);
  duration4 = pulseIn(echo4,HIGH);
  value4 =  microsecondsToCentimeters(duration4);
  delay(10);

  //Commend Part (Vibration motor)

  // Print Out Value
  Serial.print(" dist1 =");
  Serial.print(value1);
  Serial.print("(cm)");
  Serial.print(" dist2 =");
  Serial.print(value2);
  Serial.print("(cm)");
  Serial.print(" dist3 =");
  Serial.print(value3);
  Serial.print("(cm)");
  Serial.print(" dist4 =");
  Serial.print(value4);
  Serial.print("(cm)");
  delay(10);
  //

  // Initialize PIN Mode
  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  // 진동모터1,2,3
  if (  value4<60  or  value3<60)
  digitalWrite(vib1,LOW);
  digitalWrite(vib2,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
  digitalWrite(vib2,HIGH);

  if (0< value1 && value1<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);

  if (0< value2 && value2<60)
  digitalWrite(vib1,LOW);

  delay(100);

  digitalWrite(vib1,HIGH);
}

// Function of Count Distance

long microsecondsToCentimeters(long microseconds)
{
  return microseconds/29/2;
}

        int cdsValue = analogRead(cds);

        Serial.print("cds =  ");
        Serial.println(cdsValue);

        if (cdsValue < 38 ) {
                digitalWrite(led, HIGH);
        } else {
                digitalWrite(led, LOW);
        }

Your code would be a lot easier to read and find mistakes in if you formatted it. I see that you did that in the IDE, but in your question, you need to highlight all of the code, then click the "{}" button to make it look like code in your question.
When I pasted your code into my IDE and auto-formatted it, the answer was immediately clear: after the function microsecondsToCentimeters() you have written some code that is not inside any function. C and C++ don't allow that. The error message wasn't very helpful - the compilers easily get confused by our mistakes - but in this case, looking at the formatted code made it clear.
All of the executable code in a C or C++ program (Arduino IDE uses C++) must be inside a typed and named function. Since that is what the compiler was looking for, it seems to have interpreted the word "Serial" as a function type, but no type was defined with that name.
I'm not sure where you intended the lines from the end of long microsecondsToCentimeters() to go, but they need to be inside of a function, somewhere.


text:
Function to control servos
I'm trying to control 6 servos while writing a lean code. I think the function call isn't correctly yet and I think that the variables (pos_n, open_n, servo_1) in the for loop do not get inserted, but instead the string just gets inserted.
I think I have come a long way to not make this a bulky code.
What changes makes this function working, so that the call openValve(1) and openValve(2); work for both servos?
#include <Servo.h>
const int buttonPin = 2;
int buttonState = 0;

Servo servo_1;
const int pos_1 = 0;
const int open_1 = 105;
const int clos_1 = 10;
//Servo servo_2;
//const int pos_2 = 0;
//const int open_2 = 104;
//const int clos_2 = 9;

String servo_n, pos, pos_n, servo, openServo, open_n;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  servo_1.attach(11);
}

void loop() {
  openValve(1); // call the function
  while (true);
}

void openValve(n) {
  int n = 3;
  pos = "pos_";
  pos_n = (pos + n);
  Serial.println(pos_n);

  servo = "servo_";
  servo_n = servo + n;
  Serial.println(servo_n);

  openServo = "open_";
  open_n = openServo + n;
  Serial.println(open_n);

  // DONT USE STRING BUT THE VARIABLE CONTENTS ??
  for (pos_n = pos_n; pos_n <= open_n; pos_n += 1) {
    servo_n.write(open_n);
    delay(10);
  }
}

If you are trying to write "lean" code, then using the String object is not going to make it "lean". The second thing I noticed, was that the code doesn't compile. The first error is "error: 'n' was not declared in this scope. I don't think this is the correct syntax: "void openValve(n) {". HINT: The "n" is an issue. Please fix the syntax errors then edit your question to show us some code that does compile.

variables in the loop do not get inserted into what?

@VE7JRO could you give me a hint what I then should use instead of the String object?

@Ludo: Plain C strings, i.e. arrays of char.

I think you are totally misunderstanding, about variables and types and how using multiple servos with 1 function can work, and that this is your real question and not the thing with inserting variables (whatever you mean by that).
You are trying to put together a string and use it as variable name. That does not work. A string is only a variable/instance of type/class String. It cannot have methods of the Servo class. Also function parameters each have their own type. You cannot provide a value of a different type to this parameter. Servo.write() takes an integer value. It cannot use a String value. Thus the code inside the for loop is nonsense and won't compile. I would suggest doing some C++ tutorials from the web, that explain, how variables work in C++.
Instead you have to use multiple variables of the type Servo, one for each servo motor, that you are using. These variables are instances of the Servo class, which implements all the servo related functions (like write) Each motor gets it's own pin on the Arduino. You can put these Servo objects into an array, so that they can be indexed by an integer number. For example you can define the following variable in the global scope:
#define N_SERVOS 6
Servo servos[N_SERVOS];

This creates an array of type Servo with 6 elements. Each element is one independent servo object. (Note, that I used a define to easily change the number of attached servos when changing the code). You can reach an individual servo object by indexing it:
servos[3].write(pos);

This would write a new position to servo 4 (4 because array indices are starting from 0). Now we need to attach each Servo object to one pin of the Arduino. I would create an extra array, which contains the corresponding pin numbers - also at global scope:
int servo_pin[N_SERVOS] = {6, 7, 8, 9, 10, 11};

Here I used pins 6 to 11, but you can change them, as you like. Then in the setup() function we loop over our servo elements and corresponding pin numbers and attach the servo objects to the pins:
for(int i=0;i<N_SERVOS;i++){
    servo[i].attach(servo_pin[i]);
}

And now you can rewrite your openValve() function corresponding to that. I don't understand, what you wanted the servo to do in the for loop, so I will leave this to you. First you need to correct the syntax at the function declaration. You didn't specify the type of the parameter n. It has to look like:
void openValve(int n){

And then you shouldn't declare a new variable with the same name, so delete the line int n=3;. Then you can delete all the weird string concatiation. Then you need to fix the for loop (as I wrote I will leave that to you, since you didn't explain, what the servo should actually do there). And finally you need to rewrite the servo write line like described above:
servo[n].write(new_pos);

Note, that new_pos is just a placeholder here, for whatever values you need to write to the servo (as already said, I don't understand, what exactly you want the servo to do).

what I then should use instead of the String object?

The String class from the Arduino framework can get you into memory trouble (to be exactly memory fragmentation). You can read Majenko's blog post about Arduino Strings for further explanations.
Instead you should use char arrays aka C-Strings. You create a buffer with a fixed length, that is big enough to hold the biggest chunk of data, that you need to process. Let's say you need at max 30 characters. Every C-String is terminated by a zero ('\0'). This zero also needs space in the buffer. So the actual buffer size is 31.
char string_buffer[31];

You can even directly initialize it with a string value:
char string_buffer[31]="Teststring";

You can use sprintf() to put a formatted string into the buffer. For example a string with a number:
sprintf(string_buffer, "Number: %d", 50);

will put the string "Number: 50" to the buffer and will terminate it with a zero.

I am a bit stuck in thinking like PHP code with inserting 'variables' :p Thanks for your elaborate answer!

@Ludo If you think, that my answer is correct, you can mark is as correct. Then others can see, that this actually solved your problem.


text:
How can I interrupt a delay() when a button is pressed?
I have created a device that allows my son to track time spent on activities and exchanges that time into a time he can use with his electronics (eTime).
Full code in GITHUB
I am having trouble coding the part of the code that handles the countdown from his earned eTime. As it is right now it can count down and give him a warning when his eTime has run out, but the process can't be interrupted.
I would like to have him be able to stop his eTime and use the remainder later. I tried putting the function in a while loop.
while(digitalRead(button_9)==LOW){
    delay(60000);
    avail_time -= 1;
    if(avail_time<0){
      playAlarm();
      return;
}

This one registers the keypress but ignores the delay.
I have also tried using a for loop to count down and another to check every second for a keypress.
void useTime() {
  for(int i=avail_time+1; i>0; i--){
    displayTime(i);
    for(int minute=60; minute>0; minute--){
      if(digitalRead(button_9)==HIGH){
        avail_time = i;
        return;
      }
      delay(1000);
    }
  }
  while(digitalRead(button_9)==LOW){
    tone(buzzer, 2000);
    }
  noTone(buzzer);
  avail_time=0;
  displayOptions();
  return;
 }

That one does not register the keypress.

look at the blink without delay example sketch

Use timestamp instead of delay(), see Blink Without Delay example

I took a look to your code in Github. I think you also need to debounce for button

You asked "How can I interrupt a delay() when a button is pressed?" The short answer is that you can't. delay() is a blocking function. It can't be interrupted. You need to refactor your code as others have suggested.

You can if you handle your button press in a pin change interrupt handler. But still it is bad practice to use delay(). The only legit use is a timed sequence where you are not doing anything else.

You can use the millis function to check the current 'time'. If you store this, and later call this function again, by subtracting you can see how much time has been passed. so instead of delay(500) you use if (millis() - timeStamp >= 500) { ... to continue your code.
As others said in comments,  you also need to debounce to prevent multiple button triggers.
Edit: Debouncing
There is not a library for debouncing (at least not one on the Arduino site), but you can easily copy the needed code from the following sketch:
Arduino Debounce

I was able to use this solution. I have not implemented debounce yet but I'm looking into it. Is there a debounce library or do I need to implement it myself?

I have updated my answer according to your question in the comment.


text:
Arduino GPS Simulator: SoftwareSerial Issues
For my project, i need my Arduino Uno to simulate a GPS. To do this, I need to:

Generate a 5V Pulse once a second (no problem)
Send a $GPRMC NMEA sentence with the current time over RS-232 (i've got an RS-232 shield)

The GPRMC message i need to send is the following:
$GPRMC,075832.293,A,4042.695,N,07400.796,W,,,080120,000.0,W*63
Where the first part is the time, and needs to change.
I basically implemented it as:
// Setup
String prefix = "$GPRMC,";
String gprmc  = "075832.293";
String suffix = ",A,4042.695,N,07400.796,W,,,080120,000.0,W*63";
String all = prefix + gprmc + suffix;
char* buff = (char*) malloc(sizeof(char)*all.length()+1);

Then, in the loop-code i update the time and want to send the message:
//...inside the condition that gets executed once a second
gprmc = String(gprmc.toFloat()+1);
all = prefix+gprmc+suffix;
all.toCharArray(buff, all.length()+1);
mySerial.write(buff);

I'm using an RS-232 shield, which shows me when a message is being sent by blinking an LED.
However, is only seems to work, if i shorten the all string, i.e.:
Works:
all = prefix+gprmc;

Does not work:
all = prefix+gprmc+suffix;

Is it possible that the message is just too long to send? Is there a way I can fix this? Because it's crucial to send the whole message.
Note: I'm currently working on an Arduino Uno, but I'm switching to an arduino Leonardo today. I currently have low memory available (77% used). could this add to the problem?
Thank you so much for your help!! :)

What do you mean with "does not work"? What did you expect and what actually happens?

On the RS-232 Shield, an LED blinks if a message is sent. By "doesn't work" i mean, no message is sent (led no blinking)

First off, some comments about your code:

Never use String unless it is absolutely unavoidable
Unless you have a free() to balance your malloc() you will run out of memory almost immediately
There is never any need to concatenate strings to send through serial like that.

Instead of what you are currently doing, just scrap the String usage and your buf variable completely.  There is no need to concatenate things together - serial sends data one character at a time, so you're gaining nothing by concatenating and only causing yourself more problems.
How you should be doing it:
// The changing value as a float
float gprmc=75832.293;
// Print the prefix
mySerial.print(F("$GPRMC,"));
// Pad the value with zeroes
if (gprmc < 10) mySerial.print(F("0"));
if (gprmc < 100) mySerial.print(F("0"));
if (gprmc < 1000) mySerial.print(F("0"));
if (gprmc < 10000) mySerial.print(F("0"));
if (gprmc < 100000) mySerial.print(F("0"));
// Print the value with 3 decimal places
mySerial.print(gprmc, 3);
// Finally print the suffix
mySerial.println(F(",A,4042.695,N,07400.796,W,,,080120,000.0,W*63"));

Note the use of the F() macro to further reduce RAM usage by keeping the string constants in flash memory.

Thank you! Is there any difference on how the message will be transmitted by using mySerial.print(...) or mySerial.write(...)? somehow, the example uses the .write() command, which introduced my problems.

No. print just calls write but accepts more parameter types.


text:
Is it possible to use the Arduino Due's specials pins for digital writing and reading?
Hello the arduino documentation on the due specifies the pin mapping of the pins.I am making a custom board using the dues schematics and i am running still a bit low on pins. Also some of the special pins offer a better position for traces.
So is it possible digitalWrite()/digitalRead() the specials pins such as:

RX (0-3)
TX (0-3)
SDA (0-1)
SCL (0-1)
CANRX
CANTX
LED RX
LED TX
MISO
MOSI
SCLK

As for the SPI and i2c lines i will be using them for the original purpose,but i would like to take the opportunity to know anyway.
I do not own a due so unfortunately i can not test it

Yes, although you may need to modify the variant files to allow access to them.
Every function on the SAM3X8E is a "multiplexed" function. That is, it shares pins with other functions.  For example CANTX0 is an alternative function on pin PA0.
You can find all the alternative function mappings on page 40 of the datasheet.
You may find that many of these pins already have an Arduino pin number assigned to them in the variant file. If that is the case then you can just use it as you would any digital IO pin.
I have included the comments from the variant files here for quick reference:
/*
 * DUE Board pin   |  PORT  | Label
 * ----------------+--------+-------
 *   0             |  PA8   | "RX0"
 *   1             |  PA9   | "TX0"
 *   2       TIOA0 |  PB25  |
 *   3       TIOA7 |  PC28  |
 *   4       NPCS1 |  PA29  |
 *           TIOB6 |  PC26  |
 *   5       TIOA6 |  PC25  |
 *   6       PWML7 |  PC24  |
 *   7       PWML6 |  PC23  |
 *   8       PWML5 |  PC22  |
 *   9       PWML4 |  PC21  |
 *  10       NPCS0 |  PA28  |
 *           TIOB7 |  PC29  |
 *  11       TIOA8 |  PD7   |
 *  12       TIOB8 |  PD8   |
 *  13       TIOB0 |  PB27  | LED AMBER "L"
 *  14       TXD3  |  PD4   | "TX3"
 *  15       RXD3  |  PD5   | "RX3"
 *  16       TXD1  |  PA13  | "TX2"
 *  17       RXD1  |  PA12  | "RX2"
 *  18       TXD0  |  PA11  | "TX1"
 *  19       RXD0  |  PA10  | "RX1"
 *  20             |  PB12  | "SDA"
 *  21             |  PB13  | "SCL"
 *  22             |  PB26  |
 *  23             |  PA14  |
 *  24             |  PA15  |
 *  25             |  PD0   |
 *  26             |  PD1   |
 *  27             |  PD2   |
 *  28             |  PD3   |
 *  29             |  PD6   |
 *  30             |  PD9   |
 *  31             |  PA7   |
 *  32             |  PD10  |
 *  33             |  PC1   |
 *  34             |  PC2   |
 *  35             |  PC3   |
 *  36             |  PC4   |
 *  37             |  PC5   |
 *  38             |  PC6   |
 *  39             |  PC7   |
 *  40             |  PC8   |
 *  41             |  PC9   |
 *  42             |  PA19  |
 *  43             |  PA20  |
 *  44             |  PC19  |
 *  45             |  PC18  |
 *  46             |  PC17  |
 *  47             |  PC16  |
 *  48             |  PC15  |
 *  49             |  PC14  |
 *  50             |  PC13  |
 *  51             |  PC12  |
 *  52       NPCS2 |  PB21  |
 *  53             |  PB14  |
 *  54             |  PA16  | "A0"
 *  55             |  PA24  | "A1"
 *  56             |  PA23  | "A2"
 *  57             |  PA22  | "A3"
 *  58       TIOB2 |  PA6   | "A4"
 *  69             |  PA4   | "A5"
 *  60       TIOB1 |  PA3   | "A6"
 *  61       TIOA1 |  PA2   | "A7"
 *  62             |  PB17  | "A8"
 *  63             |  PB18  | "A9"
 *  64             |  PB19  | "A10"
 *  65             |  PB20  | "A11"
 *  66             |  PB15  | "DAC0"
 *  67             |  PB16  | "DAC1"
 *  68             |  PA1   | "CANRX"
 *  69             |  PA0   | "CANTX"
 *  70             |  PA17  | "SDA1"
 *  71             |  PA18  | "SCL1"
 *  72             |  PC30  | LED AMBER "RX"
 *  73             |  PA21  | LED AMBER "TX"
 *  74       MISO  |  PA25  |
 *  75       MOSI  |  PA26  |
 *  76       SCLK  |  PA27  |
 *  77       NPCS0 |  PA28  |
 *  78       NPCS3 |  PB23  | unconnected!

Well PA0 is kinda okay since it does not share with other pins. Digital 10 and 4 are have shared pins(PA29), how does that work ? if write high to D10 and LOW to D4, how will that work ? wont both of them short out?

Also if i access the pins via register manipulation do i still need to modify the variant files? They do have an arduino number (69 for CANTX) so i was thinking it should theoretically work, just needing confirmation

D10 is PA28 isn't it?  If there is a number assigned in the variant files then you can just use that as you would for any other digital pin. If you use port manipulation then the variant files don't come into play at all.

If you look at the link in the question thats from the official arduino page, pin 4  connected to both PA29 and PC26  and  pin 10 connected to both PA28 and PC29 .

I would like to take your comment as an asnwer good sir. especially this line If there is a number assigned in the variant files then you can just use that as you would for any other digital pin if you may include it in the answer. Also a link to the variant file for the lazy people that might read this thread

@Jack Done and done

Thank you very much!

@Jack, here is how you can make your own board variant referring the official SAM boards package https://arduino.stackexchange.com/questions/54484/adding-a-custom-board-to-the-arduino-ide/60660#60660

As far as I know you can use them as GPIO too (I know for sure for Arduino Uno/Mega etc., I know for STM32, I would be very surprised if it's not possible for Arduino Due.
Other solutions are using shift registers like:

74HC595: For adding upto 32 outputs using SPI
74HC565: For adding upto 32 inputs using SPI

Or you can use GPIO extenders using either SPI or I2C.

Yes my worst case scenario is using a GPIO extender MCP23S17

I can imagine, the shift registers are easier (enough documentation available for the Arduino Uno/Mega, probably will work on Due as well). Why don't you try to write to a pin directly, or you don't have a Due at hand?

I dont have a due at hand unfortunately, there are no store that i could find that sells them, there are online stores buy they charge a pricey 30$ for shipping.

You can try aliexpress but than you have to wait very long.


text:
USING HX711 ( WITH LOADCELL) WITH PCF8574 IN NODEMCU
I have used hx711 and loadcell with nodemcu (esp8266) in its D1 and D2 pins ( here I have used Logic level shifter and a 5v supply to power hx711).It worked perfectly fine.
Due to the lack of enough pins to accommodate other sensors  in Nodemcu, I'm using PCF8574. I have connected hx711 to pins P0 and P1 of PCF8574.I'm not able to get any output in serial monitor while running like this.
The PCF8574 was connected using resource -
https://www.instructables.com/id/PCF8574-GPIO-Extender-With-Arduino-and-NodeMCU/
The Hx711 was connected using this  code.It is compiling but not getting any output in serial monitor.
#include "Arduino.h"
#include "PCF8574.h"

// Set i2c HEX address
PCF8574 pcf8574(0x20); // A0,A1,A2 all connected to GND
unsigned long timeElapsed;

include <HX711.h>
HX711 scale;

void setup() {
  Serial.begin(9600);
  Serial.println("initializing");
  pcf8574.pinMode(P0,INPUT);
  pcf8574.pinMode(P1,OUTPUT);
  pcf8574.begin();

  Serial.println("initializing");

  scale.begin(P0,P1); //dt , sck
  scale.get_value(5);  // print the avg of 5 readings from ADC minus tare weight
  scale.set_scale(-450.f); // callibration value
  scale.tare();// reset scale to zero
}

void loop() {

  int weight = scale.get_units(3);
  Serial.println(weight);
  delay(1000)

}

Or how about this code without a library? Can I do some changes to it and use pcf8574 ?

#define DT D1
#define SCK D2

long sample=0;
float val=0;
long count=0;

unsigned long readCount(void)
{
  unsigned long Count;
  unsigned char i;
  pinMode(DT, OUTPUT);
  digitalWrite(DT,HIGH);
  digitalWrite(SCK,LOW);
  Count=0;
  pinMode(DT, INPUT);
  while(digitalRead(DT));
  for (i=0;i<24;i++)
  {
    digitalWrite(SCK,HIGH);
    Count=Count<<1;
    digitalWrite(SCK,LOW);
    if(digitalRead(DT))
    Count++;
  }
  digitalWrite(SCK,HIGH);
  Count=Count^0x800000;
  digitalWrite(SCK,LOW);
  return(Count);
}

void setup()
{
  Serial.begin(9600);
  pinMode(SCK, OUTPUT);
  Serial.println("Weight");
  Serial.println(" Measurement ");
  delay(1000);
  calibrate();
}

void loop()
{
  count= readCount();
  int w=(((count-sample)/val)-2*((count-sample)/val));
  Serial.print("weight:");
  Serial.print(w);
  Serial.println("g");

 delay(100);
   // val=0;
   // sample=0;
    w=0;
    count=0;
   // calibrate();

}

void calibrate()
{

  //Serial.println("Calibrating...");
  //Serial.println("Please Wait...");
  for(int i=0;i<100;i++)
  {
    yield();
    count=readCount();
    sample+=count;
   // Serial.println(count);
  }
  sample/=100;
  //Serial.print("Avg:");
  //Serial.println(sample);
  count=0;
  while(count<1000)
  {
    yield();
    count=readCount();
    count=sample-count;
    //Serial.println(count);
  }

  //Serial.println("Please Wait....");
  delay(100);
  for(int i=0;i<100;i++)
  {
    yield();
    count=readCount();
    val+=sample-count;
   //Serial.println(sample-count);
  }
  val=val/100.0;
  val=val/100.0;
  //Serial.println(val);
}

the HX711l ibrary will not magically use the PCF8574 only because you name the pins Px

Thank you for replying. I understand that Hx711 library doesn't know about the PCF8574. I was hoping to tweak the library and work it out. What changes should we make to the library?

PCF8574 takes around 256us to update pins (at standard 100khz i2c). This too high compared to hx711 sck timing constraint which is 50us max. So, it's not possible to communicate with hx711 using PCF8574. wasted two days in finding out this.

Good answer to a not great question.

According to library, hx711 sending pulses to mcu and we are scaling with take this pulses. I think you must connect DOUT and SCK pins directly to the MCU or you must counting pulses via I2C after all create a scaling value according the library code and send it to mcu.

Thank you for answering. I have to use some GPIO expander as I have limitations of pins.  Can you please explain more specifically how it can be done?

I didnt try this method ever but, I checked datasheet and found this code:

Pls check the updated Question.

I didnt try this method but; when i check the data sheet, i found this code on last page:
    sbit ADDO = P1^5;
    sbit ADSK = P0^0;
    unsigned long ReadCount(void){
     unsigned long Count;
     unsigned char i;
     ADDO=1;
     ADSK=0;
     Count=0;
     while(ADDO);
     for (i=0;i<24;i++){
     ADSK=1;
     Count=Count<<1;
     ADSK=0;
     if(ADDO) Count++;
     }
     ADSK=1;
     Count=Count^0x800000;
     ADSK=0;
     return(Count);
}

Here is the pulse counting method i think. So if we are using I2C IC,  we must get pulse datas over it to our MCU and count them. But before this scaling method; we must calibrate loadcells and tare them absolutely.
And i found a link that pointing i2c with hx711. They used sparkfuns IO expander(communicating via I2C) to fix low io problem and connect loadcells to this expander and how read scalings completely.
Here is the link: if you can check, maybe find a solution for your problem.
Sparkfun's I2c Expander with Hx711