text:
Blank project gives errors while uploading Arduino Leonardo on Linux Manjaro
I'm on Linux Manjaro. I plugged my Arduino Leonardo clone (that I know works correctly). And tried to flash a blank project on it:
(My IDE version is 1.8.12)
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

It gives me this error:
Sketch uses 3410 bytes (11%) of program storage space. Maximum is 28672 bytes.
Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2047)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: processing.app.SerialException: Error touching serial port '/dev/ttyACM1'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Permission denied.
    at jssc.SerialPort.openPort(SerialPort.java:170)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

The TL;DR of this overly verbose error message is “/dev/ttyACM1: Permission denied”.

Im currently reinstalling Arduino IDE (with my bad internet its gonna take a few minutes). So should I try to start Arduino IDE in sudo?

See https://arduino.stackexchange.com/search?q=Linux+permission+denied

Join the correct group(s). Give your user the correct permissions. Then reboot and try again.

this is a textbook example of what a question should look like ... minimal code, full error message printout ... a question asking how to determine the cause of the error, or asking what usually causes the error, or asking how to decode the error printout would complete the post .... i think that it deserves an upvote even though the question has been asked before

@jsotola lol thanks
I will post teh exact answer how to repair it for my distro tomorrow coz today I have no more time to play with arduino

https://www.arduino.cc/en/Guide/Linux#toc6

Okay I found a way to do this.
Open Terminal and type:
ls -l /dev/ttyACM*

you will get something like:
crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0
The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is dialout (is the group owner of the file).
Now we just need to add our user to the group:
sudo usermod -a -G dialout <username>

So for me that would be:
sudo usermod -a -G dialout john

BUT it seems to work with dialout on ubuntu/debian based distros. I am on Manjaro and instead of dialout I had to use uucp (and in general on Arch based distros) so:
sudo usermod -a -G uucp john

You will need to log out and log in again for this change to take effect.
This is the procedure to access the serial port from the Arduino Software (IDE) if you get an error
After this procedure, you should be able to proceed normally and upload the sketch to your board or use the Serial Monitor.
Although for me that wasn't over. After doing this the only error I got was Arduino IDe simply saying that it doesn't have permission to write to that port. So I had to start Arduino IDE by:
sudo arduino

in the terminal. After that everything works just fine.
I found help at those links:

https://www.arduino.cc/en/Guide/Linux#toc6
https://forum.manjaro.org/t/how-to-enable-putty-usb-serial-converter-access-without-sudo/82736


text:
How to prevent the garbage data when the serial port is initialised?
I use Arduino Uno. I get garbage in Serial Monitor or HyperTerminal right after I connect to the port. Here is an example code:
void setup() {
  // initialize serial:
  Serial.begin(57600);

}

void loop() {

    Serial.println("Test");
}

An example screenshot of the output. When port is re-connected the first received data is not Test:

So my problem is when the port is initialised the first data received is garbage. Is there a way to prevent this happening? Is that something to do with bootloader baud rate? I tried other baud rates and get same issue and I really want to use 57600 or 115200 baud rate.

I mean  during Serial.begin(57600); I get garbage values. How can I skip this?

@jsotola I re-articulated the problem. Please see the edit.

If I comment out I get nothing. By "When port is re-connected" means clicking "call" in HyperTerminal or openning Arduino serial monitor. First data is always garbage.

In HyperTerminal  there is Disconnect and Call buttons which closes and initiates the port. Similar to Arduino's serial monitor. I couldnt find a fix.

this may be an XY problem ... why are random characters a problem?

use a terminating or initializing char to trigger monitoring on the PC side; that way, any inadvertent signals get ignored.

Your use of the terminology in your edited post and comments is problematic because you are not being clear enough. For example:
"I mean during Serial.begin(57600); I get garbage values. How can I skip this? " and "If I comment out I get nothing".
"By "When port is re-connected" means clicking "call" in HyperTerminal or openning Arduino serial monitor. First data is always garbage". There are others."
"An example screenshot of the output. When port is re-connected the first received data is not Test:" - But, the first received data you are showing is, in fact, the word Test.
There are others.
I will try to help by answering your main question which seems to be "How to prevent the garbage data" and note that I have not included "when the serial port is initialized".
Firstly, when I use my Uno and V 1.8.13 of the IDE, and I compile and run your sample program, I get the usual output showing progress of the compilation and upload to the board, and that text ends with "avrdude done.  Thank you." At this point, the program is running and println is doing its thing.
When I open the serial monitor (by clicking on the box in the upper right corner of the full IDE screen - baud rate=57600, no line ending), I get corrupt characters at first. This always happens and I believe that is what you are seeing.
This happens because when you open the serial monitor, the UNO is being reset, but it is not the complete reset that is done when you upload code and begin execution. To be a bit simplistic, when you open the serial monitor, your program is running and the reset from opening the serial monitor is not the clean start that is done when you compile, upload and begin to execute the program.
Use either of these programs to test out what I am getting at.
void setup() {
  // initialize serial:
  Serial.begin(57600);
}

void loop() {
    delay(10000);
    while(1){
    Serial.println("Test");
    }
}

or
void setup() {
  // initialize serial:
  Serial.begin(57600);
  delay(10000);
}

void loop() {
  Serial.println("Test");
}

Go through your steps with either of these modified versions and open the serial monitor during the 10 second delay (unclick autoscroll to make it easier to see) and you will not get any corruption.
If, however, you compile/load/execute the program and then start opening and closing the serial monitor, you will start to see corruption in subsequent opens of the serial monitor - again because the reset when you open the serial monitor is not the clean reset that is done when you compile/load/execute.
Why doesn't everybody complain like crazy about the problem that you are experiencing? I think because folks learns to work with/around the way the UNO works. Your code just sends out serial data, so it is a prominent illustration of the issue, but it is not an insurmountable issue.
You can go deep into the serial monitor code and learn all about what is going on and come up with an elegant and likely tedious solution - I'm not sure, but I don't doubt that some have done this and it may even involve some hardware manipulation of serial control lines.
Alternatively, you can write the program to allow time to complete the serial monitor opening before you start sending out the data. You can even clean out any residual data (as long as you know what you are doing) if you anticipate multiple opening and closings.
Hope it helps.

source: Stack Exchange

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

sort: votes


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

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

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

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

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

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

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

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

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

Did you read the tutorial?

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

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

See the update edit

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

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

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

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

uint8_t (or unsigned char if you prefer)

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

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

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

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

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

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

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

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

Please see my update thanks

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


text:
how to check 24c32 eprom is connected or not to arduino runtime?
I want to check it on runtime if runitme i remove eprom then it shows "please insert dongle " also tried using while loop showing eroor.. How can i solve it?
Wire.beginTransmission(80);
      error = Wire.endTransmission();
    if (error == 0)
    {
    serial.print("connected");
    }
    else
    {
    serial.print("please insert dongle");
    }

also tried using while loop in loop()
void loop()
{
while (error == 0){
Serial.print("connected");
}

Serial.print("insert dongle");
}

Don't completely change the question and invalidate the existing answer. Also write properly. What is this: "usin ehilw llop"?

You should take parts of the I2C Scanner. You don't need to scan for all addresses - you can just scan for the one address you're interested in:
Wire.beginTransmission(80);
error = Wire.endTransmission();

if (error == 0)
{
  Serial.print("Connected");
} else {
  Serial.println("Insert dongle");
}

not working in runtime using also while loop? how to work as runtime?

Define "doesnt work"...

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


text:
LSM9DS1: Inconsistent data from an accelerometer
I'm currently getting inconsistent data from the accelerometer of my Adafruit LSM9DS1. To be more precise I either get a value close to the correct gravity (eg. 9.496515) or some reading like it was in space/free fall (eg. -0.023928225).
This seems to happen on all three the axes (I tried rotating the LSM9DS1).
I get the same behavior with FIFO enabled or not and with the Gyro enabled or not.
This is a set of 32 consecutive samples that I read from the FIFO memory:
result = {float[32][]@5092}
 0 = {float[3]@5100}
  0 = -0.41754755
  1 = 0.19501504
  2 = 9.519247
 1 = {float[3]@5112}
  0 = -0.421735
  1 = 0.19980069
  2 = 9.51805
 2 = {float[3]@5120}
  0 = -0.4229314
  1 = 0.20757735
  2 = 9.510274
 3 = {float[3]@5128}
  0 = -0.4127619
  1 = 0.2207379
  2 = 9.502497
 4 = {float[3]@5139}
  0 = -0.39302114
  1 = -0.06580262
  2 = -0.0017946169
 5 = {float[3]@5140}
  0 = -0.06939186
  1 = -0.045463633
  2 = -0.020937197
 6 = {float[3]@5141}
  0 = -0.05742774
  1 = -0.03469593
  2 = -0.0317049
 7 = {float[3]@5142}
  0 = -0.053838514
  1 = -0.039481573
  2 = -0.041874394
 8 = {float[3]@5143}
  0 = -0.054436717
  1 = -0.052642096
  2 = -0.043669015
 9 = {float[3]@5144}
  0 = -0.059820566
  1 = -0.068793654
  2 = -0.03469593
 10 = {float[3]@5145}
  0 = -0.06819545
  1 = 0.22731815
  2 = -0.019142581
 11 = {float[3]@5146}
  0 = -0.38644087
  1 = 0.2225325
  2 = -0.00418744
 12 = {float[3]@5147}
  0 = -0.40079778
  1 = 0.21535406
  2 = 9.505488
 13 = {float[3]@5148}
  0 = -0.40977085
  1 = 0.21355942
  2 = 9.525827
 14 = {float[3]@5149}
  0 = -0.40917268
  1 = 0.21296123
  2 = 9.540783
 15 = {float[3]@5150}
  0 = -0.40558344
  1 = 0.2207379
  2 = 9.5455675
 16 = {float[3]@5151}
  0 = -0.39960137
  1 = 0.22671993
  2 = 9.544371
 17 = {float[3]@5152}
  0 = -0.39302114
  1 = 0.22791636
  2 = 9.534203
 18 = {float[3]@5153}
  0 = -0.3906283
  1 = 0.21535406
  2 = 9.517452
 19 = {float[3]@5154}
  0 = -0.38584265
  1 = 0.19441684
  2 = 9.496515
 20 = {float[3]@5155}
  0 = -0.384048
  1 = 0.17347965
  2 = -0.023928225
 21 = {float[3]@5156}
  0 = -0.38883367
  1 = 0.15553348
  2 = -0.042472597
 22 = {float[3]@5157}
  0 = -0.39541394
  1 = -0.014356935
  2 = -0.05802595
 23 = {float[3]@5158}
  0 = -0.40259242
  1 = -0.026919257
  2 = -0.06580262
 24 = {float[3]@5159}
  0 = -0.40977085
  1 = -0.03589234
  2 = -0.071186475
 25 = {float[3]@5160}
  0 = -0.4151547
  1 = -0.040677987
  2 = -0.062213387
 26 = {float[3]@5161}
  0 = -0.421735
  1 = -0.03888337
  2 = -0.04965107
 27 = {float[3]@5162}
  0 = -0.42831525
  1 = -0.040677987
  2 = -0.032303106
 28 = {float[3]@5163}
  0 = -0.4372883
  1 = -0.04426722
  2 = -0.014356935
 29 = {float[3]@5164}
  0 = -0.445065
  1 = -0.04785645
  2 = 9.496515
 30 = {float[3]@5165}
  0 = -0.44865423
  1 = -0.04666004
  2 = 9.503693
 31 = {float[3]@5166}
  0 = -0.44865423
  1 = -0.04426722
  2 = 9.506086

