text:
Problem sending string with Python to Arduino through serial port
I want to send string 50 to Arduino through serial port, the Arduino UNO seems it communicates with port COM25 but it doesnt receive the string properly:
import serial # if you have not already done so

ser = serial.Serial('COM25')
ser.baudrate = 9600
ser.write(b'50')
ser.close()

Btw Arduino code is correct I checked it with other serial com programs. How can I fix the above code?

serial.Serial() resets Uno and it spends some time in bootloader after then. add a delay/sleep after serial.Serial

I dont understand ;so how can I send string in Python as done in hyperTerminal? My Ard code works with hyperTerminal but I have been looking for a day and couldn't find a code which work for Python.

you need to wait 2 seconds until sending something over that Serial from python. Serial Monitor resets the Arduino too when opening a connection. At opening of window, not before every sent data

The AVR Arduinos (Uno, Nano, Mega) have auto-reset function. At opening of USB connection the circuit around USB resets the MCU. After reset the bootloader waits a second for a new upload. If the upload doesn't happen the bootloader starts the current sketch.
The serial.Serial() command in python opens the USB connection. With that the Arduino is reset and waits in bootloader while you send the data. The data doesn't arrive in your sketch. Add a two seconds wait time after Python's serial.Serial().

Thanks for this answer. This was driving me nuts. Alternatively, I added a line in Arduino setup() to send a byte and waited for that in python to get things started.


text:
Powering Adafruit motor shield
Making sure not to blow anything up before testing.
I have an adafruit motor shield and an arduino Uno. The arduino uno has a power input and I was hoping to use it to power the motor shield, a nema-17 motor, and an I2C connection. Currently I'm using the power connection on the  motor shield to power the nema-17 motor and a serial connection to power the arduino.
Can I just connect a power supply to the input port on the ardiuno uno and power the motor shield and nema-17 step motor?

You should not power the motor shield (and thus the motor itself) through the Arduino. The motor draws a high current (depending on the exact product - there are many versions of the nema-17 - I found current in the range of 1 - 2A) and the voltage regulator (or the diode in the path) are not rated for this much current (for the Uno the absolute maximum is 200mA, including the Uno itself). You will fry these components, if you try to draw more than the rated current.
But you can use the same power supply and provide the power to Arduino and motor shield in parallel. This way the current for the motor does not have to pass through the Arduino.

Thanks, that is exactly what I needed to know. I shall use an external power supply for the motor shield.

source: Stack Exchange

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

sort: votes


text:
Why is the Arduino IDE ignoring my replacement start up code?
I am trying to replace the standard startup code to save flash space.
I've put the new startup.s in my core directory and added the -nostartfiles parameter to the linker reciepe in my platform.txt.
When I compile with the IDE, it does not include my start code at all.
When I use Atmel Studio or a makefile, the code assembles and is included just fine.
How can I get the Arduino IDE to use my new start up code?

to which board package does this apply? I don't have an startup.S file in any of the many installed packages

@Juraj I am using a custom AVR board, but this applies to any board with an architecture that requires a startup file - which is all that I know of. The standard startup file is usually included as an already compiled .o file. For example, the AVR start code lives in the hardware/tools/avr/lib tree as crtXXXX.o where the subsirectory and the XXXX depends on the selected platform/board/chip/variant. This file is automagically included by the linker is -nostartfiles is not specified.

is it a bug in Arduino builder?

@Juraj I'd call it more of an "unexpected, undocumented, and undesirable behavior" than a bug. :)

The Arduino builder is case sensitive and will only see files that end in .S and not files that end in .s.
Renaming the new start up file to startup.S and then deleting the precomplied core archive fixed the problem.
Note that committing this change to git slightly complicated!

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


text:
Attaching Microcontroller to DAC evaluation board
For an independent undergraduate research project I'm trying to construct a digital feedback loop. I have never used an Arduino, or done much electrical/computer engineering, so I'm just taking things one thing at a time.
I've been given this
microcontroller
and this DAC eval board, and now I'm just trying to put them together.
From reading, I need to  attach jumper cables from #16 here to

the pins on the Eval Board here,

but I don't know where to find information on them, so I don't know which to plug into what. Any advice?

Your DAC uses the SPI protocol.  For that you want to connect it to the SPI header. That's the 6-pin (3x2) header numbered 11 on the uC32.
Connect:

The uC32's SCK pin to the DAC's SCLK
The uC32's SDO pin (MOSI) to the DAC's SDIN pin.
The uC32's SDI pin (MISO) to the DAC's SDO pin.

The other pins (I am not sure what they all do off hand, but the datasheet details them) can connect to any GPIO pins you like (except pins 11-13 which duplicate the SPI header - so you could use those instead if you prefer - 11=MOSI, 12=MISO, 13=SCK).

Where would I read about if I need to ground the DAC to the microcontroller? I've edited the post to have the right DAC evaluation board, but the guide for the EVALAD5780 also does not explain their acronyms for the pins.

The pins are all defined in the AD5780 datasheet.  Of course you have to connect the grounds together, otherwise you don't have a circuit.

OK, I think a better question would be where should I read to learn about setting up a serial circuit like this? For example, the DAC has two DGND pins so I don't know where to ground. Also, the J8 pins which are the SPI do not seem to be labeled so idk which is which, can I just use 11-13 since they're duplicates?

Yes, you can use 11-13. The SPI pins are detailed in the uC32 user guide. Connect all ground pins together.

just checking back in, don't I need a Slave Select, SS or SYNC pin somewhere? I can connect the SYNC to the micro-controller and  just set that Low via any pin right?

Yep, any pin at all.

Complete shot in the dark here, but if you're able to look here, I have more questions. I don't know how to debug my SPI connections. https://electronics.stackexchange.com/questions/428571/operating-ad5780-eval-board-via-microcontroller


text:
How to fix "expected ; before ) token" error?
I am in the early stages of writing my program, but I have run into a problem. I am fairly new to Arduino so I'm not sure if there is something I am trying to do that doesn't work, but I am getting an error message

expected ; before ) token

on the line for(count <= 10).
I would really appreciate if someone could let me know why I am getting this error.
#include<EEPROM.h>
const int LED = 12;
const int SWITCH = 4;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  pinMode(LED, OUTPUT);           //LED is always outputting information
  pinMode(LED_BUILTIN, OUTPUT);   //Built in LED is always outputting information
  pinMode(SWITCH, INPUT_PULLUP);  //Switch inputs value when in/out of ground
}

void loop() {
  // put your main code here, to run repeatedly:
  int addr = 0;     //Declaring variables
  int count = 0;
  int seconds;

  if (digitalRead(SWITCH) == LOW) {
Serial.println("----Recording----");

    for (count <= 10) {
      while (digitalRead(SWITCH) == LOW) {
        count = count + 1;
        digitalWrite(LED, LOW);
        delay(50);
      }
      else {
        count = count + 1;
        digitalWrite(LED, HIGH);
        delay(50);
      }
    } else {
      digitalWrite(LED_BUILTIN, HIGH);        //Internal LED blinks
      delay (300);
      digitalWrite(LED_BUILTIN, LOW);
      delay(300);
    }
  }
}