As you can see 15 times the Z axis shows the correct value and 17 shows -0.
This is how I'm initializing the sensors:
        // soft reset & reboot accel/gyro
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG8, (byte) 0b00000101);
        // soft reset & reboot magnetometer
        writeRegByte(SensorType.MAG, REGISTER_CTRL_REG2_M, (byte) 0b00001100);

        SystemClock.sleep(10);

        byte idXg = readRegByte(SensorType.XG, REGISTER_WHO_AM_I_XG);
        byte idMag = readRegByte(SensorType.MAG, REGISTER_WHO_AM_I_M);
        if (idXg != XG_ID || idMag != MAG_ID) {
            throw new IllegalStateException("Could not find LSM9DS1, check wiring!");
        }

        setFifoMemoryEnabled(false);

        // enable gyro continuous
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG1_G, (byte) 0b11000000); // on XYZ

        // Enable the accelerometer continuous
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG5_XL,
                (byte) (CTRL_REG5_XL_ZEN_XL | CTRL_REG5_XL_YEN_XL | CTRL_REG5_XL_XEN_XL)); // enable X Y and Z axis
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG6_XL, (byte) 0b11000000); // 1 KHz out data rate, BW set by ODR, 408Hz anti-aliasing
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG7_XL, (byte) 0b10000000); // HR - High resolution mode

        // enable mag continuous
        writeRegByte(SensorType.MAG, REGISTER_CTRL_REG3_M, (byte) 0x00); // continuous mode

And this is how I'm reading the accelerometer data:
        byte[] buffer = new byte[6];
        int[] result = new int[3];
        readRegBuffer(SensorType.XG, REGISTER_OUT_X_L_XL, buffer, buffer.length);
        result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
        result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
        result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values
        return result;

I'm then converting the raw values with this formula (but this is a constant change so it should not matter):
rawAccelerometerData[i] * mAccelMgLsb / 1000f * mGravity;

I've also tried to disable the gyro and the magnetometer and left only the Z axis enabled and than tried to fetch the data using different output data rate but the result is the same.
The full code of my driver is available here.
I currently have only one LSM9DS1 so I have no clue if this is a defective product or an expected behavior and if this can be fixed with a different configuration.
PS

! as you might have guessed looking at the code I'm not really using an Arduino to access the LSM9DS1 but I still believe that this is still a good place to ask for help since I don't think my issue is platform related but is either some error in my code or a faulty sensor.
  And my code is just a port of this Arduino driver: https://github.com/adafruit/Adafruit_LSM9DS1.

This community will have no way to tell you if your hardware is defective, and since your code isn't for Arduino, it doesn't really fit in this group. The code sample you provided is nice, but can't be verified on Arduino.

I understand this but at least I can have a confirmation that this doesn't happen on Arduino, right? Can someone with a LSM9DS1 tell me if he/she get always consistent data from the accelerometer using this Arduino driver? https://github.com/adafruit/Adafruit_LSM9DS1

the comments in your code shows that you are enabling "everything" .  try enabling only one direction of the accelerometer  and disable the gyro .... also try reading the data at slower rate

Hi @jsotola, thanks for the hint, I tried to disable everything but the accelerometer and there I enabled only the Z axes. I tried with several values of output data rate, from the min to the max, with high resolution enable and disabled but the result is always the same. I've updated the OP including this new info and a link to the full source code of the driver.

The problem is how the accelerometer data is read, to be precise is in these lines:
result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values

What I'm getting from the sensor is a 16bit in two’s complement spitted in 2 bytes, for example buffer[4] and buffer[5] where 4 is the low byte and 5 is the high.
In Java the & and | are defined to operate only on int and long values, so what happens is that the byte is always promoted to signed int:
buffer[5] = 00111100
buffer[4] = 11110110
(int)buffer[4] = 11111111111111111111111111110110 = FF FF FF F6
(buffer[5] << 8) | buffer[4] = FF FF FF F6

With the original code both bytes are handled has two’s complement when actually only the high byte is holding the sign.
Long story short, you have to keep the sign for the high byte (cast to int) and threat the low as unsigned (autocast to int using the & and keeping only the original byte with 0xFF):
result[0] = (((int) buffer[1]) << 8) | (buffer[0] & 0xFF); // Store x-axis values
result[1] = (((int) buffer[3]) << 8) | (buffer[2] & 0xFF); // Store y-axis values
result[2] = (((int) buffer[5]) << 8) | (buffer[4] & 0xFF); // Store z-axis values

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


text:
Connecting multiple clients to a server in Wifi
What is the best method or retrieving information such as temperature from multiple wifi clients with a ESP8266-01 ?
I have one server and five client running with ESP8266.
I have seen post ang Get method. JSON files. client-server transfers.
What is the best method to do that ?
I am reading temperature so I do not need the clients to be all connected at the same time. So reading the client one after another in a loop would be great.
thanks in advance
Ken

This isn't really an Arduino question. A server can only query clients if the clients are maintaining connections to it, so often instead people just have the clients connect and post values.  Or you can keep the connection open and try to reconnect automatically if it breaks - this does sometimes give you the ability to ask, but also costs more server resources per client.  Also look at things like MQTT.

https://github.com/internetofhomethings/ESP8266-MQTT-HTTP-Server

Hi jsotola,  I am not seeing where in your link that multiple clients are called. I was thinking of adding an IP address to each clients and making a GET command to each IP to get the information.

@ken: that's the right track: an http server can be polled at any time, whereas a client must stay connected, which is not ideal. the other option is to have each sensor "phone home" on a schedule, so that the server doesn't need to maintain a client list/routine.

you do not need http for this. use plain socket communication. create a WiFiServer on every 'sensor' and ask from the main esp8266 over WiFiClient object. the WiFiServer creates a WiFiClient object and the Clients can exchange what you want.
snippet from my code:
void loop() {
  WiFiClient client = telnetServer.available();
  if (!client) {
    delay(100);
    return;
  }
  if (client.status() != 4) {
    client.stop();
    delay(1000);
    return;
  }
  while (client.connected()) {
    if (!client.available())
      continue;
    char c = client.read();
    if (c == '\n') {
      long v = s.toInt();
      s = "";
      analogWrite(PWM_PIN, v);
      v = readElSens();
      client.println(v);
    } else {
      s += c;
    }
  }
  delay(100);
}