try while (count <= 10) { or for ( ; count<=0; ) { - find some C tutorial to learn about correct syntax

The problem is with the syntax of your for loop.

I switched to a while loop but then I just get an error at the else statement...any other help you could provide?

for and while blocks do not have an else. Only if blocks do. Look at some basic C examples.

@Thomas, you really have to refer to the arduino language refference pages before you  post a question ..... https://www.arduino.cc/reference/en/language/structure/control-structure/for/

Welcome to arduino.stackexchange.
Compiler informs you about the problems with your code. In your case there is a problem with for loop.
Remember, the for loop is one of basic concepts in c/c++ (and many others) programming language.
Syntax is:
for ( init-expression ; cond-expression ; loop-expression )
    statement;

Description of above:
init-expression:
Before any other element of the for statement, init-expression is executed only once. Control then passes to cond-expression.
cond-expression:
Before execution of each iteration of statement, including the first iteration. statement is executed only if cond-expression evaluates to true (nonzero).
loop-expression:
At the end of each iteration of statement. After loop-expression is executed, cond-expression is evaluated.
For example:
for(int count=0; count<10; count++){
    if (count%2) {
        digitalWrite(LED, LOW);
        }
    else{
        digitalWrite(LED, HIGH);
        }
    }

Add some extra code when needed.
To see more description of for loop see here.

Also, only 'if' statements have 'else' clauses; loop statements do not. If you didn't get an error for the 'else' at first, it is because the compiler got lost in the for-loop with only one argument.
'while()' statements have a boolean expression inside the parentheses. Each time the boolean evaluates TRUE, the statement or block following the loop executes once, until the loop evaluates FALSE. Regardless of how many times it executes, even zero, the following code will be executed.
'for()' statements have three expressions. Any of the three may be absent but the places for all three must be shown.

The first expression is executed once at the beginning of the loop. It typically initializes a loop variable, but may do anything, or be absent.
The second expression is a boolean expression that works exactly like the only argument in a 'while()' loop (the loop is only executed if, and for as long as, the expression is TRUE).
The third expression is executed after all of the statements in the loop. It typically advances the loop variable, but may do anything.
Like the 'while()' loop, whatever follows the 'for()' loop will be executed regardless of whether the loop did anything.

Though any of the 'for()' loop's expressions may be left out, both semi-colons must still be present to make it clear which expressions were left out.
Note that 'for(;;)' is an idiom in C that means "forever" - i.e., an infinite loop. Some other construct needs to be executed within the loop to cause it to end, if it not meant to execute perpetually.


text:
D1 Robot... lights up but nothing
I have the Arduino shield described here, I have run the example code compiled to the device, both v1 and 1.1 example, and it shows nothing whatsoever on the screen.
https://www.dfrobot.com/wiki/index.php/Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)
Is there a special trick to initializing this or did I yet again get a lemon that will not display anything?

reduce the code to only the code for displaying something on LCD ..... only this line LiquidCrystal lcd(8, 9, 4, 5, 6, 7); and the code in setup() .... leave loop() empty .... does that display anything?

Like many cheap online shields, this one is a dud, in fact it looks like extended use would fry it if it did work - according to test code this chip is bad.
https://forum.arduino.cc/index.php?topic=96747.0

I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display.

"I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display." Thanks


text:
Sketch talks to Android via BLE on Serial2 but times out after 5 seconds when Serial cable disconnected or not present
From an Android phone I am using the "Serial Bluetooth Terminal" app to communicate to an Arduino Mega 2560 with a Bluetooth Low Energy HM10 (Jaycar XC-4382) module connected via Serial2.
If the physical USB serial cable (Serial) is connected to Arduino the very simple sketch below works fine and runs continuously. When the cable is disconnected mid sketch or the power is cycle without the cable connected the sketch will run for about 5 seconds and then stop.
How can I prevent the sketch from timing out when the serial cable is disconnected?
int counter = 0;

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

void loop()
{
    Serial2.print(counter); Serial2.println();
    delay(1000);
    counter++;
}

how do you power it when disconnected from USB?

12V dc power supply plugged in to the mains

The workaround is to switch to using SoftwareSerial, see code below. Data is continuously sent via Bluetooth from Arduino Mega to Android with or without the usb cable connected.
#include <SoftwareSerial.h>

// Connections
// Arduino HM10
// MEGA
// ----    ----
// 3.3v    VCC
// GND     GND
// 12      RX
// 13      TX

SoftwareSerial bte(12,13);    // RX, TX use (2,3) for UNO
int counter = 0;

void setup() {
  // set the data rate for the SoftwareSerial port
  bte.begin(9600);
  bte.println(counter);
}

void loop() { // run over and over
  bte.println(counter);
  counter++;
  delay(1000);
}

he has a Mega with 4 hardware Serials


text:
Turn on Indicator LED if Moisture Sensor Value >= MaxDryness for longer than 20 min
Hi so I am making a self watering flower pot with a moisture sensor and a peristaltic pump, the code is as follows:

I want to add an indicator LED which turns on if the sensor value has been equal to or greater than MaxDryness for longer than twenty minutes.
How would I alter the code to do that?

why did you post a picture of the code? ... do you really think that someone will spend time typing it in so that it could be added to, and posted as an answer?

Ditch the delay() calls and learn the non-blocking coding style from the BlinkWithoutDelay example. It uses the millis() function, that returns the milliseconds since startup. You can use this as a clock to time the 20min. The coding style has been explained many times on the web.

@jyc43 please replace your source code picture with a code block, this will allow us to insert the lines of code you are looking for.

Please code the text as text

Following is an example how it could be coded.
Remember that the soil is dry by setting DrySoil = true.
Register the time at which a dry period starts in DrySoilBegin.
Check at each 'dry' reading whether DrySoil was true for more than 20 minutes.
Set DrySoil = false at every 'not dry' reading.
The ul after the constant 1200000 makes it an unsigned long value. This because millis() returns a unsigned long result. I am not 100% sure this is necessary (maybe the compiler takes care of this automatically).
As I don't have a plant watering system I couldn't verify the proper working..
#define WATERPIN 10
#define READSOILPIN A0
#define LEDPIN 13

// higher number is more dry
#define MAXDRYNESS 700

#define WATERDELAY 10000
#define WATERPOSTDELAY 5000

bool DrySoil = false; // State of soil
unsigned long DrySoilBegin; // Time when DrySoil became true

void setup() {
  Serial.begin(9600);
  pinMode(READSOILPIN, INPUT);
  pinMode(WATERPIN, OUTPUT);
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  int SensorValue = analogRead(READSOILPIN); //take a sample
  Serial.print(SensorValue);
  Serial.print(" ־ ");

  if(SensorValue >= MAXDRYNESS) {
    // Soil is too dry
    // Check if soil was already in a dry state
    if(DrySoil){
      // If already in a dry state check the duration
      if((millis()-DrySoilBegin) > 1200000ul){
        // If duration is longer than 20 minutes switch LED on
        //   or keep LED switched on
        digitalWrite(LEDPIN, HIGH);
      }
    }
    else{
      // First 'dry' result after 'wet' result(s)
      DrySoil = true; // Set DrySoil in true state
      DrySoilBegin = millis(); // Set beginning of DrySoil period
    }
    // start watering for 10 seconds then
    //    wait for 5 seconds before monitoring again
    Serial.println("Soil dry start watering");
    digitalWrite(WATERPIN, HIGH);
    delay(WATERDELAY); // wait until WATERDELAY milliseconds have passed
    digitalWrite(WATERPIN, LOW);
    delay(WATERPOSTDELAY); // wait until WATERPOSTDELAY milliseconds have passed
  }
  else{
    // Soil is not too dry
    DrySoil = false; // Set or keep DrySoil in state false
    digitalWrite(LEDPIN, LOW); // Switch LED off, or keep it switched off
    delay(50); // Wait 50 ms before next sampling
  }
}

You should move your first else down so that it matches if(DrySoil). 2. You should replace while((millis()-TimerStart)<... by delay(). Using millis() in this blocking fashion has zero advantage over delay() and it makes the code harder to read.

Thank you, you are right. Have edited accordingly. 2. My guess was, this left more internal processes running. But I understand this is not true. Also corrected accordingly.

Here's a little example how to do it. Adapt this way(if you want) by yourself.
// GLOBAL VARIABLES
unsigned long lowSensorTick = 0;
bool dry = false;

void loop()
{
    if (analogRead(/* PIN */) > /* THRESHOLD VALUE */)
    {
        // DRY
        if (dry == false)
        {
            lowSensorTick = millis();
            dry = true;
        }
        else
        {
            if (millis() - lowSensorTick > 720000) // 720000ms = 12min * 60000ms (1s = 1000ms)
            {
                digitalWrite(LED_PIN, HIGH); // LED GOES HIGH/ON
            }
        }
    }
    else
    {
        // WET
        dry = false;
        digitalWrite(LED_PIN, LOW); // LED GOES LOW/OFF
    }
}

Note that zero is a perfectly valid timestamp. You should use a separate boolean variable, like in PimV's answer, rather having lowSensorTick perform double duty of storing the timestamp and a "timestamp valid" state.

Why? millis() will never return zero as value. I use this way in my projects and it works without any problem.

millis() returns zero at the beginning of the program run, and then once again every 49.7 days.

At the begining you have pinMode function. Zero stays for 1/1000s. For overflow that's another problem.

pinMode() executes in way less than a millisecond. 2. lowSensorTick = 0 is a kludge to shoehorn a valid/invalid status info into a variable that is meant to hold something else, and this can make the program misbehave, albeit very rarely. Other than laziness, there is no reason to not use a separate Boolean. If you want to take the (very tiny) risk on you own programs, that's OK. But when answering questions, you should avoid teaching bad practices, especially considering that there is already a perfectly valid answer.

@EdgarBonet fixed.


text:
HTTP request as bytes
I need to send this line of HTTP request as bytes. What is the correct way?
client.write(byte(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>"));

To be more clear this is my C# code for the request
byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

This is my full C# working code
 ServicePointManager.Expect100Continue = false;
        ASCIIEncoding encoder = new ASCIIEncoding();
        byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");
        Uri a = new Uri("http://192.168.0.64");
        HttpWebRequest request = WebRequest.Create("http://192.168.0.64/ISAPI/System/Video/inputs/channels/1/overlays") as HttpWebRequest;
        request.Method = "PUT";
        request.Credentials = new NetworkCredential("admin", "12345qwerty");
        request.ContentLength = 888;
        request.ContentType = "application / x - www - form - urlencoded; charset = UTF - 8";
        request.ContentLength = data.Length;
        request.GetRequestStream().Write(data, 0, data.Length);
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        response.Close();

This is the Arduino version
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 177 };
byte server[] = { 192,168, 0, 64}; // Google
String big_string="<?xml versiding='rlay>";
EthernetClient client;

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

  delay(1000);

  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("POST /ISAPI/System/Video/inputs/channels/1/overlays HTTP/1.0");
    client.println("Host: 192.168.0.64");
    client.println("User-Agent: arduino-ethernet");
    client.println("Authorization: Basic YWRtaW46MTIzNDVxd2VydHk=");
   client.println("Content-Type: application / x - www - form - urlencoded; charset = UTF - 8");

    client.println("content-length:888");
    // client.println();
    //client.println(big_string.length());
    client.write(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

     //client.println();
    //client.print(big_string);
    // client.println();

  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {

    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

why do you think that you have to send the request as bytes?

Because i have a c# aplication that works with sending the request as bytes , in order for the ip camera to read them , and now i need to do the same for the arduino

why do you think that a string character, such as an x is not a byte?

this appears to be an example of an X-Y problem ...... you are asking for help with what you consider to be a solution to your problem, but you withhold the details of the original problem

first reduce the C# code. remove lines with request.ContentLength = 888 and request.ContentType. they are wrong so could be ignored. Uri a = new Uri("http://192.168.0.64"); is not used. remove it

post your Arduino version too

I posted my Arduino version

remove the trailing space from " <xml. in C# version you send correct Content-length. In arduino you send 888. the type must by without spaces application/x-www-form-urlencoded

I changed it , still nothing

For one it's <?xml version='1.0' encoding='utf-8'?> and "Content-Type: application/x-www-form-urlencoded; charset=UTF-8"``. Secondly you specify the content-length to be 888, while the string above is 895 characters long. Thirdy the data you send isn't actually application/x-www-form-urlencoded`, but most likely the server doesn't care about this. Lastly, you haven't told us what the actual problem is. What doesn't work? Where does the C# code come into play here?

My problem is that nothing is sent to the camera , i need the arduino to send text to the ip camera display

Characters are bytes. ASCII codes of characters are the values. There is no difference between client.print(str) and client.write(str, strlen(str)). And client.write(str) is the same too.
In C# or Java the constant string is of type String. It is an object. You must call a method of the object to get the raw char/byte array. In Arduino a constant string is of type const char* a.k.a. const char[] which is on low level the same as const byte* or const byte[]
Equivalent of C#
byte[] data = encoder.GetBytes("some string");
for ASCII characters (not UTF) in C is
byte data[] = "some string";

I read that (client.write) send bytes and (client.pritnln) sends string and chars etc , i understand your answer.  but i think it needs to be like my c# code that i edited in my question

in C# the constant string is of type String. it is an object. You must call a function to get the char/byte array. in Arduino a constant string is of type const char* a.k.a. const char[] which is on low level the same as const byte* or const byte[]

And what would be the way to do this ? sorry i am not that good in programming and i am having a little hard time with the bytes array

without byte(. it does wrong

One more question what about the Json library ? can it be used for this problem ?

this is xml, not json

you have a working C# code and can't rewrite it to Arduino?

Yeah i have the full working code on c# but cant rewrite it to Arduino

I posted it in my question


text:
Serial Communication between 2 Arduinos for analogRead value
I have an optical sensor connected to A0 on Arduino #1 (Nano) giving me values from 200 to 1010. I need to receive these values in Arduino #2 (Nano) through serial communication. I have used a simple code for sending and receiving bytes, but I don't understand how to get the actual sensor values as int. I found some examples showing single values, but as far as I can understand variable values are more complex.
Transmitter Code:

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

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
}

Receiver Code:
void setup() {
        Serial.begin(9600);
}
void loop() {
        if (Serial.available() > 0) {
        int incomingByte = Serial.read();
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
        }
}

Maybe you should slow down the serial printing on the transmitter side. The Arduino will pretty fast fill up the whole buffer and every serial write with a full buffer will result in values, that do not get transmitted. That might also be the problem with Rudy's answer. Try adding a short delay(100);

You'll want to get familiar with the standard C function sscanf().  It does exactly what you're looking for, converts an ASCII string into whatever type you like.
sscanf() API
The code to read an integer from the serial port would look something like this:
  char recv_buf[10];  int recv_int;
  Serial.readBytesUntil('\n', recv_buf, 9);
  recv_buf[9] = 0;  // make sure it's null terminated
  sscanf(recv_buf, "%d", &recv_int);
  Serial.print("I received: ");
  Serial.println(recv_int);

One byte is 8 bits so 2^8 is equal to 255. One byte can hold value up to 255. Since you have value of 1023(max possible) you have to split value into two bytes.
Here's an example:
unsigned byte highValueByte(int value)
{
    return (value >> 8);
}

unsigned byte lowValueByte(int value)
{
    return (value - (highValueByte(value) << 8));
}

int giveValue(unsigned byte highByte, unsigned byte lowByte)
{
    return ((highByte << 0) & 0xFF) + ((lowByte << 8) & 0xFFFF);
}

void loop()
{
    int senValue = analogRead(/* PIN NUMBER */);
    int byteOne = highValueByte(senValue);
    senValue = lowValueByte(senValue);
}

Your code Works for one byte(try it), but it doesn't for two bytes value. Because you have two bytes, you have to introduce some kind of buffer.
Example:
unsigned byte buffer[2] = { 0, 0 };
Also be sure you connected pins properly. RX from Arduino #1 goes into TX from Arduino #2 and vice versa.
About serial communation sync


text:
Can I make the BT module disconnect with a BT module and connect with another in the code?
I am working on a project that requires a connection between two BT modules (HC-05) and a mobile phone. Later on, I encountered a problem: I can't connect two BT modules to one at the same time, So I thought about the possibility of ending a connection and starting the other one when needed. If that was possible, how can I do that in an arduino code?
One of the BT modules is a master which means it can't connect to the phone and it has to be a master because it must be connected to the other slave BT module.

Send AT+ROLE=1 to BT module to set module into master role.
To set module back to slave mode, send AT+ROLE=0
Also check this video, you have source code in the description. It will help you understand how to do it.

But that requires reversing the rx-tx connection to enter the AT mode from the connection being used to send and receive data, which as far as I know can't be done during the code execution as the pins setup is being configured once at the beginning of the code.

Can you share your code? Serial comm(RX TX) is two way communication

I haven't written a code yet.

Try with this command. You can't know without the  code

As I knew recently that the BT connection is a point to point connection which means that can't connect the two BT modules and the mobile in one network at the same time.

That's true, only one device can be connected to one BT module. It's normall.

I have tried many time to enter the AT command mode connecting the tx with the rx and vice versa but it didn't work. Strange characters were appearing on the serial monitor. It didn't work till I connected the rx with the rx and the tx with the tx.

TX from BT module goes into RX pin from Arduino and vice versa. That's the way you talk with BT module.

So I decided to use the slave module to communicate between the masters in different times (connects with one and disconnects with the other). How can I make the BT module do that (to disconnect with the current BT module and wait for connection with another known module)?

To connect the BT module to the arduino for communication Rx to TX and TX to RX is used. But to enter the AT mode I had to connect the RX to the RX and the TX with the TX and it worked.

Send proper command to BT module. Here's link with list of all commands for HC-05 BT module. Anwser is edited

@SilvioCro, the trick with connecting RX to RX, TX to TX is that then the USB chip is connected RX to TX to module and you can talk to module from the Serial Monitor. The main MCU must have a sketch without Serial.begin() (empty sketch or Blink)


text:
What's the function of this transistor on Arduino Mega?
I am trying to get information about the transistor on the Arduino Mega board below:

It says "340P" on the transistor. I want be able to know which model transition is this so that I can check its documentation. It also want to know what it is driving or its function on the Arduino board.

It's a P-channel MOSFET.  It's job is to act as a "dropless" diode.
The principle is this:

MOSFETs have a built-in diode across them in reverse bias (an effect of the chemistry)
The P-channel MOSFET is connected backwards in series with the incoming USB power.
The internal diode conducts power when there is +5V in to the USB to give power to the board.
The diode imposes a voltage drop, but there is enough voltage still to run the circuitry.
An op-amp compares the incoming voltage from the barrel jack (divided by 2) against 3.3V.  If it's less than 3.3V (6.6V incoming) or not there at all, it turns on the P-channel MOSFET
The MOSFET then short circuits the internal diode removing the voltage drop, giving the full 5V from the USB to the rest of the board.

simulate this circuit – Schematic created using CircuitLab
Note: diode shown is internal to the MOSFET.
The MOSFET is designated T2 in the schematic, and is a FDN340P on the reference design, although the actual model is not that critical, as long as the threshold voltage is above about -3V and it can happily handle 500mA or more.

"The diode imposes a voltage drop" I noticed this too and was curios on what's going on. Thanks for your clear answer

As a curiosity: if you connect 5V on the Vin, it'll be injecting current back to the USB (mainly if it's powered down). Or if you accidentally short 3v3 to 5v, threshold voltage jumps over 10V. (the first one was caused by 5V voltage regulator instead of 9V. Second one by some short on shield and 9V on Vin)


text:
NRF51822 ± Arduino Uno / ATmegaXXX?
Hello I want to make a simple home automation project and I'd like to use an arduino uno for prototyping and later a atmega for deployment. I need some sort of a mesh communication method. I was thinking about the NRF51822 chip but I can't find any arduino libraries for it.

NRF51822 has a MCU. you don't need to add ATmega

you want to use Bluetooth for home automation?

Oh, weird it's advertised as a BLE module. And yeah

You can use the NRF51822 as module with AT firmware attached to Arduino. Then you need only the AT commands reference and some examples how to send AT commands and parse the response.
Or you can use the 32-bit ARM cortex-m0 micro-controller inside NRF51822 with Arduino nrf5 package. It requires a programmer/debugger hardware for sketch upload.


text:
What components do I need to build Arduino based water pump controller?
I have situation at my home which is causing us a lot of headache. We get drinking water only at midnight and someone has to wake up and switch on electric pump. This electric pump will pump water from water tank present at ground floor to the water tank present on the terrace.
I want to automate this electric pump operation and I have come up with following rules for it:

When water tank at ground floor is almost full then automatically turn on the pump which will push water from ground floor to the tank on the terrace.
When water tank on the terrace is full then switch off motor.

I am a professional software engineer and I have vast experience in Java, Scala, REST API, Big Data and all but I am totally new to Arduino so I do not know which Arduino components I need to build the above mentioned system.
Any guidance will be deeply appreciated.
Thanks,
Chandra

Float Switches are probably all you need.

In fact you can probably do it with discrete logic gates.

How far away are both tanks from each other? It might not be feasible to get a wire from both tanks to the Arduino. Is the pump near the tank on the terrace of near the tank on the ground-floor. If the pump is on the terrace, and you can't get a wire (for the float-sensor) to the ground-floor tank, you could add a RTC module to the Arduino, and always start the pump and 1AM. Have a float sensor in the tank to make the pump stop when the tank is full. Maybe add a flow sensor or something, to make sure the pump isn't pumping air (which might damage it (maybe))

If you are controlling an AC pump, you might look into a PowerTail switch, which allows you to control AC power easily and relatively safely, but of course, if you are working with anything around water, be careful!  http://www.powerswitchtail.com/

The easiest to build would be to use a real-time clock shield for time-keeping (examples: make or buy) and a relay- or solid-state switch shield (popular item - many choices) for switching the pump. A simple wall power supply providing 5volts to run the Arduino completes it. Oh, yes - an Arduino board, too!


text:
how to code LED turning signals on smart car
this question is regarding how to add turn led signals on arduino powered smart car. I have 4 leds to give turn indications on my smart car(line follower, obstacle avoider, Bluetooth mobile controlled and also IR remote controlled)
can someone help me to modify the code in such a way that I can add led turn signals?(I'm completely new to arduino)
want two front leds high at the same time when the car moves forward and when the car moves backward i need two back leds high at the same time.
i also need two right leds high at the same time when it turns right and I need two left leds high at the same time when it turns left .
this is the code
#include <IRremote.h>
#include <Servo.h>

//Pin assignments and global variables per function. Customize if needed
//*******Pin assignments Motor board and IR receiver********************
const int MotorRight1 = 7;
const int MotorRight2 = 8;
const int MotorLeft1 = 9;
const int MotorLeft2 = 10;
const int MotorRightPWM = 6;
const int MotorLeftPWM = 11;
const int irReceiverPin = A5;
const int servoPin = A4; //orange wire
int iSpeed = 255; //speed, range 0 to 255
const int LedPin=13;

//******Infrared key bindings********************************************
const long IRfront = 16730805;      //go straight: button up
const long IRback = 16718055;       //go back    : button down
const long IRturnright = 16734885;  //turn right : button right
const long IRturnleft = 16716015;   //turn left  : button left
const long IRstop = 16726215;       //stop       : button OK
const long IRcny70 = 16754775;      //CNY70 automatic mode: button EQ
const long IRAutorun = 16750695;    //Ultrasonic mode : button play/pause
//******Track following pin assignments and signals**********************
const int SensorLeft = 5;      //
const int SensorMiddle = 4 ;   //
const int SensorRight = 3;     //
IRrecv irrecv(irReceiverPin);  // IRrecv signal
decode_results infrared;       // decode result
//*******Ultrasonic pin assignments and signals**************************
const int echoPin = 12; // ultrasonic receive=echo pin
const int triggerPin = 13; // ultrasonic send=trigger pin
Servo myservo; // define myservo
const int degreesForward = 130; //nr degrees to look forward
const int degreesLeft = 60; //nr degrees to look left
const int degreesRight = 180; //nr degrees to look right
const int delay_time = 250; // servo motor delay
const int Fgo = 8; // go straight
const int Rgo = 6; // turn right
const int Lgo = 4; // turn left
const int Bgo = 2; // go back
//*****Bluetooth signals**************************************************
char val; //stores received character. Needs to be global to perform continuous movement

//*********General SETUP: activate pins***********************************
void setup() {
  //start receiving serial infor
  Serial.begin(9600);
  //motor connections
  pinMode(MotorRight1, OUTPUT);  //

  pinMode(MotorRight2, OUTPUT);  //

  pinMode(MotorLeft1,  OUTPUT);  //

  pinMode(MotorLeft2,  OUTPUT);  //
  pinMode(MotorRightPWM, OUTPUT); //enable for right side motor
  pinMode(MotorLeftPWM, OUTPUT); //enable for right side motor
  irrecv.enableIRIn();      // start infrared decode
  myservo.write(degreesForward);       // will make head look in front

  //black track following
  pinMode(SensorLeft, INPUT);
  pinMode(SensorMiddle, INPUT);
  pinMode(SensorRight, INPUT);

  //Ultra sonic
  //digitalWrite(2,HIGH); //what is this pin for?
  pinMode(echoPin, INPUT);
  pinMode(triggerPin, OUTPUT);
  myservo.attach(servoPin);
}

//**************Movement functions******************************
void advance(int d) { //go straight
  digitalWrite(MotorRight1, HIGH);
  digitalWrite(ledrightfrontindicator, HIGH);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(ledrightfrontindicator, LOW);
  digitalWrite(MotorLeft1, HIGH);
  digitalWrite(ledleftfrontindicator, HIGH);
  digitalWrite(MotorLeft2, LOW);
  digitalWrite(ledleftfrontindicator, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void right(int d) { //turn right (single wheel)
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void left(int d) {//turn left(single wheel)
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void turnR(int d) {//turn right (two wheels)
  digitalWrite(MotorRight1, HIGH);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void turnL(int d) {//turn left (two wheels)
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, HIGH);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void stopp(int d) { //stop
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void back(int d) { //go back
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}

//************Ultrasonic distance calculator*************************************
//detect distance for given angles and print char + direction
float getDistance(int degrees, char dir) {
  myservo.write(degrees);
  digitalWrite(triggerPin, LOW); // ultrasonic echo low level in 2us
  delayMicroseconds(2);
  digitalWrite(triggerPin, HIGH); // ultrasonic echo high level in 10us, at least 10us
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW); // ultgrasonic echo low level
  float distance = pulseIn(echoPin, HIGH); // read time
  distance = distance / 5.8 / 10; // turn time to distance
  Serial.print(dir); //
  Serial.print(" distance: "); //
  Serial.print(int(distance)); //  output distance (mm)
  Serial.print("\n");
  return distance;
}
//*************Ultrasonic direction decision making******************************
//measurements three angles (front, left, right
int getDirectionFromdetection() {
  int Fspeedd = 0; // front distance
  int Rspeedd = 0; // right distance
  int Lspeedd = 0; // left distance
  int delay_time = 250; //
  int directionn =0;

  //get front distance
  Fspeedd = getDistance(degreesForward, 'F');

  // if distance is less than 10mm
  if (Fspeedd < 10) {
    stopp(1); //  clear output
    directionn = Bgo;
  }
  // if distance less than 25 mm
  else if (Fspeedd < 25) {
    stopp(1); // clear output
    Lspeedd = getDistance(degreesLeft, 'L'); // detection distance on left side
    delay(delay_time); // waiting for the servo motor to become stable

    Rspeedd = getDistance(degreesRight, 'R'); // detection distance on right side
    delay(delay_time); // waiting for servo motor to be stable

    // if left distance greater than right
    if (Lspeedd > Rspeedd) {
      directionn = Lgo; // go left
    }

    if (Lspeedd <= Rspeedd) {//if left distance less than right
      directionn = Rgo; //go right
    }

    if (Lspeedd < 15 && Rspeedd < 15) { //if distance less 10mm both right and left
      directionn = Bgo; //go back
    }
  }
  else {
    directionn = Fgo; //go straight
  }
  return directionn;
}

void autoRunUsingUltraSonic() {
  bool stopPressed;
  int directionn = 0; // front=8, back=2, left=4, right=6
  while (IRAutorun) {
    myservo.write(80); // make the servo motor reset
    directionn = getDirectionFromdetection();
    stopPressed = stopCommandPressed();
    if (stopPressed) {
      break;
    }
    else if (directionn == Fgo) { //go straight
      infrared.value = 0;
      advance(5); //
      Serial.print(" Advance "); //
      Serial.print(" ");
    }
    else if (directionn == Bgo) { //go back
      infrared.value = 0;
      back(8); //
      turnL(3); //
      Serial.print(" Reverse "); //
    }
    else if (directionn == Rgo) { //turn right
      infrared.value = 0;
      back(1);
      turnR(60); //
      Serial.print(" Right "); //
    }
    else if (directionn == Lgo) { //turn left
      infrared.value = 0;
      back(1);
      turnL(60);
      Serial.print(" Left ");
    }
  }
  infrared.value = 0;
}

//*************************Bluetooth functionality***********************
//Bluetooth commands
void bluetoothCommand() {
  if (Serial.available()) { //check if bluetooth command available
    val = Serial.read();
    Serial.write(val);
  }
  if (val == 'F') { // Forward
    advance(10);
  }
  else if (val == 'S') { // Stop Forward
    stopp(10) ;
    val = Serial.read(); //read value again, otherwise can't continu with infrared
  }
  else if (val == 'B') { // Backwards
    back(10);
  }
  else if (val == 'R') { // Right
    turnL(10);
  }
  else if (val == 'L') { // Left
    turnR(10);
  }
  else if (val == 's') { // Stop, not used though
    stopp(10 ) ;
  }
  else if (int(val) >= 49 && int(val) <= 57) { //set speed
    iSpeed = (int(val)-48)*26;
    Serial.println("Speed set to: " + iSpeed);
  }
  else if (val == 'q') { //set speed
    iSpeed = 255;
    digitalWrite(LedPin,HIGH);
    Serial.println("Speed set to: " + iSpeed);
  }
  else if (val == 'W') {
    digitalWrite(LedPin,HIGH);
  }
  else if (val == 'w') {
    digitalWrite(LedPin,LOW);
  }
}

//Check if stop command on remote is pressed (button 5)
bool stopCommandPressed(){
  bool stopPressed = false;
  if (irrecv.decode(&infrared)) {
    irrecv.resume();
    Serial.println(infrared.value, HEX);
    if (infrared.value == IRstop) {
      stopp(10);
      stopPressed = true;
    }
  }
  return stopPressed;
}

void followBlackLine() {
  bool stopPressed;
  int SL;  //sensor left
  int SM;  //sensor middle
  int SR;  //sensor right
  while (IRcny70) {
    SL = digitalRead(SensorLeft);
    SM = digitalRead(SensorMiddle);
    SR = digitalRead(SensorRight);

    if (SM == HIGH) {//middle sensor in black area
      if (SL == LOW & SR == HIGH) {//left sensor in black area, right sensor in white, turn left
        left(0);
      }
      else if (SR == LOW & SL == HIGH) {//left white, right black, run right
        right(0);
      }
      else { // left and right both in white, go straight
        advance(0);
      }
    }
    // middle sensor in white area
    else {
      if (SL == LOW & SR == HIGH) { // left black ,right white, turn left
        left(0);
      }
      else if (SR == LOW & SL == HIGH) {
        right(0);
      }
      else {  //left and right both in white, stop
        stopp(0);
      }
    }
    stopPressed = stopCommandPressed();
    if (stopPressed) {
      break;
    }
  }
  infrared.value = 0;
}

//**************************************MAIN LOOP***************************************
void loop() {
  //bluetooth commands
  bluetoothCommand();
  //************************************normal remote control mode ********
  // decoding success 'receive infrared signal
  if (irrecv.decode(&infrared))  {
    if (infrared.value == IRfront) {
      advance(0); //go straigt
    }
    else if (infrared.value ==  IRback) {
      back(0); //go back
    }
    else if (infrared.value == IRturnright) {
      turnR(0); // go right
    }
    else if (infrared.value == IRturnleft) {
      turnL(0); // go left
    }
    else if (infrared.value == IRstop) {//stop
      stopp(0);
    }
    //********************follow black line********cny70 automatic mode********
    else if (infrared.value == IRcny70) {
      followBlackLine();
    }
    //***********************ultrasonic automatic mode***************************
    else if (infrared.value == IRAutorun ) {
      autoRunUsingUltraSonic();
      myservo.write(degreesForward);       // will make head look in front
    }
    //********************wait a little before continuing**************************
    irrecv.resume();
    delay(300);
  }
  else {
    stopp(0);
  }
}

This is quite a lot of code. Did you write it yourself? What exactly prevents you from adding LEDs, which you turn on and off with digitalWrite(), just like you activate the motors.

Why do you have this loop in your followBlackLine() function: while (IRcny70) ? `IRcny70 is a constant with a value greater than zero, so this is essentially an infinite loop, thats difficult to read.

The same goes for autoRunUsingUltraSonic()

I got the code online

i did not write it myself

as im a beginner please tell me what modifications i will have to do to add leds

i need 2 leds in front and 2 leds at the back of the car.

i want two front leds high at the same time when the car moves forward and when the car moves backward i need two back leds high at the same time.

i also need two right leds high at the same time when it turns right and  I need two left leds high at the same time when it turns left

So no blinking or stuff like that? Then you can simply turn on the corresponding LEDs in your moving functions ( back(), advance()) with a digitalWrite() and turn them off after the delay() with the same function. Have you looked at the many examples, that come with the Arduino IDE? They can teach you how to control LEDs right good.

please don't get angry, can you please do that for me as i tried but it didn't work...

do I have to use any resistor or something like that to make it work??

I'm not angry. But you will not get happy with the Arduino platform, if you don't try to understand, how the code actually works. And also we are not a free coding service. It is part of the working principle of this site, to first research the topic and try it out, and then come here with a specific question. One reason for this is, that you would have to answer the same questions over and over again, which already have been explained on the web for multiple times. So please first learn how basic examples like Blink work and how the components have to be connected. It's all on the web.

This site is not a free code writing service.

Like chrisl suggested, add the led code to the functions advance, back, left, and right
const int LedFrontRight = 21;//change pin numbers
const int LedFrontLeft = 22;
const int LedBackRight = 23;
const int LedBackLeft = 24;

// ...

void setup() {
  // ...
  pinMode(LedFrontRight, OUTPUT);
  pinMode(LedFrontLeft , OUTPUT);
  pinMode(LedBackRight , OUTPUT);
  pinMode(LedBackLeft  , OUTPUT);
}

//**************Movement functions******************************
void advance(int d) { //go straight
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void right(int d) { //turn right (single wheel)
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void left(int d) {//turn left(single wheel)
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}
void turnR(int d) {//turn right (two wheels)
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void turnL(int d) {//turn left (two wheels)
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}
void stopp(int d) { //stop
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void back(int d) { //go back
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}


text:
Newbie question - Biltong Box Project
I am a newbie to electronics, but I do have experience working with electrical wiring in the UK, so I am comfortable working with 240V reasonably safely. I have also built a camper including all the 12V electrics from scratch. I am fairly technically able, as a building physicist and academic researcher. However, my expertise is in mechanical engineering and physics rather than electronics or electrical engineering.
The Project
I am designing a new generation biltong box. My previous biltong boxes had electrical devices wired individually into plugs and then manually switched.
For those who dont know 'biltong' is the South African equivalent of US jerky. We simply dry the raw beef as opposed to light cooking.

Image 1 - first generation manually switched biltong box
The first generation boxes worked great - they were a test bed for the physics - airflow/heat and drying rates. However, they lacked finesse and were technologically challenged. So I have set myself the goal of building a new smaller box, laser cut from acrylic and packed with more intelligence.
My inspiration is drawn from this great project
Technical details
The biltong dryer design currently comprises of:

1no 240V AC 60W tubular heater - this one specifically. I might want to add another in the future.
2no 12V DC 14.4W axial fans - these ones
1no 12V LED strip light - not yet selected

What I want to do / Problem Statement
I would like to have an Arduino based system, to facilitate the following features:

2no temperature and humidity sensors (one at the inlet at the bottom and one at the outlet at high level)
Touch screen to: 1. display temperature and humidity over time, 2. enable manual control of the heater, fans and LED light, 3. allow me to modify the temperature and humidity setpoints
The ability for the Arduino to control the heater (on/off) and the fans (ideally variable) based on setpoints for temperature and humidity. But also to allow me to operate the heater and fans individually from the touchscreen - on / off / auto for all.

Please help
I know all the kit I am trying to control and how I want to do it (conceptually). Now I need some advice on how to make this happen please.
To kick things off I have purchased an Arduino MEGA 2560 board and kit and have experimented with a few small projects. I now want to use this to control the above.
Questions

Is my idea sensible and achievable (technically)?
I know that I will need a 240V relay to control the heater. Is this safe and reliable? ** This is my biggest concern. What can you recommend for this - there are so many available on the market.
I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?
Can I control the speed of the proposed 12V fans? And how is this achieved?

Huge thanks in advance.
First Edit
My calculated current for the heater is 60W / 240V = 0.25A
Questions:

So for a SSR - this looks like a good option - what do you think?
Found a four channel, four route MOSFET - what do you think? Once I have the switching working, i will consider working out the PWM. But switching will be fine for now.
How do I go about designing the circuitry - are there any good online Arduino resources for this?

Second Edit

Not sure where to go from here!
Also, cannot find MOSFET's in Fritzing.

It may be better to post your question on a different SE, like electrical engineering.  Questions here need to be specifically about an aspect of Arduino programming.

Thanks Paul - can the MOSFET control the speed or do i need additional PWM module for that. Excuse the noob question. Please see the first edit in the original question where i have found some options, which I would appreciate some advise on.

Personally I do not feel it being on topic, basic electric control imho is on topic (As in, what component do I need from my Arduino to control x). Nor do I think it would be worth the hassle to close or move the question as it's perfectly answerable and has been already answered.

Regarding components, if it matches your requirements, they should be fine. I think you should separate it in smaller projects, first try controlling a single fan and then build on that. The mist simple designing tool is "Fritzing".

My biggest concern would be the touchscreen, the Arduino has quite limited processing power and interfacing a touchscreen can be difficult.
However, if you purchase the screen from a source that supplies example code, tutorials and libraries (such as adafruit or other known vendors), you should be OK. Alternatively you can check if an 2x16LCD with buttons/'rotating knob' suffices as user interface.

If you switch from Arduino to chipKIT you would get plenty of resources for running a touch screen - as well as my premium DisplayCore library suite.  Unfortunately discontinued now, the 4D Systems Picadillo-35T used to be the ideal solution - chipKIT plus nice touch screen in one. Such a shame they discontinued it :(

I am tending towards a simplified solution of LCD and switches. I am also concerned that the touch screen will add another layer of complexity to the project

Where is the best place for me to now learn how to connect all this up physically? I have downloaded Fritzing and got all the components in there that I need to model the circuitry, but not got much of a clue of how they physically connect and how to plan the physical connections. The Arduino for example has so many connections.

Ruling this "off-topic" seems unnecessarily strict and unfortunate. It sounds like a perfectly good Arduino project to me, and not unlike some other recent, and accepted, questions about components choices and/or connectivity. Voted to unhold/reopen.

I am confused about why this is off topic...?

https://arduino.stackexchange.com/tour

Is my idea sensible and achievable (technically)?

Yep, sure is. It's not really much different to a DIY Reflow Toaster Oven.

I know that I will need a 240V relay to control the heater. Is this safe and reliable? ** This is my biggest concern. What can you recommend for this - there are so many available on the market.

I would suggest an SSR instead of a mechanical relay. Easier to drive, and less electrical noise.

I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?

No. Use MOSFETs for those. You can drive those with PWM to change the speed / brightness.

Can I control the speed of the proposed 12V fans? And how is this achieved?

Yes - see above.
As far as control goes you may want to investigate PID as your calculation method.

Thank you for the advice. I have added an edit to the original post with some suggestions on possible devices. Would be grateful for any comments.

@CairanVanRooyen Yeah, looks OK.  I use these SSRs in my reflow oven simply because they are easier to mount in a chassis than a PCB-based one.MOSFETs look fine.

Thanks Majenko. All ordered, just got to wait for the postman!


text:
Fail programing a Sonoff Dual with Arduino IDE
1) I have a Sonoff Dual, which I wish to upload a Sketch.
2) Other Sonoff basic devices programed the same way, with succes.
But when uploading  the sketch the ( even the generic Blink sketch ) - I do not get any response from the Sonoff device.
3) pins were soldered correctly according this tutorial
4) Uploading the sketch succeeds, using FTDI set to 3.3v.
What might be the reason for it ? What can I do more to check it ? my only guess is that something has happened to Sonoff device - but it uploads successfully.
Guy
Code (edit2)
    /*
  Blink

  Turns an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino
  model, check the Technical Specs of your board at:
  https://www.arduino.cc/en/Main/Products

  modified 8 May 2014
  by Scott Fitzgerald
  modified 2 Sep 2016
  by Arturo Guadalupi
  modified 8 Sep 2016
  by Colby Newman

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Blink
*/
#define LED_BUILTIN 12
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  delay(2000);
  Serial.println("HELLLLLLO");
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

Upload
Build options changed, rebuilding all
Sketch uses 251224 bytes (50%) of program storage space. Maximum is 499696 bytes.
Global variables use 28080 bytes (34%) of dynamic memory, leaving 53840 bytes for local variables. Maximum is 81920 bytes.
Erasing 0x80000 bytes starting at 0x00000000
Uploading 255376 bytes from /tmp/arduino_build_214375/Blink.ino.bin to flash at 0x00000000
................................................................................ [ 32% ]
................................................................................ [ 64% ]
................................................................................ [ 96% ]
..........                                                                       [ 100% ]

Addede1: Port Selection:

note: when taken port was not connected ( connects to USB0)
edit3: erasing using esptool.py:
guy@desktop:~$ esptool.py --port /dev/ttyUSB0 --chip esp8266 erase_flash
esptool.py v2.5.0
Serial port /dev/ttyUSB0
Connecting....
Chip is ESP8285
Features: WiFi, Embedded Flash
MAC: 60:01:94:ad:bf:34
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 2.4s
Hard resetting via RTS pin...

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

Your code is not good to detect if it  works.
The esp8266 Serial needs some time until it prints. First print after the Serial.begin() isn't printed. I guess the reason is the USB chip.
According to schematic, the LED in Sonoff Dual is on pin 12

changed to 12- still no reaction :(

add delay(2000) after Serial.begin ()

tried without any response. see code edit.


text:
Arduino clone woks only with USB - NOT with external power
I have an Arduino UNO ch430 clone. It works with USB power supply, I can upload a Sketch and it works just fine. With external power supply, doesn't work. What do I mean? No LED lights up, high pins output  ~ 0V. I'm using that barrel jack plug with 9V (6 x 1,5V batteries). Input voltage is measured OK. The AMS1117 regulator has Vin pin = Vout pin; i mean it gets no input Voltage. On the other hand, the M7F rectifier diode that comes between the jack and the regulator takes all voltage. I don't understan why, given that the anode is at higher voltage than the cathode (+9V). It shouldn't block current flow.
I tried jumping the rectifier and getting the jack +pin directly to the Vin at the regulator: current starts to flow, but apparently so much that the ams1117 heats a lot and really fast. Well i don't know why it suddendly gets so much current, I have absolutely nothing pluged to the board and I couldn't find any stain or damaged spot on it.
I can't figure out what is happening. I hope you can help me, and thanks in advance.

This is an exact (i'm pretty sure) schematic of my board.
Link

What kind of batteries? Good quality rechargeable batteries can supply enough current to blow a diode or even to melt wires.

It sounds like there's some form of short, or the AM1117 regulator is dead. Too much current being drawn by the regulator (as it gets so hot) has caused the diode to blow.
You will need to replace both the regulator and the diode and hope it works - or use a separate external regulator into the 5V pin instead.
Personally, I'd use a switch-mode regulator (UBEC regulators are cheap and easy to get hold of) since it is far more efficient than the LM1117.


text:
Reading values with HC-05 and sending commands at the same time working inconsistently
Not good at coding at all, so I'm at a total loss here.
But I'm doing a project that involves controlling a larger DC voltage through a mosfet.
What I'm doing is I'm using a HC-05 to transmit data between a phone and the Arduino Uno. Seeing the value within a couple of seconds is necessary.
However, sending the mosfet gate a command to open or close up work very inconsistently. Sometimes never and sometimes it takes up to 30 seconds for it to register.
The code here is a short version of the project that I'm working on, but behaves similarly.
#define mosfet 11
int state = 0;
int gate = 0;
int maxgate = 255;
int mingate = 0;

void setup() {
  delay(2000);
  pinMode(mosfet, gate);
  analogWrite(mosfet, 0);   //starts closed
  Serial.begin(9600);
}

void loop() {
  while(Serial.available() > 0){
    state = Serial.read();

    for (int y=0; y <= 5; y+=5){
      delay(500);
      Serial.println("testphase 1");
      delay(500);
    }

    for (int y=5; y >= 0; y--){
      delay(250);
      Serial.println("testphase 2");
      delay(250);
    }

    if (state == '0') {
    gate = gate + 1;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +1");
    state = 0;
    }

  if (state == '1') {
    gate = gate + 10;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +10");
    state = 0;
    }
}
}

When sending 'State == 1', for example it will go through both for loops multiple times and the maybe sometimes do gate + 10. Sometimes the commands goes completely ignored.
I have no idea how I would interrupt a loop to execute the given command and then go back.

Why do you have these for loops? If you want to do something timed but also be responsive to commands you can make your code non-blocking, like in the BlinkWithoutDelay example of the Arduino IDE.

The pinMode() seems incorrect (because of the variable gate bring where the pinmode constant should be). But that shouldn't be a problem, since analogWrite() configures the pin correctly.

How do you know, that it takes so long? Are you measuring the PWM signal, which goes to the MOSFET? You would need to send many times '0' or '1' to get to the maximum value

Those state changing IF-loops are just a few of the many I have in my code, but I cut out most to just test the code. Even adding a +1 or a +10 to the gate variable should show some signs of life on an LED I'm using to test the system, before I hook it up to a more powerful DC source.

Also, adding to my previous comment. How do I know it takes so long? It should print the current value + the added amount when a change is detected and the change should be easily observable with the green LED that I'm using for testing. Although I now see that it actually just prints the current value + the added amount.

Also, why for loops? Honestly it is just me lack of experience with coding stuff and something I thought I'd try out. I have a version that doesn't have the for loops now. Work quite similarly to be honest.. maybe a tab bit more responsive. How important would the placing of those 'if(state == x)' statements be?

Actually got it working myself, but thank you so much for your help @chrisl
Ditched the for loop completely just to try things out and reorganized my code a bit. Surprisingly it started to work well enough.
Basically just moved my measuring stuff outside the while loop*(and now that I think about it, why would it ever be withing the while loop? Literally makes no sense)* and to the end of the whole void loop part, and only polled for state changes within the while loop while the BT connection was active.
Doesn't miss a command as far as I can tell, and the adjustment is within 2 seconds when using my whole code, which is perfect. Also the whole program doesn't just freeze itself while trying to think what happened when the change set was send.
Here's a short version, should somebody bump into this thread in the future.
void loop() {
   while(Serial.available() > 0){
    state = Serial.read();

  if (state == '0') {stuff happens here,
    }
    }  //End of the while loop.

  sensors.requestTemperatures();
  delay(1000);
  Celcius=sensors.getTempCByIndex(0);
}


text:
Transient buttons control non-transient behaviour of LEDs
Imagine a system where you have two transient non-exclusive buttons and two LEDs.
When you press button 1, the LED 1 is HIGH and LED 2 is LOW (and stays that way).
When you press button 2, the LED 1 is LOW and LED 2 is HIGH (also stays that way).
Which C++ code allow me, to keep the LED 1 turned on indefinitely (until button 2 is pressed)?
Basically, my problem is, that the buttons are transient and the behaviour of LEDs shouldn't be.
Here is code, that would work for pernament exclusive buttons, but doenst work for transient non-exclusive buttons.
if (digitalRead(button1) == HIGH)
{
    led1 = HIGH;
}
else
{
    led2 = LOW;
}
if (digitalRead(button2) == HIGH)
{
    led2 = HIGH;
}
else
{
    led2 = LOW;
}

AIqbalRaj Choices are in the infinite space of all possible programs.

can you share the code that you tried and where did you get stuck?

I edited my original post.

Is the answer just: "remove else branches and add reset for other led to the same branches"?  And for that "attack" this isn't homework resolving facility. Without your code it was just too broad.

Something like this:
if (digitalRead(button1) == HIGH)
{
    led1 = HIGH;
    led2 = LOW;
}
if (digitalRead(button2) == HIGH)
{
    led2 = HIGH;
    led1 = LOW;
}

Hello Mike, thanks. It is correct answer for my question, but I failed to mention, this was just small piece of the program and in that case, I might be better off using interrupts. If I am correct, the loop has to do full cycle, before it reaches button1 again. Thanks, anyway

Don't react to the button by changing the LED; change a state-variable in memory, instead. That saves the information of which button was most recently pressed. Then, each time through your loop, set your LED's according to the contents of that persistent variable. Remember that it will have to be a static variable (global or static local), as an automatic one will disappear and reappear after each exit and re-entry to loop(), and you cannot count on its contents when that happens.
Update:

How do I prevent overwriting the state variable with different input ?

You don't prevent it - you must over-write it. The purpose of the state variable is to remember which button was last pressed. I had in mind something like the following, where lastButton saves the number of the most recent button:
void setup(){
   pinmode(LED1PIN, OUTPUT);
   pinmode(LED2PIN, OUTPUT);
   pinmode(BUTN1PIN, INPUT_PULLUP);  // you might not want the pullup
   pinmode(BUTN2PIN, INPUT_PULLUP);  //  depending on your wiring.
}

void loop(){
   static uint8_t lastButton = 0;

   // Save the number of the last button pressed.
   if (digitalRead(button1) == HIGH)
      lastButton = 1;
   else if (digitalRead(button2) == HIGH)
      lastButton = 2;

   // Set the LEDs according to most recent button
   // Note that at program-start, when no button has
   // been pressed yet, this code leaves both LED's off.
   if (lastButton == 1)
   {
      digitalWrite(LED1PIN, HIGH);
      digitalWrite(LED2PIN, LOW);
   }
   else if(lastButton == 2)
      digitalWrite(LED1PIN, LOW);
      digitalWrite(LED2PIN, HIGH);
   }
}

Thanks, but how do I prevent the corruption of the variable, by pressing another button ? Lets say, I make code in which, something is gonna happen after b1 (state-variable) is true. That is gonna send me into while loop, but when you as user press Button2, b1 gets reseted to false and the loop will be exited ?. How do I prevent overwriting the state variable with different input ?

I might make my question more intelligible and make another thread. I am not sure, if its clear enough.


text:
how to simplify code
I am as new as new can be to the Arduino world and have been playing around with them.  I have a few "Arduino Uno" boards that I purchased and have successfully loaded sketches to them.  However I am having problems figuring out how to write code in a simple manner.
I am  using a LED strip of WS2812 LEDs (similar to this). Here is what I would like to achieve:
I would like to be able to light  "lets say"  LEDs  1, 3, 5, 7.  Then light LEDs 2, 4, 6, 8  or any other combination of "multiple LEDs", by that I mean maybe LEDs 0, 14, 15, 36, 37, 52, 54.  I am sure you get the idea.
Can I write a single line code to light these LEDs or do I have to write out each line.
Sorry if this is a simplistic question, but I have searched and have not seen anything that may accomplish this, or I just over looked it.
Thanks in advance for your help

Oh I guess I should say they are strip led(s) ws2812

please post code

Please edit your question to add the important information that you're using WS2812. It's better to have all the info in the question rather than expecting that people will read the comments.

Most times you would set the states of the LEDs in a for loop, while checking the rule with which they should light up. Please state clearly the rule behind this

if you want to use a single command to light multiple LEDs, then you will have to write a function that accepts multiple parameters ..... each of the parameters would be the LED number to light

I have to say that I do not have any experience with the ws2812 led strip but basically it is used with the Adafruit_Neopixel library where you have the function pixel_obj.setPixelColor(pixel_number,pixel_obj.Color(R,G,B)
and the function pixel_obj.show().
Now you basically want to make the code in void loop() clean and there is a wide choice of possibilities and techniques to use. The simplest is not to do it, but if you want you can write a library to do it or write a function that takes the number of the pins and light 'em up (all with the same color), like this
void light_pixel(int pixels[],int Red,int Green,int Blue){
    for(int i=0;i<NUMPIXELS;++i){
        pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
    }
    pixel_obj.show();
}
This works assuming you have declared pixel_obj in the outermost scope, and you will call the function like this:
#include <Adafruit_NeoPixel.h>
#define PIN //Whatever you pin is
#define NUMPIXELS //Thenumber of the pixels in your strip
Adafruit_NeoPixel pixel_obj = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
// You may have to modify the third parameter Rationale: You didn't
// specified anything about your led strip
void setup(){
pixel_obj.begin();
pinMode(PIN, OUTPUT);
}
void light_pixel(int pixels[],int Red, int Green, int Blue){
for(int i=0;i<NUMPIXELS && pixels[I]!=-1 ;++i){
    pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
}
pixel_obj.show();
}
void loop(){
int my_pixels[NUMPIXELS]={1,3,5,7,-1}; // Using -1 as terminator
// Initialize the array . Disclaimer: this is not optimised and you might use
// new opearator or better pass the reference of a vector to the function so
// that you can modify the range of the vector and have a more concise function
light_pixel(my_pixels,255,255,255);
delay(1000);
light_pixel(my_pixels,0,0,0);
}

Then you can change the number of my_pixels with a smile array assignment
This function is just a sample to get the job done but I'd recommend you to study further the C/C++ programming language in general in order to write better code
Good Luck!

sizeof(pixels)/sizeof(*pixels) won't work here, as at this point pixels is a pointer, not an array.

@EdgarBonet This should work, I just set a fixed value for both the array sizes


text:
Random characters generated by LCD during serial.read()
I am using the following codes to print characters on LCD display....
#include <LiquidCrystal.h>

const int rs = 8, en = 9, d0 = 4, d1 = 5, d2 = 6, d3 = 7;
LiquidCrystal lcd(rs, en, d0, d1, d2, d3);

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    delay(100);
    lcd.clear();
    while (Serial.available() > 0) {
      lcd.write(Serial.read());
    }
  }
}

but in the end it is generating an unwanted character also..

kindly help me with the problem

I guess, it is the newline character. What line end is Serial Monitor set to send?

Does 'lcd.write("Hello");' work? You should check if the problem is on the serial or on the LCD.

yes it works perfectly

@Gyan_mishra in that case, it doesn't appear to be a problem on the display's side. Is the same character generated when you do: "lcd.write("\r\n");"? Or choose "No line ending" in the Arduino serial monitor.

thanks for help @Paul .... the problem was exactly the same...

The character to the right of the 'A' on your LCD display does not correspond to any of the built-in character bitmap definitions (either on a EU or Chinese display).  This random pattern is likely one of the 8 programmable character bitmaps supported by the LCD that has not been defined yet (ASCII codes 0 to 7).
So, you're likely sending the LCD a character with a value between 0 and 7.  It's probably a good idea to filter out invalid characters before attempting to display them on your LCD.
Filtering Example:
char c = Serial.read();
if ((c >= 32) && (c <= 128))
  lcd.write(c);

could you tell me, how to filter out invalid characters before attempting to display

I've updated the answer to illustrate a simple filtering example.  Take a look at an ASCII table to understand why the numbers I chose are significant.

thank you @jeff, for providing me such an excellent example of filtering.. it worked


text:
How millis() resets itself to 0
Looking at the documentation for the millis() function , it says:

Returns the number of milliseconds since the Arduino board began
  running the current program. This number will overflow (go back to
  zero), after approximately 50 days.

How's this possible? Is Arduino detecting when millis() overflow then resets the value to 0? If so, how does it do it? I just want to know what exactly is going on under the hood with the variable that is being returned by the millis() function.

It is not an exclusive property of millis(). Any counter with a limited number of digits eventually returns to zero. For example, a 4 digit tally counter returns to zeros after 9999.
Under the hood, the variable for millis() is of type unsigned long, which is 32 bits on the Arduino. In this case, the 32 bits (binary 0's and 1's) are similar to the digits (0 thru 9) on the tally counter.
The maximum is 11111111 11111111 11111111 11111111. Once there, millis() returns to zero when you add 1.  The maximum (32 "ones") is 2^32 - 1, which equals 4294967295 in the decimal number system. The maximum value for the counter is, therefore, 4,294,967,295 milliseconds.   Converted to days you get approximately 49.71 days.

Old versions of Windows also maintained a milliseconds count in a 32-bit integer, causing lots of software to misbehave after 49 days uptime.


text:
Library Compiler Error - ArduinoJson
I have installed via the Arduino Library Manager a library called ArduinoJson.  It seems to install fine and I have included the library in my sketch using:
#include "ArduinoJson.h"

But when I compile the sketch I get the following error:
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\mega" "-IG:\\My Drive\\Personal\\jdeation\\Arduino\\libraries\\HX711-0.1" "-IG:\\My Drive\\Personal\\jdeation\\Arduino\\libraries\\ArduinoJson\\src" "C:\\Users\\jason\\AppData\\Local\\Temp\\arduino_build_7871\\sketch\\counting_machine.ino.cpp" -o nul

In file included from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/JsonBufferBase.hpp:7:0,

                 from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/DynamicJsonBuffer.hpp:7,

                 from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:9,

                 from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                 from G:\My Drive\Personal\jdeation\Arduino\counting_machine\counting_machine.ino:32:

G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/Deserialization/JsonParser.hpp:7:29: fatal error: ../JsonBuffer.hpp: No such file or directory

compilation terminated.

I'm very new to Arduino programming,  can someone point me in the right direction.
Thanks.

delete it and try to install again

Go through the library manager and make sure your version is 5.14.3 and not higher. The higher ones are Beta versions and there has been changes that are not compatible with the previous non-Beta versions.
This is an annoyance because you would think that the latest would be the best. But that is not always the case.


text:
could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool'
I am trying to make some LED lights to turn on when i flick a switch on my RC crontroller. I will connect the signal wire from RC controller to pin 8. The plan is: if i flick the swich, the LED's (pin 12,11,10,9) will turn on, and if i don't flick the swich the LED's wont turn on. This is a Arduino nano what will be connected on a drone.I found another question HERE, but there was no real answers.
 I get a error that say:

exit status 1
  could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool'

How can i fix this? Should i write the code another way?
Arduino Code:
    void setup() {

  pinMode(4, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, INPUT);

}

void loop() {

  if (digitalWrite(8, HIGH));
    digitalWrite(12, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);
  else
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);

  digitalWrite(4,HIGH);
  delay(1500);
  digitalWrite(4,LOW);
}

why has this question upvotes?

Because it’s a clear, answerable question with an error message and (relatively) minimal reproduction @Juraj

upvote is for "usefull". and I agree with the text in bubble over the downvote button

You should be using digitalRead(8) instead of digitalWrite(8, HIGH). Your sketch is also missing some curly brackets.
void setup(){
  pinMode(4, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, INPUT);
}

void loop(){
  if(digitalRead(8) == HIGH){
    digitalWrite(12, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);
  }
  else{
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite(9, LOW);
  }
  digitalWrite(4,HIGH);
  delay(1500);
  digitalWrite(4,LOW);
}

The use of delay() will block the sketch from doing anything else, and should be replaced with a millis() timer. Have a look at the BlinkWithoutDelay example in the IDE.

Can't i just make another void loop() and have the blinking there? Then it won't interfere with the if statement.

You can only have 1 void loop(). There are several libraries available that are easier to use than writing your own code, such as https://www.avdweb.nl/arduino/timing/virtualdelay. This library lets you use a similar syntax as the delay() function, and is non blocking.

This line of code is the source of your problem.

void loop() {

  if (digitalWrite(8, HIGH));

If expressions expect a boolean (true/false), but if you check the documentation for digitalWrite(), you’ll see it returns “Nothing” (i.e. void).
You need to use digitalRead() to check the current state of the pin.


text:
Preforming impedance termination for UART Communication (TX and RX) pins
I need two Arduino devices (Arduino Mega and Nano) to communicate with each other via UART. The two Arduino devices are long distance apart from each other. The distance is 1.5 meters.

The Arduino 1 TX pin is connected to Arduino 2 RX pin.
The Arduino 1 RX pin is connected to Arduino 2 TX pin.

Now, I have to use resistor to preform impedance termination so that the long distance does not cause transmitting and receiving issues between the two devices. I did some research and found an  image that shows the signal differences when impedance termination is preformed and when it is not.

I have two questions:
1. Since the distance between both Arduino devices is 1.5 meters, what resistor value should I use? How is that calculated?
2. Where do you put the resistors? It's not really clear on where to connect the resistors. Between ground and the RX pins on each device?
I don't know the gauge ratings of my wire but if that information is needed, I am using this wire.

How it all works with line impedances is explained in this old education video: AT&T Archives: Similiarities of Wave Behavior

@KIIV Nice video. I wonder why those old education videos are more comprehensive than modern education videos in Universities.

The relevant parameter is not the length of the link, but its
characteristic impedance. For a twisted pair connection, this is
typically in the order of 100 to 120 Ω. It should be specified in
the datasheet. Your cable is not a twisted pair, but its geometry is
quite close. Just make sure that there is a ground or Vcc line between
the two data wires in order to minimize cross-talk. If you want to
compute that impedance yourself, here is an online
calculator.
Connect the resistor in series with the TX pin, i.e. between the pin and
the data wire. Note that the pin already has an internal output
resistance of about 25 Ω, so you would add no more than 100 Ω
in series.
If you search online about termination resistors, you may learn tat they
are often put between the receive pin and ground, or even at both the
sending and the receiving end. In high frequency applications, the
latter is often the preferred configuration, as it prevents the signal
to be reflected from either end of the link. However, for logic-level
signals, that configuration would attenuate the signal too much. On the
other hand, terminating only at the receiver would put excessive load on
the TX pin. Thus, sender-side termination is your best option. A
resistor in series with TX does not prevent a reflection at the RX end,
but it prevents the reflected signal to be reflected again and cause
oscillations.

Not sure what you mean as "resistor in series with the TX pin". You mean a resistor from TX pin(Arduino 1 ) to RX pin(Arduino 2). A little image with the drawing would be helpful...

A resistor in the tx to rx line between the two Arduino boards. At the tx terminal connect the resistor, the other side of the resistor connects to the wire.

@Programmer: You cannot put a resistor between TX1 and RX2, unless the resistor is 1.5 m long. You have to put it between TX1 and the wire that goes to RX2, as explained by Rudy. See amended answer.

@Rudy That's what I though. Was just making sure it's what Edgar meant.

@EdgarBonet Not what I meant. I know the resistor is not that long and meant adding it between the connection TX and RX. Your EDIT is clearer and it makes sense it adding the resistor to the sending side.


text:
Connecting Winsen ZE11-C2H4 Sensor to Arduino
How should I connect the ZE11 Ethylene Sensor to an Arduino Uno? I want to know how to attach the pins of the sensor to the Arduino and which resistor I should use. I'm very unprofessional at working with circuits so I most likely will need step-by-step help. To make things easier, I am attaching the datasheet associated with the sensor. The pin identification and technical parameters are on pages 3-4. Also if someone taught me how to do advanced coding for this project then that would be great. Please note that Winsen is a company based in China, so some things can be inaccurate because of translation. Any help is appreciated.

Why do you ask "what resistor to use?" To use for what? What makes you think you want a resistor for anything? Do you know what a resistor does? What it is used for?

Pin 5 & pin 6 are UART Bus. To use UART, connect pin 5 with TX pin on Arduino and pin 6 to RX pin on Arduino. Details about communication settings are at 4th page.
I can't find library for that sensor so guess you're on your own.
UART also Know as Serial communication.


text:
Getting at the PS_ON pin on a RAMPS1.4 mounted to a Mega
Got it! Check end of post for solution.
I'm running a Mega 2560 with a RAMPS 1.4 Shield which is usually used for 3D printing applications. For my use case I only want to get at the stepper motor drivers. The RAMPS is pulling its own 12V power supply (using an old xbox 360 brick rated for 12V and have tested with a multimeter) and the Arduino is pulling 5V from an RPI. But for some reason I seem unable to get the stepper motor A4988 drivers to pull anything from the 12V power supply. The LED on the RAMPS turns on, and the stepper drivers are pulling a little power (also tested) but obviously not enough to get them to make the motors turn. In other words, the RAMPS isn't using the external power supply.
I'm NOT using any of the 3D printer firmware like Marlin since it can't compile on Raspbian and I only want to get at the Stepper Motor Drivers and now in my case the PS_ON pin...
Here's the schematic:

My code for trying to get the motors to turn (and flip the PS_ON switch) is as follows:
int PS_ON = 12;
int X_STEP_PIN = 54;
int X_DIR_PIN = 55;
int X_ENABLE = 38;
int NUM_OF_STEPS = 400;
int WAIT_TIME = 500;
int LED_PIN = 13;

void setup(){

  digitalWrite(LED_PIN, HIGH);

  delay(2000);

  pinMode(PS_ON, OUTPUT);

  delay(20000);

  pinMode(X_DIR_PIN, OUTPUT);
  pinMode(X_STEP_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(X_ENABLE, OUTPUT);

  digitalWrite(PS_ON, LOW);
  digitalWrite(X_ENABLE, LOW);

  digitalWrite(X_DIR_PIN, HIGH);
  for(int n = 0; n < NUM_OF_STEPS; n++){
    digitalWrite(X_STEP_PIN, HIGH);
    digitalWrite(X_STEP_PIN, LOW);
    delay(WAIT_TIME);
    digitalWrite(LED_PIN,!digitalRead(LED_PIN));
  }

  delay(3000);

  digitalWrite(X_DIR_PIN, LOW);
  for(int n = 0; n < NUM_OF_STEPS; n++){
    digitalWrite(X_STEP_PIN, HIGH);
    digitalWrite(X_STEP_PIN, LOW);
    delay(WAIT_TIME);
    digitalWrite(LED_PIN, !digitalRead(LED_PIN));
  }
}

void loop(){

}

Any thoughts would be appreciated.
Here's how I got it to work.
Firstly if you're going to use a Xbox 360 PSU to power the RAMPS you need to tie together the red wire and the blue wire to force the box out of standby and make it give out a constant 12V (if you buy a 3rd party psu then the wire colors/layout will be different and you're on your own, but all the ones made by Microsoft for the base xbox 360 are color coded like this, including current Xbox One PSUs as far as I can tell).
There's also the option of connecting the blue to VCC and the red to GND on the RAMPS board (im not sure why that also works, but it's also mentioned in the docstring of the config.h or config_adv file under power supply settings in the Marlin firmware which is where I got the idea)
At that point, if you're reading 12V on a multimeter on the 5A rail of the RAMPS, make sure the RAMPS is able to power itself without the Arduino, if it can you should be good to go. There seems to be no need to get at the PS_ON at this point and you can power the RAMPS without any firmware.

Got it working without using any firmware, going to sleep. Will update post in the morning for how I got it working for anyone else with a similar question in the future.