Hi. I get what you are saying. But how do you go from one sensor to another sensor. All I see in your code and more on the internet ''while (client.connected()) {...''   but I need to identify the client as in client1.connected....client2.connected..  but arduino IDE does not allow me to do that.

code is for the esp with a sensor. in this case the client is the central esp and the servers are the sensor esps

I understand what you are saying concerning client-server. But I dont understand how I make the rotation from the multiple sensors. Each of my 5 sensors are on a ESP8266 chip. I should of mentionned that earlier.

and the WiFi network is created by a router or by the main esp?

add a server to the main esp too and let the sensor esps register to main esp over it

I am logging on to myprovider wifi. I have an arduino web server running wich i have access over the internet with dns and port forwarding.


text:
Can I use Arduino to generate a 0 to 15V analog output?
Is it possible to use the analog output pin with some circuit to generate a 0 to 15V analog output?

Yes, if you use an amplifier.

The Arduino cannot directly produce anything more than 5V.
You can use PWM and a Low-Pass Filter to produce an analog waveform between 0 and 5V, which you can then amplify using a suitable non-inverting buffer with 3x gain (op-amp), which will boost the voltage to 15V. Whether that is suitable for your needs, though, since the current will generally be quite low (most op-amps have a high output impedance) is unknown.
If you want a cleaner waveform you can attach or create a DAC which produces discrete output voltages (again between 0 and 5V) which you then amplify similarly.

simulate this circuit – Schematic created using CircuitLab
R3 and C1 form the low-pass filter and should be sized according to the frequency ranges you want to filter and keep. Note that many op-amps that can cope with the higher voltages you need aren't rail-to-rail which means you will have to use a higher power supply voltage than you want to output to leave some headroom. Similarly the 0V will be clipped and will never go below a certain voltage. If you want to get right down to 0V you will need a negative power supply to feed the V- supply of the op-amp (which is currently connected to ground in this schematic). That would allow the output to drop right down to 0V.

Thank you very much. Your explanation is really helpful. I don't need a high current output. What op-amp do you suggest me to use? What is the triangle at the bottom of the figure? Is that the ground?

Yes, that is ground. I suggest a parametric search on your favourite electronics supplier. You are looking for one that works at a high enough voltage and, if you don't want a negative supply, then one that works on a single supply rail.

The supplier in my region is quite hard to work with. Do you mind suggest a model no. for me? I think the minimum voltage output I need is 0.3V. Do I need a negative supply?

You could try the TL072, though I can't see in the datasheet how well it works with a single supply.

finally, I have tried the circuit, but I found that the voltage output is 5-17V.

I connect the arduino board to my macbook air without charging, the circuit ground is connected to the arduino ground pin. Any idea?

The Arduino does not have any "analog output pin". There are analog inputs, and you can generate a variable output with PWM pins.
Whether the latter meets your needs depends on your (unstated) requirements.


text:
Brushless motor + ESC with Arduino question
Sorry in advance as I'm still a rookie with Arduino projects. My goal is to use an Arduino Uno 3 to create an inexpensive drone/plane project.
Here are my materials and my set up:

A2212 1000kv Brushless Motor
HW30A Brushless Motor Speed Controller (ESC)
Arduino Uno R3
bunch of cables
9 V battery

Upon compiling the code I found here and connecting the 9 V battery to the ESC, all I hear is constant beep sounds from the motor (about once every 1.5 seconds). Can anyone help me figure out what's going on? Is it the 9 V battery that's not giving the motor enough juice? Or am I just too silly hoping to create something that works under $10?
#include <Servo.h>
Servo ESC1;

int pos = 0; //Sets position variable

void arm() {
  setSpeed(0); //Sets speed variable delay(1000);
}

void setSpeed(int speed){
  int angle = map(speed, 0, 100, 0, 180);
  //Sets servo positions to different speeds ESC1.write(angle);
}

void setup() {
  ESC1.attach(9); //Adds ESC to certain pin. arm();
}

void loop() {
  int speed; //Implements speed variable
  for(speed = 0; speed <= 70; speed += 5) {
    //Cycles speed up to 70% power for 1 second
    setSpeed(speed);
    //Creates variable for speed to be used in in for loop
    delay(1000);
  }
  delay(4000); //Stays on for 4 seconds
  for(speed = 70; speed > 0; speed -= 5) {
    // Cycles speed down to 0% power for 1 second
    setSpeed(speed); delay(1000);
  }
  setSpeed(0);
  //Sets speed variable to zero no matter what
  delay(1000);
  //Turns off for 1 second
}

I was able to find more instruction regarding this ESC, I'll continue to read on this while the post is up: https://www.bphobbies.com/pdf/bp/esc_2015/bp-hw30a-esc-2015.pdf

Like the previous answer stated, you should be using a 20-25c battery (can discharge up to 25A). I don't know exactly how much a 9V draws, but it definitely can't supply more than an AMP. Your motor pulls much more than 1 amp. Get yourself a nice LiPo from hobbyking.com, maybe an 8.4v or 11.1v
The ESC beeping could be telling you it can't draw enough Amps from the battery?

got it working with a better battery, thanks!

Probably a bit late but your code has some important parts commented out such as (in order):

delay(1000);
ESC1.write(angle);
arm();

Once you add those to the next lines the program should work and the esc shouldn't just beep and actually get the motor to spin

thanks anyway! we'll consider this if we use those motors again/

The beeping is actually from the ESC. I believe that this model needs to be properly configured (which you can do using the Arduino - refer to the user manual or here) before it can be used. Some kits come with it preconfigured but since you seem to have possibly purchased it individually you need to configure it yourself. Also it doesn't appear to be that your code wouldn't actually send any PWM signals to the ESC. I've only ever used Servo.write() functions in my quads, so I can't be 100% sure on that.

thank you. Correction, it's actually not a beeping sound, but a little twitch sound made by the motor (nothing from the ESC) I'll continue to read your link and learn more on this. Best regards!

That twitching is a possible error/idle warning in your ESC configuration. I know that my ESCs came programmed to start twitching like a mad dog if they were idle for 10 minutes, which kinda broke the idle warning/shutdown sequence I had designed for my camera-quad.

You need high current for working with this motor, 8.4 LiPo battery for example.


text:
WifiClient and aREST on esp32 - loop until new instructions recieved?
I've created a simple sketch for an esp32 that hosts a REST API that can be accessed via HTTP. Based on the instructions received from the client, the esp32 controls some neopixels with some various animations I've written.
Everything worked as expected until I got to an animation that runs in a while loop. The loop breaks when a new client is detected so that the light can switch functions. However, when the new client is detected, the client seems to be discarded or consumed, and i just end up back in the loop() function until I make a second HTTP request, then the changes to show up.
I'm sure it's something obvious, but what have I done wrong?
Code:
#include "WiFi.h"
#include "FastLED.h"
#include "aREST.h"
#include "ArduinoJson.h"

#define NUM_LEDS 64
#define DATA_PIN 18

CRGB leds[NUM_LEDS];
int LED_COUNT = 64;
int MAX_BRIGHTNESS = 200;

const char* ssid = "wifi";
const char* password = "password";
aREST rest = aREST();
WiFiServer server(80);
WiFiClient client;

void setup() {
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, LED_COUNT);
  flashAll(CRGB::Black);
  // Bind urls to the handling functions
  rest.function("random-strobe", randomStrobe);
  rest.function("solid-color", solidColor);
  rest.function("reset", reset);

  // Connect to WiFi and wait until we're connected to continue
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    flashAll(CRGB::Cyan);
    delay(500);
    flashAll(CRGB::Black);
    delay(500);
  }
  server.begin();
  flashAll(CRGB::Green);
  delay(2000);
  flashAll(CRGB::Black);
}

void loop() {
  if (checkForTask()) {
    rest.handle(client);
  }
}

boolean checkForTask() {
  // I have tried making this reassignment conditional
  // when the global 'client' is false, but it did not help
  //if (!client) { client = server.available(); }
  client = server.available();
  if (client) {
    return true;
  }
  return false;
}

int randomStrobe(String params){
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:application/json");
  client.println();
  client.stop();
  StaticJsonDocument<200> jsonDoc;
  Serial.println(params);
  Serial.println("params recieved. parsing...");
  auto error = deserializeJson(jsonDoc, params);
  if (!error) {
    // some setup stuff
    while(!checkForTask()){
      // do stuff in here
    }
    return 0;
  }
}

I have tried making this reassignment conditional how?

@JaromandaX Something like: if (client) {...} else { client = server.available();
if (client) {...} -- i couldn't find any good documentation on checking for a client without that reassignment part, but i'm sure there is a better way..

@Juraj I fail to see how this is different than what i have, really. could you elaborate?

Okay, I've managed to resolve the issue with some general direction from @juraj.
I now have TWO WifiClient instances:
WiFiClient client;
WiFiClient newClient;

This allows me to use the newClient instance to check for a new client:
boolean checkForTask() {
  newClient = server.available();
  if (newClient) {
    Serial.println("new client detected.");
    return true;
  }
  return false;
}

and only reassign the main client instance when a new client is actually detected:
void loop() {
  if (!newClient.connected()) {
    checkForTask();
  } else {
    client = newClient;
    runTask();
  }
}

This seems to work without any discernible side effects or additional resource usage, but if there is a more efficient way to accomplish this, please share. Thanks!

I show a simpler solution in my answer

server.available() doesn't return an already 'claimed' connection again. It returns a new connection or an empty WiFiClient object.
The esp8266 and esp32 Arduino core WiFi library close the underlying connection if the last referring WiFiClient instance is freed. The assignment of empty WiFiClient object frees the previous reference to underlying socket and if it was the last referrence, the library closes the socket.
You get a client with server.available() in checkForTask() and then you call server.available() again. It returns an empty WiFiClient object and you assign it to your WiFiClient object. The library closes the referred connection.
The solution is not to check server.available until WiFiClient is valid.
if (!client) {
  client = server.available();
}

Thank you for your help. How might I check for a new client to exit the loop, and then execute the client's instructions? What should me checkForTask() method look like? (I suspect the 'if' condition just needs to be revisited, though you should note that the client is declared globally, and should only be 'destroyed' by the reassignment, if i'm understanding correctly.) I have more experience with other languages, but my c++ is limited to arduino. sorry if i'm missing something obvious.

@shadowkrazee, I edited the answer. I don't understand why I didn't see the client is global. I solved all kind of similar traps with networking libraries in my project with Telnet server and WebServer on WiFi and Ethernet libraries https://github.com/jandrassy/Regulator/blob/8262f28b7452df0b75aa6c5a7bc676e14cd0cd26/Regulator/Telnet.ino#L23


text:
Connect SD card to Arduino with or without a level shifter
I have some audio files in an SD card and I want to play them using Arduino, thus connect the SD card to the Arduino. Since the transfer of the data will be from the SD card (+3.3V) to the Arduino (+5.0V) and not vice versa, is a level shifter necessary?

You can't use SD card without level conversion from 5 V to 3.3 V. Clock and CS line are driven by the master, and the master must request over MOSI the data to read.

.... your answer should be yes, to match the rest of your answer

i have a cheap generic chinese off-brand sd Card module and it does not even work if i do connect vcc to 3v3 so i use it with 5v. and i do not bother to add a Level shifter on the bus lines. and writing text to a file on the sd Card does work like a charm this way. so i would say no you not neccesarily Need the Level shifter but feel free to add it anyway and see if it works this way too.

this is funny, do you have many microSD cards?

less than a handfull -- and they are still working...

but there may be different variants of sd Card modules out in the wild...


text:
How to detect patterns in an FFT output?
I have an FFT output from a microphone and I want to detect a specific animal's howl from that (it howls in a characteristic frequency spectrum). Is there any way to implement a pattern recognition algorithm in Arduino to do that? Thanks!

We can help you with the programming language and hardware side of things. We can't help you with obscure algorithms. Maybe the maths or physics SE sites would be better for that.

Well that's a bummer. I guess I will close the topic then. Thanks!

Once you have an idea of what you want to choose we can help you code it.

You could apply a simple version of Machine Learning; measure, filter, normalize and last match (as distance to collected statistics).

It depends.
First you need to break the problem in steps:

If you can make a static analysis, than there is a chance. Meaning, if you can record a snapshot of the howl, and than spend some time processing it.
If you need to process it (almost) real time, than I am almost sure the Arduino is way too slow for that. In the next steps will be clear why, and otherwise you can use the next steps to get some idea how to do the analysis.
Assume you can do a snapshot of the sound, than you have to store it. The Arduino has only 2 KB of SRAM which is way too small. I assume you want a decent frequency (let's say 40 KHz) of mono (1 channel) samples, which is 40 KB of memory.
You need to record this (probably any sound sensor will be fast enough), and store it to some device, either external SRAM (fastest, most expensive), external EEPROM (somewhere in the middle) or SD card (might be slow). EEPROM/SD cannot be written 'forever' so if you want to process a sample every second, you might run in trouble.
Than you need to run your algorithm over the static data. I do not know this algorithm, if you have to iterate many times, forget about using SD, use SRAM or EEPROM.
Otherwise, read a few blocks (typically 2 or 3, to get 1 or 1.5 KB) and process it. I hope you can store the result also in the Arduino, otherwise write it (if you write much, probably SRAM is the only well feasible solution).

As you can see, you have to break your problem into smaller pieces, and check how the algorithm works (does it need a lot of data, or a snapshot), can it be processed in pieces, or does it need to iterate over the entire sample data a lot, are there intermediate results need to be stored etc.
Note there might be other solutions:

If you need more speed, try an Arduino Due
If you need more (internal) SRAM, try a Mega (8 KB) or Due (48 KB)

Thanks for the answer! As for the memory problems you pointed out, I think I may be able to get away with it because the spectrum I'm trying to analyse is completely below 1kHz, which means there is no need to have that high of a sampling frequency (I know harmonics can mess it up but I have some hardware filtering).

And I don't really need to do it realtime-ish.

still 1 KHz is 1024 bytes, the Arduino has 2048 free bytes, and you might need to store intermediate results.

Not realtime-ish makes it easier a lot.

I really only need 128 samples per cycle. The sampling frequency only affects the speed the arduino is running at.

Memory -> resolution.

In that case you might get good results. 128 samples is very good manageable. You might even be able to record new data while the previous data is being calculated (using two buffers, one for storing new data, one for processing).

If you think this answer is useful, upvote it please, and if the answer answers your question, accept it as answer.

Thanks for the help! I can't really accept it as an answer because I wanted to have some direction on what type of algarithms I can use

you're welcome (you can upvote by clicking the up arrow next to my answer), and below is a button to accept it. Good luck with your project.


text:
Any advice on how to repeat the song 6 times instead of infinitely?
//Here is my code so far
int speakerPin = 9;

int length = 28;

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo);

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   delay(tempo);

}

}

Assuming, the program can stop after playing 6 times, put another for loop in the loop function:
void loop()
{
   for (int nTimes = 0; nTimes < 6; nTimes++)
   {
      // Existing loop code
   }

   while(true) {};
}

A less crude way is to create a global variable:
int _timesPlayed = 0;

And change the for loop:
void loop()
{
   if (_timesPlayed < 6)
   {
      // Existing loop code

     _timesPlayed++;
   }
}

In most programming contexts, creating a global variable to represent a loop-counter would be considered very crude (rather than less crude), as it's unnecessarily hoisting the scope of the loop-counter from the for-block to not even just the method-scope, but the global-scope.  Is there a special reason that this might be a good thing in Arduino?

@Nat: The benefit of making items global is that it will show up in the summary of compiling so that it shows the amount of used SRAM. Also, some libraries use global defined variables (including those libraries is enough). And if a variable is global, you can access it anywhere (which is not so maintainable, but easy), but by passing parameters the stack is filled which also counts toward the amount of SRAM, although this should be ignorable (passing structs or buffers, not by pointer/reference is not a good idea anyway).


text:
Trouble trying to turn a stepper while a button is pressed down
So i'm currently coding a little device that rotates a step motor round one 8th of a full revolution every time a button is pushed. the motor is attached to a question reel with 8 questions on it, each one is viewable through a little window covering the reel after each button press. the thing im concerned about is that if even one of the question sections is slightly larger or smaller than the others, it will cause the question to become misaligned with the window after a certain number of run throughs.
in order to combat this I want to have a back up code that simply rotates the stepper while the button is held down. this will allow me to manually reset the reel to its proper positioning should the questions become misaligned. im not achieving this however, and was hoping someone may be able to detect where the issues are in my code?
#include <Stepper.h>

#define STEPS 2048

Stepper myStepper(STEPS, 8, 10, 9, 11);

const int  buttonPinBlue = 6;

void setup() {

  myStepper.setSpeed(5);
}

void stepp() {

 myStepper.step(1);

  pinMode(buttonPinBlue, INPUT);
}

void loop() {

 if (buttonPinBlue == HIGH) {

  Serial.print("pin is high");

   stepp();
  }

}

also just as a side note, the stepper runs fine using the 'define steps' value and the speed that I've set here, the issue appears to be that the button press is not being detected

You don't set the pin itself:
Change
if (buttonPinBlue == HIGH) {

to
if (digitalRead(buttonPinBlue) == HIGH) {

Also you don't have to set the pin every time, only one time is enough: in function setup should be the following line (and it can be removed from the function stepp:
pinMode(buttonPinBlue, INPUT);

Note that if you want to use a 'click' to move to the next item, you have to debounce the button; on the Arduino site check for button debouncing: https://www.arduino.cc/en/Tutorial/Debounce

Ahhh that's sorted it, should have known that really. Thanks for your help!

I also aligned your code slightly (next time select it and press ctrl-k), to make it better, remove the empty lines and align the code nicer.

You're welcome (if it is the correct solution, upvote and accept the answer). Welcome to Arduino Stack Exchange.

@KingDuken True, probably if he sees the motor is running he has a starting point how to proceed


text:
Variable that holds the users input doesn't empty itself, so the program only works once
This code seems to function, but only works once before I need to press the reset button. Otherwise, it repeats the same error message. It might have something to do with emptying the String variable.
// A program that will allow a user to turn ON one of several LED's
// using if...else statements.

String pinAsk="Please select which pin you would like to supply power to:";

// A different coloured LED will be attached to each pin number.
int Red=14; // This one would be the A0 Header on the Arduino
int Yellow=15; // A1
int Green=16; // A2
int Blue=17; // A3
int Purple=18; // A4
int Violet=19; // A5

int invalidColorRed;
int invalidColorYellow;
int invalidColorGreen;
int invalidColorBlue;
int invalidColorPurple;
int invalidColorViolet;
// If the user didn't select any of these colours, then all these variables will
// be given a 1. This triggers an if...else condition that prints out a message,
// to say that they didn't enter a valid input.

String inputColor;
 // The String variable can store integers as well as other characters

String activePin1="The ";
// The users input is printed out between these.
String activePin2=" LED is now active";

int Volts=102; // The 102 tells the Arduino to output 2+ (Two volts)

void setup() {
 Serial.begin(9600);
 Serial.println("Colour Selection");
 Serial.println("");

 pinMode(Red,OUTPUT);
 pinMode(Yellow,OUTPUT);
 pinMode(Green,OUTPUT);
 pinMode(Blue,OUTPUT);
 pinMode(Purple,OUTPUT);
 pinMode(Violet,OUTPUT);
}

void loop() {
 Serial.println(pinAsk);
 Serial.println("Red = A0 (14)");
// These describe the available pins and their colors.
 Serial.println("Yellow = A1 (15)");
 Serial.println("Green = A2 (16)");
 Serial.println("Blue = A3 (17)");
 Serial.println("Purple = A4 (18)");
 Serial.println("Violet = A5 (19)");

  while (Serial.available()==0) { } // Wait for user to respond

 inputColor=Serial.readString(); // Store their input into an empty variable

// The following segment checks whether the user has selected to turn ON
// the Red LED.

 if (inputColor=="14") analogWrite(Red,Volts);
 // The String variable can also store integers as well as other characters
 else if (inputColor=="A0") { analogWrite(Red,Volts); }
 else if (inputColor=="Red") { analogWrite(Red,Volts); }
 else if (inputColor=="red") { analogWrite(Red,Volts); }
// User may only use lower-case letters.
  // The "equal equal" sign == doesn't assign a new value.
  // It will test whether a number or string is the same
// as described at the end of the equal's sign.

 else { analogWrite(Red,LOW); }
// If the users input, stored within inputColor, isn’t "14", "A0", "Red",
// or "red" then this Red LED will be turned off.

 if (inputColor!="14" && inputColor!="A0" && inputColor!="Red" && inputColor!="red") { invalidColorRed=1; }

// The exclamation mark or bang ! is a NOT operator.
// A "bang equal" sign != is placed after a variable, such as inputPin!=
// to say that the value must NOT be equal to "14". If the expression is true
// (The condition is fulfilled), then a 1 is given to invalidColorRed.

// The AND operator, shown as a double ampersand && combines
// all the conditions into the same expression. By putting this operator `
// between them, it tells the Arduino that all the variables must NOT be
// any of the values described.

// Each colour has its own invalidColor variable.
// If the user does not enter any of the valid inputs
// (Which means the LED is off), a 1 will be assigned to this colors
// invalidColor variable.

// If all these invalidColor variables have a value of 1, it means all
// the LED’s are off. This can be made into another condition that causes
// the Arduino to read an expression that tells the user that they haven’t
// entered a proper input and to try again.

// Checking to see if the user has opted to turn on the Yellow LED.
 if (inputColor=="15") analogWrite(Yellow,Volts);
 else if (inputColor=="A1" || "Yellow" || "yellow") { analogWrite(Yellow,Volts); }
// The OR || operator combines the Lower-case and Upper-case letters in
// the same expression. A space between the operator and variables is not
// necessary, but improves readability. Also, a single pair of quotation
// marks "" can encase the conditions if || is being used.
 else { analogWrite(Yellow,LOW); }

 if (inputColor!="15" && inputColor!="A1" && inputColor!="Yellow" && inputColor!="yellow") { invalidColorYellow=1; }

// Checking to see if the user has opted to turn on the Green LED.
 if (inputColor=="16") analogWrite(Green,Volts);
 else if (inputColor=="A2") { analogWrite(Green,Volts); }
 else if (inputColor=="Green") { analogWrite(Green,Volts); }
 else if (inputColor=="green") { analogWrite(Green,Volts); }
 else { analogWrite(Green,LOW); }

 if (inputColor!="16" && inputColor!="A2" && inputColor!="Green" && inputColor!="green") { invalidColorGreen=1; }

// Checking to see if the user has opted to turn on the Blue LED.
 if (inputColor=="17") analogWrite(Blue,Volts);
 else if (inputColor=="A3") { analogWrite(Blue,Volts); }
 else if (inputColor=="Blue") { analogWrite(Blue,Volts); }
 else if (inputColor=="blue") { analogWrite(Blue,Volts); }
 else { analogWrite(Blue,LOW); }

 if (inputColor!="17" && inputColor!="A2" && inputColor!="Blue" && inputColor!="blue") { invalidColorBlue=1; }

// Checking to see if the user has opted to turn on the Purple LED.
 if (inputColor=="18") analogWrite(Purple,Volts);
 else if (inputColor=="A4") { analogWrite(Purple,Volts); }
 else if (inputColor=="Purple") { analogWrite(Purple,Volts); }
 else if (inputColor=="purple") { analogWrite(Purple,Volts); }
 else { analogWrite(Purple,LOW); }

 if (inputColor!="18" && inputColor!="A4" && inputColor!="Purple" && inputColor!="purple") { invalidColorPurple=1; }

// Checking to see if the user has opted to turn on the Violet LED.
 if (inputColor=="19") analogWrite(Violet,Volts);
 else if (inputColor=="A5") { analogWrite(Violet,Volts); }
 else if (inputColor=="Violet") { analogWrite(Violet,Volts); }
 else if (inputColor=="violet") { analogWrite(Violet,Volts); }
 else { analogWrite(Violet,LOW); }

 if (inputColor!="19" && inputColor!="A5" && inputColor!="Violet" && inputColor!="violet") { invalidColorViolet=1; }

 if (invalidColorRed==1 && invalidColorYellow==1 && invalidColorGreen==1 && invalidColorBlue==1 && invalidColorViolet==1)
 {
  // This if statement is asking "Are all invalidPin variables equal to 1?"
  // In other words, "Are all the LED's off?"
  Serial.println("");
  Serial.println("That is not a valid option, please try again");
  Serial.println(""); }
  else if (invalidColorRed==0 || invalidColorYellow==0 || invalidColorGreen==0 || invalidColorBlue==0 || invalidColorViolet==0)
  {
  // If the user entered a valid input for at least one LED,
  // this message will play instead.
  Serial.println("");
  Serial.print(activePin1);
  Serial.print(inputColor); // The users input is printed out here.
  Serial.println(activePin2);
  Serial.println(""); }

  inputColor=""; // Shouldn't this empty the variable?
}

Can someone tell me whats wrong?

Could you post the output you get from the console?

If a valid answer is entered, such as blue, it will print out 'The blue LED is is now active'. After that, it will repeat the first message, asking the user to select a color from the list presented. Even if the user gives an acceptable answer, it will read out the error message 'That is not a valid option, please try again'. The reset button needs to be pressed before the user can enter another color.

You set the invalidColor___ to 1, but you never reset it. So if you set the blue color, all variables invalidColor___ except for invalidColorBlue are set to 1. Then if in the next loop you set the red color, invalidColorBlueis also set to1, and now all invalidColor___s are set to 1and you get the error message. You need to set them back to0` at the beginning of the loop.

Without looking deeply into your code, this is wrong:
if (inputColor=="A1" || "Yellow" || "yellow")

You need to repeat what you are testing against, ie.
if (inputColor=="A1" || inputColor=="Yellow" || inputColor=="yellow")

You might want to use the auto-format tool (Ctrl+T). Putting a lot of stuff in one line is just confusing.


text:
Problem while connecting two arduino with NRF24L01
I am a beginner in Arduino programming so that program is also little bit lengthy sorry for inconvenience.
I have make a program for wire less controlling of a servo motor and LED(7 Nos.) using ARDUINO UNO, Funduino Joy stick shield V1.A and NRF24L01.First i have prepare the program (using Array) only for controlling the LEDs and its become success as that LEDs working as per program.Than i added Servo motor also in circuit and make some  changes in existing LED program. Unfortunately the result is erratic out put.joy stick input signal interrupting the led signal and some time servo motor respond led input .Transmitting code and Reciever code  given below.
I came to know that this problem will solve using "struct" command in existing program . Please help me to modify the program with "struct".Because i have no thorough knowledge in C,C++
TRANSMITTER
    #include <SPI.h>
    #include <RF24.h>
    #include <nRF24L01.h

>

#define xAxis A0
RF24 radio(9,10);
const uint64_t pipe = 0xF0F0F0F0D2L;

int msg[1];
int buttonPin1 = 2;
int buttonPin2 = 3;
int buttonPin3 = 4;
int buttonPin4 = 5;
int buttonPin5 = 6;
int buttonPin6 = 7;
int buttonPin7 = 8;
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
int buttonState6 = 0;
int buttonState7 = 0;

void setup(void)
{
  radio.begin();
  radio.openWritingPipe(pipe);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  pinMode(buttonPin5, INPUT_PULLUP);
  pinMode(buttonPin6, INPUT_PULLUP);
  pinMode(buttonPin7, INPUT_PULLUP);
}

void loop(void)
{
  int potValue = analogRead(A0);                              //  INPUT FOR SERVO MOTOR
  int angleValue = map(potValue, 0, 1023, 0, 180); // INPUT FOR SERVO MOTOR
  radio.write(&angleValue, sizeof(angleValue));         // INPUT FOR SERVO MOTOR

  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);
  buttonState5 = digitalRead(buttonPin5);
  buttonState6 = digitalRead(buttonPin6);
  buttonState7 = digitalRead(buttonPin7);

 if (buttonState1 == LOW){
    msg[0] = 111;
    radio.write(msg, 1);               // INPUT FOR LED1
   }
 if (buttonState2 == LOW){
    msg[0] = 222;
    radio.write(msg, 1);               // INPUT FOR LED2
   }
 if (buttonState3 == LOW){
    msg[0] = 212;
    radio.write(msg, 1);               // INPUT FOR LED3
   }
 if (buttonState4 == LOW){
    msg[0] = 216;
    radio.write(msg, 1);                 // INPUT FOR LED4
   }
 if (buttonState5 == LOW){
    msg[0] = 218;
    radio.write(msg, 1);                // INPUT FOR LED5
   }
 if (buttonState6 == LOW){
    msg[0] = 220;
    radio.write(msg, 1);                 // INPUT FOR LED6
   }
    if (buttonState7 == LOW){
    msg[0] = 224;
    radio.write(msg, 1);
   }                                              // INPUT FOR LED7

  }

RECIEVER
 #include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>  // SERVO LIBRARY INCLUDED

Servo myServo;
RF24 radio(9,10);
const uint64_t pipe = 0xF0F0F0F0D2L;

int led1 = 2;
int led2 = A2;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 7;
int led7 = 8;
int msg[1];
int angleValue ;

void setup(void)
{
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, pipe);
  radio.startListening();
  myServo.attach(3);                  // SERVO CONNECTED TO PIN 3
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
}
void loop(void)
{
   // Receiving code for LED 1 TO LED 7

  if(radio.available()){
    bool done = false;
    while (!done) {
    done = radio.read(msg, 1);
    Serial.println(msg[0]);

    if (msg[0] == 111) {
      digitalWrite(led1, HIGH);
      digitalWrite(led7, LOW);
      }
    if(msg[0] == 222){
        digitalWrite(led1, LOW);
        digitalWrite(led2, HIGH);
        digitalWrite(led7, LOW);
        }
     else if (msg[0] == 111){
          digitalWrite(led2, LOW);
        }
     else if(msg[0] == 212){

          digitalWrite(led3, HIGH);
        }
    else if(msg[0] == 216){
          digitalWrite(led4, HIGH);
        }
    else if(msg[0] == 218){
          digitalWrite(led5, HIGH);
        }
    else if(msg[0] == 220){
          digitalWrite(led6, HIGH);
        }
    else if(msg[0] == 224){
          digitalWrite(led7, HIGH);
          digitalWrite(led1, LOW);
          digitalWrite(led2, LOW);
        delay(10);
        }
      }
   }

//Recieving code for servo motor

    if(radio.available()){
      bool done = false;
      while (!done) {
      done = radio.read(&angleValue,sizeof (angleValue) );
      myServo.write(angleValue);}
      delay(10);
     }
                  //Receiving code for LEDs
      else {
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
      digitalWrite(led6, LOW);

      }
 }

I have tried to make a program using "struct" for 6 button state and one angle input signal  to control using 6 LEDs and one Servo and its working fine(Program mentioned below.)
But problem is that when i add two more input signal that time output become erratic and output is not getting as per program.Please help to modify the program.
transmitter
#include <SPI.h>
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int upbut = 2;
int rightbut = 3;
int downbut = 4;
int leftbut = 5;
int nuetral = 6;
int starte = 7;
int stope = 8;
struct data {
    uint8_t leds;
    uint8_t angle;
};
struct data packet;
void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(pipe);
  pinMode(upbut,INPUT_PULLUP);
  digitalWrite(upbut,LOW);
  pinMode(rightbut,INPUT_PULLUP);
  digitalWrite(rightbut,LOW);
   pinMode(downbut,INPUT_PULLUP);
  digitalWrite(downbut,LOW);
  pinMode(leftbut,INPUT_PULLUP);
  digitalWrite(leftbut,LOW);
  pinMode(nuetral,INPUT_PULLUP);
  digitalWrite(nuetral,LOW);
  pinMode(starte,INPUT_PULLUP);
  digitalWrite(starte,LOW);
  pinMode(stope,INPUT_PULLUP);
  digitalWrite(stope,LOW);
  //end pinMode and digitalWrite
}//--(end setup )---
void loop(){
int potValue = analogRead(A0);
packet.angle = map(potValue, 0, 1023, 0, 180);

packet.leds = 0;
packet.leds = digitalRead(upbut) ? 0x00 : 0x01;
packet.leds |= digitalRead(rightbut) ? 0x00 : 0x02;
packet.leds |= digitalRead(downbut) ? 0x00 : 0x04;
packet.leds |= digitalRead(leftbut) ? 0x00 : 0x08;
packet.leds |= digitalRead(nuetral) ? 0x00 : 0x10;
packet.leds |= digitalRead(starte) ? 0x00 : 0x20;
/*packet.leds |= digitalRead(starte) ? 0x00 : 0x30;*/

radio.write((uint8_t *)&packet, sizeof(struct data));
}

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

#include <Servo.h>
#define CE_PIN 6
#define CSN_PIN 7
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
const int servo1 = 9;
int servoVal;
Servo myservo1;
struct data {
    uint8_t leds;
    uint8_t angle;
};
struct data packet;
int led1 = 2; // digital out put
int led2 = 3; // digital out put
int led3 = 4; // digital out put
int led4 = 5; // digital out put
int led5 = 8; // digital out put
int led6 = A0; // digital out put
int led7 = A1; // digital out put
void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  myservo1.attach(servo1); // attaches the servo1 /analog output

  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  Serial.println("Nrf24L01 Receiver Starting");
  radio.begin();
  radio.openReadingPipe(1,pipe);
  radio.startListening();;
}                             //--(end setup )---

void loop(){

if (radio.available()) {
    radio.read((uint8_t *)&packet, sizeof(struct data));
    myservo1.write(packet.angle);
   if (packet.leds ==0x01){
    digitalWrite(led1, packet.leds & 0x01);
    digitalWrite(led2, packet.leds & 0x00);
    digitalWrite(led6, packet.leds & 0x00);
    }
   else if (packet.leds ==0x02){
    digitalWrite(led2, packet.leds & 0x02);
    digitalWrite(led1, packet.leds & 0x00);
    digitalWrite(led6, packet.leds & 0x00);
    }
    else if (packet.leds ==0x20){
    digitalWrite(led6, packet.leds & 0x20);
    digitalWrite(led1, packet.leds & 0x00);
    digitalWrite(led2, packet.leds & 0x00);
    }
    digitalWrite(led3, packet.leds & 0x04);
    digitalWrite(led4, packet.leds & 0x08);
    digitalWrite(led5, packet.leds & 0x10);

   /*digitalWrite(led7, packet.leds & 0x30);*/
}
}

You are sending two bytes, which each carry different information (LED and servo values), but you don't have any method to tell them apart. Think about what happens, when one byte is lost on the transmission. Everything will get out of step. Maybe you should only send complete messages with a delimiter, that marks the end of a package. Inside this package you can use the byte positions. Also maybe you need some kind of error detection/correction.

No need for delimiters with the nRF systems - they send discrete packets.

Your whole method is completely wrong.
Instead of sending bytes with some unknown meaning at random times you need a far more structured approach to sending your data.
You need to either:

Send the meaning of the byte(s) along with the byte(s), or
Send all the information every time at pre-defined periods.

Of the two options I'd favour the latter, using a struct:
struct data {
    uint8_t leds;
    uint8_t angle;
};

And then:
struct data packet;

int potValue = analogRead(A0);
packet.angle = map(potValue, 0, 1023, 0, 180);

packet.leds = 0;
packet.led |= digitalRead(buttonPin1) ? 0x00 : 0x01;
packet.led |= digitalRead(buttonPin2) ? 0x00 : 0x02;
packet.led |= digitalRead(buttonPin3) ? 0x00 : 0x04;
packet.led |= digitalRead(buttonPin4) ? 0x00 : 0x08;
packet.led |= digitalRead(buttonPin5) ? 0x00 : 0x10;
packet.led |= digitalRead(buttonPin6) ? 0x00 : 0x20;

radio.write((uint8_t *)&packet, sizeof(struct data));

Then when reading you do the exact opposite:
struct data packet;

if (radio.available()) {
    radio.read((uint8_t *)&packet, sizeof(struct data));
    myServo.write(packet.angle);
    digitalWrite(led1, packet.leds & 0x01);
    digitalWrite(led2, packet.leds & 0x02);
    digitalWrite(led3, packet.leds & 0x04);
    digitalWrite(led4, packet.leds & 0x08);
    digitalWrite(led5, packet.leds & 0x10);
    digitalWrite(led6, packet.leds & 0x20);
}

The struct combines a number of variables together into one single block of data giving you easy access by name to the different portions.  One, the leds variable, is then used as a bitmap of whether each LED is on (1) or off (0). That way you can send the current state of up to 8 LEDs in just a single byte.  If you want to expand that to send different combinations of LEDs then just change which bits of the byte are set.
If you want to "toggle" the LEDs then it will be necessary to keep a record at the sender of the states and send that instead of the raw button data.

Up to 6 leds and one angle input this working fine.But i have add one led and angle input more that time output become erratic.#include


text:
Robot beeping when power set to 0
I am working on an Arduino Uno robot project for college, I have modified my robot to beep and light up when he bumps into a wall or reverses, my robot works fine except for one very annoying problem, when my robots power is switched to 0 to turn him off he starts to beep as though he is bumping and I have no idea why!
My code:
#include <Servo.h>                           // Include servo library

Servo servoLeft;                             // Declare left and right servos
Servo servoRight;

byte wLeftOld;                               // Previous loop whisker values
byte wRightOld;
byte counter;                                // For counting alternate corners

void setup()                                 // Built-in initialization block
{
  pinMode(7, INPUT);                         // Set right whisker pin to input
  pinMode(5, INPUT);                         // Set left whisker pin to input
  pinMode(8, OUTPUT);                        // Left LED indicator -> output
  pinMode(2, OUTPUT);                        // Right LED indicator -> output

  tone(4, 3000, 1000);                       // Play tone for 1 second
  delay(1000);                               // Delay to finish tone

  servoLeft.attach(13);                      // Attach left signal to pin 13
  servoRight.attach(12);                     // Attach right signal to pin 12

  wLeftOld = 0;                              // Init. previous whisker states
  wRightOld = 1;
  counter = 0;                               // Initialize counter to 0
}

void loop()                                  // Main loop auto-repeats
{

  // Corner Escape

  byte wLeft = digitalRead(5);               // Copy right result to wLeft
  byte wRight = digitalRead(7);              // Copy left result to wRight

  if(wLeft != wRight)                        // One whisker pressed? (Output on the left is not the same as the right)
  {                                          // Alternate from last time?
  tone(4, 3000, 1000);                       // Beep for 1 second as we hit the wall (BK)
    if ((wLeft != wLeftOld) && (wRight != wRightOld))
    {
      counter++;                             // Increase count by one
      wLeftOld = wLeft;                      // Record current for next rep
      wRightOld = wRight;
      if(counter == 4)                       // Stuck in a corner?
      {
        wLeft = 0;                           // Set up for U-turn
        wRight = 0;
        counter = 0;                         // Clear alternate corner count
      }
    }
    else                                     // Not alternate from last time
    {
      counter = 0;                           // Clear alternate corner count
    }
  }

  // Whisker Navigation
  if((wLeft == 0) && (wRight == 0))          // If both whiskers contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnLeft(800);                           // Turn left about 120 degrees
  }
  else if(wLeft == 0)                        // If only left whisker contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnRight(400);                          // Turn right about 60 degrees
  }
  else if(wRight == 0)                       // If only right whisker contact
  {
    bump();                                  // Call bump function
    backward(1000);                          // Back up 1 second
    reverseBeep();                           // Call reverseBeep function
    turnLeft(400);                           // Turn left about 60 degrees
  }
  else                                       // Otherwise, no whisker contact
  {
    forward(20);                             // Forward 1/50 of a second
  }
}

void forward(int time)                       // Forward function
{
  servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
  servoRight.writeMicroseconds(1300);        // Right wheel clockwise
  delay(time);                               // Maneuver for time ms
}

void turnLeft(int time)                      // Left turn function
{
  servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
  servoRight.writeMicroseconds(1300);        // Right wheel clockwise
  delay(time);                               // Maneuver for time ms
}

void turnRight(int time)                     // Right turn function
{
  servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
  servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
  delay(time);                               // Maneuver for time ms
}

void backward(int time)                      // Backward function
{
  servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
  servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
  delay(time);                               // Maneuver for time ms
}

void bump()                                  // Light and sound code for when the robot bumps a wall (BK)
{

  tone(4, 3000, 1000);                       // Play tone for 1 second
  digitalWrite(8, HIGH);                     // Left LED on
  digitalWrite(8, LOW);                      // Left LED off

}

void reverseBeep()                           // Light and sound code for when the robot reverses(BK)
{

      for (int i = 0; i < 3; i++)
      {

        digitalWrite(8, HIGH); // Left LED on
        tone(4, 1600, 400);                     // Beep (Pin 4, 1600Khz tone for 400ms) (BK)
        digitalWrite(8, LOW); // Left LED off

      }

}

I am using this breadboard setup
http://learn.parallax.com/tutorials/robot/shield-bot/robotics-board-education-shield-arduino/chapter-5-tactile-navigation-6
The custom functions bump() and reverseBeep()are my custom functions to control the bumping and reversing beep and LED light up.
Does anyone know why he beeps when the power switch is set to 0?

Can you share your schematic too?

Probably electrical schema would be useful too. Servos and motors need high current to move decently fast, while Arduino does not need so much for "just live". If you have there large capacitors, or if the robot is moving when powered off and so turns motors to dynamos temporaly, then it is possible, that even with switch OFF the Arduino have enought power to live for a moment and at the same time the whiskers go donw as if pressed, so it works like it bumped.

I have edited my question now to include the relevant breadboard diagram.

Please avoid linking to your code on pastebin as the current configuration will remove your code in less than one month, making your question and any answers just plain useless at that time. Rather copy your code here in your question.

Code is very large, over 100 lines.

100 lines is nothing. 10,000,000 is very large.

I see no power switch on that diagram. We need your actual setup, not someone else's sketch that is vaguely similar in a few ways. How exactly do you "set the power switch to 0"?

I am following the tutorial, that is the tutorial, that is what I am told to do, the Arduino Uno board has a power switch directly built in http://learn.parallax.com/tutorials/robot/shield-bot/robotics-board-education-shield-arduino/chapter-3-assemble-and-test-12

Do you have the Arduino wired over USB? You can try logging the whisker statusses and if your bot wants to go left/right. Though your code seems sane and I think it's something electrically.

It does the same thing if wired or on USB, I probably should have tested another robot, it isn't a big deal it is just a little annoying.

bill it as a feature, not a bug.

By beeping I assume you mean a 1 second been with no flash from the LED.
The only place in you code that can happen is when the whiskers are not equal.  I think the whiskers are powered by the shield you have turned off, in which case I suspect they are floating.  Is it possible to power these direct from the board, bypassing the off switch?
The easiest way to fix it would be to allow the processor to know when the Off switch is on and off.  Wire the 5V from the shield to the Arduino via a resistor of ???Ohms and read that pin before doing anything in loop().


text:
ESP32 Dimmable LED Panel with MOSFET
I want to use ESP32 to control and use a dimmer for 6 LED panels in my bedroom. The specification of each panel is mentioned in the diagram. Although in the diagram it shows ONLY 1 MOSFET and 1 LED Panel but in reality there are 6 LED Panels therefore I am guessing that each of the 6 LED Panel will need a separate MOSFET.

I would like to know:

What MOSFET (Part number or model number, company name,  etc) should I use for the above LED panel connected with ESP32 (I guess voltage of ESP32 is 3.3 v) ?
Will each LED panel need separate MOSFET (6 LED Panels will need 6 seperate MOSFET) or can 1 MOSFET be connected to all 6 LED Panel ?
If I am using 6 LED Panels what should be the specification of Power Supply (Voltage & Amps) ?
If I use 6 set of MOSFET & LED Panels, can all MOSFETs be connected to a single PWM pin in ESP32 or does each MOSFET needs to be connected to separate PWM pins in ESP32 ?
Is the above circuit okay, or would you suggest some other components to be added apart from MOSFET?
What will be connection between power supply, LED and MOSFET.
I am guessing that 'Positive of Power Supply --> Positive of LED Panel', 'Negative of LED Panel -->  Source of MOSFET' and 'Drain of MOSFET --> Negative of Power Supply'. Kindly correct me if I am wrong.

Thanks.

To add more information regarding the LED panel:

It is 15W LED Panel (note it is not LED Bulb or LED Strip).
Link to LED panel is 15W LED Panel

Below is the picture of Driver that came with the LED Panel, note the below driver is non-dimmable.

Kindly help.

please provide a link to the datasheet for the LED panel .... if that is not available, then make and model of the LED panel .... or a web link to where it is sold

how do you want to dim a LED bulb with working voltage from 150 to 260 V? It will turn off under 150 and have full light over 150 V. it has a switching AC/DC power supply inside. use DC LED strips for the panel

Hi Juraj,
It is not LED bulb, it is a LED ceiling panel. I have added below more detail of the LED panel and picture of the original driver that came with the LED Panel.
Note that the original Driver is non-dimmable.

bulb or panel, it is the same principle for 'AC LED' . the LED bulb has the driver build-in. for the panel you could replace the driver, but it is not easy to do it right and sure not a question for Arduino SE. perhaps it is easy, only connect the DC side with the MOSFET and use PWM, but I can't tell if the driver likes it


text:
Arduino RS485 shield to RS485 temperature & humidity sensor
I’m try to get data from rs485 is not work please advise to me.
1.  Try to connect PC usb485 to DY-MD02 is work.
    Send command “AUTO” or “READ”

2.  Try to Arduino rs485 shield to DY-MD02 is not work.
    Send command “AUTO”

my code
''''
char command[4] = {'A', 'U', 'T', 'O'};

int n = sizeof(command)/sizeof(command[0]);   // Number of elements in an array

String incoming = "";   // for incoming serial string data

void setup()

{

      // initialize serial ports
      Serial.begin(9600);
      pinMode(EN,OUTPUT);
      digitalWrite(EN,HIGH); //Enable high, RS485 shield waiting to transmit data
      Serial.write(command,n); //Test send command Auto,Read to RS485
      delay(500);
}

void loop()

{

      String temp;
      digitalWrite(EN,LOW); //Enable low, RS485 shield waiting to receive data

      while(Serial.available() > 0 )
      {
          temp=Serial.read();
          Serial.println(temp);
          delay(1000); //Delay for some time, waiting for data transmitted
      }

}

''''

if change code to = Serial.readString() not show anything.
please help me
Thank

to Juraj
Maker tell me can connect with Arduino uno and send manual to me.
see in attach file.

exact model or datasheet of shield please? does it communicate with Uno over hardware Serial?

model of the shield?

it looks like your serial input doesn't provide end of line characters (\r\n) at the end. readString function fetch the character value step by step and store them in buffer till EOL character are received. After receiving EOL character it returns the string.

@Vaibhav, readString doesn't care about line ends. it returns after timeout

I want details about the RS485 shield

To Juraj = https://github.com/DFRobot/DFRobotMediaWikiMarkDown/wiki/Arduino_RS485_Shield_SKU__DFR0259

your shield on the photo is different

i'm tray change this code to readStringUntil, is OK
if(Serial.available() > 0)
  {
    temp = Serial.readStringUntil('\n');
    Serial.println(temp);
    delay(1000); //Delay for some time, waiting for data transmitted
  }

Thank all for help me
^^

I will suggest try to use Modbus Master library it will help you get the data from sensor. The issue with the code is you are only sending the command but while interfacing with modbus there is a packet/ frame which you need to form and then send it the packet/frame format is in the below diagram
I will prefer use an Arduino Mega or other arduino which have more than 1 Serial port for communication. I also faced a similar issue but it was resolved after digging a little bit you can have a look at the issue here


text:
Using MouseX in processing to control LEDs. Error in code - LEDs remain off
I am fairly new to processing and Arduino - I have a coursework deadline for both on Monday (6th January).
I am trying to write a script that uses the mouseX values to turn LEDs on and off. I haven't got any error messages on either of the scripts but currently, nothing happens to the LEDs (they remain off) when I move my mouse. I have tested the circuit with a simpler Arduino code and it is correct so there must be an error in my code!
I would be very grateful for some help. Thanks!
Processing code:
import processing.serial.*;
Serial port;
byte lightsOn;

void setup()
{
  size(600,300);
  port=new Serial(this,"/dev/cu.usbmodem1411",9600);
}

void draw()
{
  background(32,78,95);
  rect(300,0,300,300);
  noStroke();
  fill(185,215,216);

  lightsOn=byte(mouseX);
  port.write(lightsOn);

  println(lightsOn);
}

Arduino code:
#include <Servo.h>

Servo myservo;
int ledpinA=12;
int ledpinB=13;

void setup()
{
  Serial.begin(9600);
  myservo.attach(ledpinA&&ledpinB);
  pinMode(ledpinA,OUTPUT);
  pinMode(ledpinB,OUTPUT);
}

void loop()
{
  if(0<Serial.available())
  {
    int data = Serial.read();

  if (data>300)
  {
    digitalWrite(ledpinA, HIGH);
    digitalWrite(ledpinB, LOW);
  }
  else
  {
    digitalWrite(ledpinB, HIGH);
    digitalWrite(ledpinA, LOW);
  }
  }
}

lightsOn=byte(mouseX);

A byte can be any number from -128 to 127 (Java has no concept of "unsigned" values). The Arduino will reinterpret that as a value from 0 to 255.
if (data>300)

255, the maximum value, can never be more than 300 - so this will always fail.
You need to re-think what data you are sending and how you want to send it.


text:
Problem with a seven segment display. The segments blink then turn off
I can't figure it out what is the problem with my circuit, the segments turning on for sec and then they are turning off for good.
I tried to connect to GND instead of the 5 V but then, nothing happened.

My code:
void setup() {
  for (int pin = 2 ; pin < 9 ; pin++){ // setup pins 2 – 8 to be output
    pinMode(pin, OUTPUT);
  }

  for (int pin = 2 ; pin < 9 ; pin++){ // turn on pins 2 - 8
    digitalWrite(pin, HIGH);
  }
}

void loop(){}

Working simulation demo

How do you expect a LED to light up if you put 5 V on anode and cathode?

You are also missing the current limiting resistors.

@gre_gor. Thanks. I updated my question. Can you take a look?

There are two types of 7 segment displays: common anode and common cathode. Which do you have? Depending on the type, you must connect the COM pin to 5V and all the segment pins via a resistor to GND to light them up (common anode type). Else reversed (COM to GND, segments to +5V over a resistor)

The first thing to understand is how to connect the 7 segment display to your Arduino. The common anode pin connects directly to 5VDC. Each "segment" connects to the Arduino through a current limiting resistor (1k ohm is a good value to start with).

To turn a segment on, you supply a ground to it (through the resistor of course). Change: digitalWrite(pin, HIGH) to: digitalWrite(pin, LOW) in your sketch to turn on the segments.
I'm sure there are plenty of tutorials on the internet showing one resistor on the common anode input, but that is not the correct way to drive the display. Think about what happens when you display the number 1 VS the number 8. Changing the number of segments drawing power from the single resistor will vary the intensity of the display. The number 1 will be far brighter than the number 8.

Make sence. You are right, all of the tutorials are using only 1 resistor. I will try it.. Thanks!

There are two reasons the tutorials might show a single resistor on the common cathode or anode:  (1) They just accept the fact that an 8 will be a little dimmer than a 1--that might be acceptable for a quick hack.  (2) They illuminate one segment at a time, essentially blinking the segments fast enough that they seem to be lit steadily, which you can do from the microcontroller if it's not too busy doing other work.  There are also peripheral drivers that can do this type of time multiplexing.

Thanks! It was a good explanation! Another thing I noticed that there are  2 types of 7 segment display based on Anode and Cathode. Depends on the type I need to connect it to 5v / GND. Right?

@MoshFeu - Yes, there are common anode and common cathode displays available. Here is a tutorial that does a good job of explaining the differences: https://www.electronics-tutorials.ws/blog/7-segment-display-tutorial.html

With foregood you mean broken probably.
I don't see any resistor in your circuit, probably the LEDs are broken.
I'm afraid you have to use a new segment LED, and follow:
Arduino Example
Especially read this fragment:
Current-limiting Resistors

Don't forget that the display uses LEDs, so you should use
  current-limiting resistors in series with the digit pins. 330 ohms is
  a safe value if you're unsure. If you use current-limiting resistors
  on the segment pins instead, then open up the SevSeg.h file and set
  RESISTORS_ON_SEGMENTS to 1 for optimal brightness.

Ok. I updated my circuit. Can you take a look? Thanks!

Did you also follow the arduino example first? Because if that doesn't work, your segment display is broken.


text:
Arduino ESP8266 ESP-01S GET command
Looking for some help on this please. It is a little long winded, but the point of it is I cannot retrieve a string response via my ESP8266 ESP-01S.
I connect my ESP to my Ardiuno using SoftwareSerial esp8266(2,3).
I can quite happily send POST and GET commands to my server and process the request server side. This is done through the AT sequence below. My server uses a REST API to receive the request and responds with a simple string (for example 'HELLO'). If I attempt the same client side functionality through C# code or Python on my Pi I receive the response from the server no problem. But on my Arduino the response is always 32 when reading via ESP.read() (which I believe is in bytes and signals end of data). I have also tried esp.readString() and esp.readStringUntil('\n') all with no luck.
Is it not possible to access the response sent back to the ESP using my approach?
I see many examples go down the route of programming the ESP directly. I'm not really looking to do that on this attempt as I am creating some basic Arduino tutorials for family and friends and would prefer to not add that complexity.
Result server response
esp8266.println(postRequest);
while (esp8266.available() > 0) {
  Serial.println("." + esp8266.readString() + ".");
}

So I guess in short, am I wrong in expecting the
//* AT SEQUENCE*
AT
AT+RST
AT+CWMODE
AT+CWJAP
AT+CIPMUX
AT+CIPSTART
AT+CIPSEND

// CREATE DATA

String data = "=DATA1";

// POST

String postRequest =
  "POST " + URI + " HTTP/1.1\r\n" +
  "Host: " + HOST + ":" + PORT + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Content-Length: " + String(data.length()) + "\r\n" +
  "Content-Type: application/x-www-form-urlencoded\r\n" +
  "\r\n" +
  data;

// GET

String postRequest =
  "GET " + URI + "?data=" + data + " HTTP/1.1\r\n" +
  "Host: " + HOST + ":" + PORT + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Connection: keep-alive\r\n" +
  "Content-Length: " + String(0) + "\r\n" +
  "Content-Type: text/plain\r\n" +
  "\r\n";

the host header value should not contain port

@Juraj That's not true. It's not needed only if it's the default, but even then it's nothing wrong having it.

Those AT commands are missing arguments. 32 is the ASCII code for a space character. The HTTP server's first character of the response should be "H". Neither your POST or GET request have the proper format for the parameters. GPIO3 is a hardware serial's RX pin.

thank you, @gre_gor. now I regret I was lazy to open the RFC

Juraj. Thanks, I understand. Although what is RFC?
@gre_gor, thanks for your response but I'm pretty new to this and what you've said is above my head. I've followed other tutorials (my project is a hybrid of many of them) to get here. Do you know what arguments I am missing? As I seem to have included enough to covert sending data to my server?

gre_gor corrects me with a link to RFC 2616 (HTTP protocol description). RFC is "Request for Comments" It is a way how standards are maintained at "Internet Engineering Task Force" organization


text:
Error while uploading the sketch for Arduino Mini
I'm having a problem while uploading the program.
Arduino: 1.8.4 (Windows 10), Board: "Arduino Mini, ATmega328P"

Archiving built core (caching) in: C:\Users\UMME-K~1\AppData\Local\Temp\arduino_cache_566019\core\core_arduino_avr_mini_cpu_atmega328_3f323efdab4276426e9d8710d5d73f64.a
Sketch uses 3932 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables. Maximum is 2048 bytes.
D:\Amna\arduino-1.8.4\hardware\tools\avr/bin/avrdude -CD:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\UMME-K~1\AppData\Local\Temp\arduino_build_808790/buzzer.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

An error occurred while uploading the sketch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

What should I do?

how is the Mini connected to USB? (or serial port?)

has it ever worked?

@Juraj through USB cable , serial port

doing it for the first time @jsotola...

connects the cable to Reset pin?

https://www.google.com.pk/search?biw=1366&bih=662&tbm=isch&sa=1&ei=guaHWq25IsG1gQbTuZnIDg&q=arduino+mini+program+upload&oq=arduino+mini+program+upload&gs_l=psy-ab.3...23636.28787.0.29006.15.15.0.0.0.0.330.1716.2-5j1.6.0....0...1c.1.64.psy-ab..9.6.1711...0j0i67k1j0i8i30k1j0i30k1.0.5aM_FwHjjdM#imgrc=p97hfh3t5iS8aM: @Juraj This is the arduino mini that im using and i have connected the data cable to it.. I am having issues while uploading the program. I think there is an issue with some driver or something if u know please let me know ....

On Uno and other boards with USB on board, for flashing the IDE resets the Atmega to bootloader, sending signal over USB. Mini has not an build in USB and you connected it with an USB to TTL cable. Has this cable a Reset signal line? If yes, did you connect this line to Reset pin?
If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button.

Well Thanks for your answer...Highly appreciated ... Anyhow the issue is solved  ...

"If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button."
In the IDE, if you select File:Preferences and turn on Verbose outputs, you can see when the IDE is about to download, there will appear "compiled xxx of 32xxx bytes), then3 attempts to download. If you press Reset when you see that message, or press & hold reset then release when you see that message, it is much easier to get the bootloader started at the right time (assuming one is actually loaded and there is nothing interfering with the signals on the D0/D1 pins).


text:
Why does a variable size struct not compile in the Arduino IDE?
This sketch does not compile in the Arduino IDE
void setup() {
  // put your setup code here, to run once:

}

struct test {
  int i;
  char variable[];
};

typedef struct test test;

test t = {
  0, "hi"
};

void loop() {
  // put your main code here, to run repeatedly:

}

Arduino throws
sketch_may09a:16: error: initializer-string for array of chars is too long [-fpermissive]

 };

 ^

exit status 1
initializer-string for array of chars is too long [-fpermissive]

However compiling with g++ works just fine. How can I fix it? Or is there a principle reason why flexible array members are not supported?

It hurts to see that code, so it must be wrong. A struct is a definition of a variable (wich contains other variables). How would you create an array of those structs when they have different lengths?

@Jot: The struct type itself is declared correctly. There's nothing wrong with an [] array as the last member of a struct. However, in standard C language the only way to make such structs to "have different lengths" is to malloc them individually. This is what this [] feature is designed for. In all other contexts the [] array simply "disappears" (i.e. it is an array of size 0). So, the issue simply does not exist in situations when one'd try to create an array of such structs.

@AnT I know that it is set to zero size and I have read your answer with the correct type definition and declaration of the structs. the_architect tries to put the characters into the struct itself. That is not possible.

@Jot Not sure what answer you are talking about. Placing the characters into the struct itself, as the OP is trying to, is possible through GNU-specific extension. As I said already, the OP code is perfectly correct from GNU point of view.

Flexible array member is a C feature. It does not exist in C++. On top of that, the way you use it to declare and initialize a static struct of flexible size is non-standard even for C.
However, GNU-C language supports it as an extension. Also, newer versions of GCC (6 and higher) allow this in GNU-C++ code as an extension as well. But GCC 5.4.0 used by Arduino IDE doesn't support this non-standard feature in C++ code.
If you flip through different GCC versions on Godbolt (https://godbolt.org/z/Iul7hD) you'll see that support for this feature has always been present in C code, but for C++ code it first appeared in GCC 6.
This is why you were able to compile it with your standalone g++ compiler (which is apparently a much later version), but were unable to compile it in Arduino IDE.
It means that if you really want this non-standard code to compile in the current version of Arduino IDE, you have to place it into a .c file. Or just specify the array size explicitly.

Thanks for the link to godbolt. I tried a few things and it goes wrong very fast. For example adding a variable to the struct after the flexible array, or with an array of structs. Some things work with gcc version 6, but not with 8 or 9. The sizeof() does not include the flexible array member. And so on.

@Jot: Flexible array member is naturally supposed to be the last field of the struct. Yes, sizeof does not take it into account. Flexible array members are intended to provide support for the good old "struct hack" (http://c-faq.com/struct/structhack.html) and the fact that sizeof ignores this member makes it easier to calculate the proper size for malloc.

Maybe you've compiled it in g++ without any warnings enabled (or maybe it yeld warnings but was compiled). The arduino uses flags to consider all warnings as an error, so it won't compile. It may wary for different platforms, I've got -fpermissive used (and I don't like it at all).
That's because size of struct must be known compile time and if you provide char variable[]; you'll get zero sized array. Therefore anything biiger than nothing you'll try to initialize for is too long.
Maybe you're looking for something like this:
struct test {
  int a;
  const char * ptr;
};

test paramx {1, "some string"};
test paramy {2, "another string"};

test array[] = {{3,"three"}, {4, "four"}, {5,"five"}};

char variable[]; is not a zero-sized array. It is a flexible array. In standard C its size depends on how much memory was allocated by the user for the whole struct object. And in extended GNU-C the extra memory can be requested the way the OP requests it: by using an {} initializer. As far as GNU-C is concerned, the code is perfectly fine.

And it works like it's zero size array pointing after the end of struct, so you have to allocate more than sizeof(struct) to use it without "buffer overflow". But as it was noted, it can't work on statically allocated struct instance. And in C++ it has to be struct containing POD's only.

Well, it can't work for non-dynamic struct object in pedantic standard C. But the OP is apparently not trying to use pedantic standard C. And yes, it can and will work in extended GNU-C (and in GNU-C++ after version 6 of the compiler). The original code is perfectly fine as far as GNU-extended versions of these languages are concerned. The code will compile and work as intended in Arduino IDE once it is placed into a .c file, as I clearly stated in my answer. Once Arduino IDE moves to a later version of AVR-GCC, this code will compile and work as intended right away.

Hower I'm not sure he really wanted to use FAM. It might be just coincidence. Maybe he wanted just  const char * variable; That should be perfectly legal in this case (or flash string helpers / progmem pointers)

The title of the question seems to suggest that the OP did actually want to use a variable-size struct. Whether they meant it literally, as a reference to this specific language feature - I don't know.

@AnT True. Btw, it seems to be working with using malloc anyways. He just cannot use that initialization, because it takes it as zero lenght array. And strcpy must be used to copy strings on it's place.

Well, once again: in GNU C you can use this initialization. It is a specific feature of GCC compiler. It does set aside the proper (flexible) amount of static memory for struct object and it does work as if the initializing string was properly placed the into the trailing array. sizeof for the struct will ignore the [] array, but the elements will be properly accessible (and modifiable).