text:
Managing 2 ultrasonic sensors without blocking the other
I have an ultrasonic distance sensor. When this sensor is measuring a distance below 25 cm, a second sensor has to be measuring a distance below 5 cm. If not, there should be a one minute timespan, after which a speaker should make noise until the second sensor is measuring a distance below 5 cm.
I am having trouble with this. The first sensor has a lot of code it should be running as well, so using a while-loop to wait out one minute for the other sensor and creating noise after that isn't a possibility.
How do I go about this dilemma? I read into interrupts in Arduino but unfortunately I don't know how I'd make this work.

look at the "blink without delay" example; you need to do the same thing while "waiting" on the sensors.

I strongly advice you to use interrupts and make sure the sensors are in a cylindrical cone in order to prevent interference to each others as much as possible.
Here is code snippet which can give you an idea how the interrupts are set and used. I believe that you can adapt it to yours. It is from Arduino forum (link), credits to "cattledog".
volatile unsigned long LastPulseTimeA;
volatile unsigned long LastPulseTimeB;
int durationA;
int durationB;
//unsigned long startTime;
#define trigPinA 7
#define echoPinA 2
#define trigPinB 8
#define echoPinB 3
void setup() {
  Serial.begin (9600);
  pinMode(trigPinA, OUTPUT);
  pinMode(echoPinA, INPUT);
   pinMode(trigPinB, OUTPUT);
  pinMode(echoPinB, INPUT);
attachInterrupt(digitalPinToInterrupt(echoPinA), EchoPinA_ISR, CHANGE);  // Pin 2 interrupt on any change
attachInterrupt(digitalPinToInterrupt(echoPinB),EchoPinB_ISR, CHANGE);  // Pin3 interrupt on any change
}
void loop(){
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPinA, HIGH);
  digitalWrite(trigPinB, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  Serial.print("Sensor A  ");
  Serial.print(LastPulseTimeA);
  Serial.print('\t');
  Serial.print((LastPulseTimeA/2) / 29.1,1);
  Serial.println("cm");
  Serial.print("Sensor B  ");
  Serial.print(LastPulseTimeB);
  Serial.print('\t');
  Serial.print((LastPulseTimeB/2) / 29.1,1);
  Serial.println("cm");

  delay(1000);
}
void EchoPinA_ISR() {
    static unsigned long startTimeA;

    if (digitalRead(echoPinA)) // Gone HIGH
        startTimeA = micros();
    else  // Gone LOW
        LastPulseTimeA = micros() - startTimeA;
}
void EchoPinB_ISR() {
    static unsigned long startTimeB;

    if (digitalRead(echoPinB)) // Gone HIGH
        startTimeB = micros();
    else  // Gone LOW
        LastPulseTimeB = micros() - startTimeB;
}

Thanks, I'll try. Question though, will there be time enough for the rest of the program to run, as I assume the pins will change value all the time, interrupting the program 24/7?

As far as I can see from the specs, the echo will take some time up to 25 ms depends on the distance, maybe even more if there is no obstacle and then can take up to 38ms. So, it won't be that busy. But, of course it is also what you want to do with the echoing data. You may then consider to switch Arduino Mega or even Cortex-M0 or further.

fairly simple:
  if (time_is_up_for_sensor1()) read_sensor1(); //read sensor1 if time is up
  if (time_is_up_for_sensor2()) read_sensor2(); //read sensor2 if time is up

in time_is_up_for_sensor1/2(), update for the next round of reading:
int time_is_up_for_sensor1(void) {
  static uint32_t millis_next = 0; //next millis
  if (millis() >= millis_next) {  //time is up for sensor1
    millis_next += INTERVAL_SENSOR1; //advance to the next measurement time
    return 1;  //needs to read sensor1
  } else return 0;
}

similarly for sensor2

The millis_next += INTERVAL_SENSOR1; ... if (millis() >= millis_next)... method miscomputes when millis() overflows.  To avoid that, instead write millis_prev = millis();  (or perhaps millis_prev += INTERVAL_SENSOR1;) and then test via if (millis()-millis_prev > INTERVAL_SENSOR1)...

what does static uint32_t millis_next = 0; do exactly? (I'm new to C++/Arduino)


text:
Set array to array passed as parameter in constructor
I have a constructor which looks like this:
Preset::Preset(char* presetName, MIDICommand* MIDICommands[])
  _presetName = presetName;
  _MIDICommands = MIDICommands;
}

_MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.
When run, this throws the error below on the second line in the constructor:
incompatible types in assignment of 'MIDICommand**' to 'MIDICommand* [0]'
Why do I need to declare _MIDICommands as MIDICommands**, and not MIDICommand* _MIDICommands[]?
The array I pass is declared like this:
MIDICommand* one =  new MIDICommand(1, 2);
MIDICommand* two =  new MIDICommand(2, 2);

MIDICommand* MIDICommandsA[] = { one, two };

EDIT:
When I pass in an array, should I just use MIDICommand* MIDICommands, or do I need the [] at the end?
Now I've taken them off, but then I get trouble with passing the array.
It doesn't find a matching function to call. Basically, this MIDICommand* MIDICommandsA[] = { one, two }; doesn't match this MIDICommand* MIDICommands parameter.
EDIT 2:
So, I've solved the problem of passing the array. I changed the parameter in the constructor to MIDICommand** MIDICommands, and I just pass a pointer to the array.
Now the constructor looks like this:
Preset::Preset(char* presetName, MIDICommand** MIDICommands)
{
  Serial.println(MIDICommands[0]->getProgramChange());

  _presetName = presetName;
  _MIDICommands = *MIDICommands;

  Serial.println(_MIDICommands[0]->getProgramChange());
}

I'm getting an error on the second Serial.println, telling me it is a non-pointer type. I'd like it to be a pointer, so that's what I am looking at now.
_MIDICommands is now declared like this: MIDICommand* _MIDICommands.
EDIT 3: When I try to loop through the array now, it seems I have lost the second element, and have only the first.

Guessing, try leaving off the square brackets in the list of constructor parameters.  If no one answer w/the correct solution, I'll try to dig into this more later.

One is a zero-sized array of pointers, the other is a pointer to an array of pointers. Subtle difference, but important to the compiler.

@st2000 I tried leaving of the square brackets, but then I have some trouble passing the array.

@Majenko Thanks, but I still haven't figured it out.

_MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.

This is the major error. That is an incomplete array type. The number of elements (and storage) is unknown.
To solve this you have decide on how the elements should be stored. Should the class allocate storage and copy the values given to the constructor or should a pointer to the vector be used.
One alternative is to use a template class and provide the max element size as a template class parameter.
Cheers!

I've changed that to MIDICommand** _MIDICommands now. Is that not viable as well? I'd rather pass around a pointer to the array of pointers, and it seemed to work, except I can't access my values, so I guess it isn't working in the end.

source: Stack Exchange

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

sort: votes


text:
How can I setup a LED state change with push buttons?
I'm doing a project using Arduino Uno R3 and I'm trying to use two buttons to change LED state between HIGH and LOW. I have already a code but someting its not right because the LED should be starting in LOW state but it's starting in HIGH state. I checked the circuit and its all good none of the components is connected in wrong place or not connected corretly and the resistors I used are the right ones.
Here is the code I'm using:
 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);
}

void loop() {

static bool ledState = false; // LED is off by default
 if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
    digitalWrite(ledpin, HIGH);
    ledState = true;
 }
  if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
    digitalWrite(ledpin, LOW);
    ledState = false;
  }
}

You need some PULLUP there - either external resistors or INPUT_PULLUP settings, otherwise disconnected pin have not defined valou (so it can be LOW even if button is not pressed.

I tryed the INPUT_PULLUP and it worked but now the LED state turns LOW when I stop pressing the button and the other button does the same thing.

I tried that on my arduino and it works - when I press button1, LED goes ON when I release it, the LED is still ON. When I press button 2, LED goes OFF and stays OFF even when I release the button. I would check all your connections if they are reliable (do not lose contact when you manipulate the buttons - I have universal shield with LEDS and buttons soldered fast - I had recently some problems with some breadboards) and if the led is on pin 13(the build in is), while buttons are between pins 7,8 and ground. (and that the script uploaded correctly)

Also note, that your loop can be as simple as: loop() { if ( ! digitalRead(pushbutton1) ) digitalWrite(ledpin, HIGH); if ( ! digitalRead(pushbutton2) ) digitalWrite(ledpin, LOW); }

This is an excellent tutorial for exactly that:
http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/
Its a bit hard to give you a specific answer without seeing you circuit.
but as a start, i would set the ledPin to LOW in the setup routine.
void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);

  //initialize the pin to low
  digitalWrite(ledpin,LOW);

}

I think you have just minor changes. First of all, you haven't applied pullup. And here, what is the use of boolean lastbuttonstate1 = LOW; and boolean lastbuttonstate2 = LOW;? I think it not useful for the code so I remove it. And always initialize flag or something in starting of the code means globally. I update your code, just check it out. It might be helpful.
int ledpin = 13;
int pushbutton1 = 8;
int pushbutton2 = 7;

static bool ledState = false; // LED is off by default

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

  pinMode(pushbutton1,INPUT_PULLUP); // Provide pullup
  pinMode(pushbutton2,INPUT_PULLUP); // Provide pullup
}

void loop()
{
  if((digitalRead(pushbutton1) == LOW) && !ledState) // 1 pressed & led is off
  {
    digitalWrite(ledpin, HIGH);
    ledState = true;
  }
  if((digitalRead(pushbutton2) == LOW) && ledState) // 2 pressed & led is on
  {
    digitalWrite(ledpin, LOW);
    ledState = false;
  }
}

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


text:
Remote controlled lights
I have a fixed roof light in my room that came with a remote control that can be fully taken apart. The remote control can switch the lights on or off using a radio system. I was wondering if there was any way to use my Arduino to control the remote control (through wires) to control the lights. I do not have any Arduino radio components so it would still need to go through the original remote. I have taken the remote apart and this is what it looks like:
http://go.hma-uk.org/dlt
The buttons are as follows: the top two (K1 & K2) buttons is to turn on/off a coloured LED but these are not important to me. The button K3 is to turn on/off the main light (I want the effect of this button being pressed to be created using the Arduino) and the button K4 is to turn all lights on/off.

Picture = 404. Attach the picture to the post using the picture button.

I have 10 pictures, link works for me

Well, not for me, and probably not for the rest of the world.

Ill see what I can do

Works better.  What voltage does the remote run from?

I don't know the voltage.

It will tell you on the battery.

I used to use gamepads as input device for USB many years ago. I simply soldered wires paralel to buttons and shortcut them to "simulate" the button press - it worked nice and reliable.
With Arduino - I would measure the voltage on the button in question with Voltmeter - if the voltage is less then Vcc of Arduino (5Volts), I would simply connect Arduino ground to lower side (negative) of the button and output pin to the high side of the button. Then I would set that pin for Input to have the button released (from Arduino side) and to LOW + Output to have it pressed. (maybe I would first shortcut the button with Ampermeter to see, that no more, than 100mA is sinking there).
If the sink is more, or the voltage is more, then I would use relay and shortcut the button with the relay, switching the relay with Arduino.
( something like this http://www.instructables.com/id/Home-Automation-How-to-Add-Relays-to-Arduino/?ALLSTEPS )


text:
Is there any way to use the serial port as an interruption source?
I have an sketch made for reading a temp/hum sensor once every ten seconds aprox. However, I want to introduce an interruption source to send from my keyboard a magic word to make the sensor be read exactly at that instant.
By checking out the reference on attachInterrupt(), I found only the ways to declare interruption pins, but nothing related to serial. What you can say about it?
Thanks in advance.

Serial.available() or the serialEvents can be used essentially like an interrupt.

@dandavis, not really.  Those are polling methods, not interrupts.  Those two methods do not "interrupt" other things that your code may be doing.  Your code must call available frequently or, if you are using serialEvent, you must make sure that loop doesn't block.  However, in the OP's application, polling is sufficient (see gre_gor's answer).

@slash-dev: regardless of the underpinning, to the dev, they "can be used essentially like"... Specifically, there's no need here for a low-level interrupt when the "main work" is only is done every 10 seconds...

Use millis() for the timing of the temperature reading, then you can read from the serial in between time and won't need to use any interrupts.
unsigned long last_measure = 0;

const byte buffer_size = 16;
char buffer[buffer_size] = "";
byte buffer_i = 0;

// setup() and other stuff

void loop() {
    if (millis() - last_measure > 10000) { // read the temperature like in the "blink without delay" example
        last_measure = millis();
        int value = readSensor();
        Serial.println(value);
    }
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') { // end of line, which means we got the whole string
            if (strcmp(buffer, "magic") == 0) { // compare if it matches the magic word
                int value = readSensor(); // read and print the temperature
                Serial.println(value);
            }
            buffer_i = 0; // reset the index
            buffer[buffer_i] = 0;
        }
        else if (buffer_i < buffer_size-1) { // if the buffer is not full
            buffer[buffer_i++] = c; // add char to buffer
            buffer[buffer_i] = 0; // and null terminate the string
        }
    }
}

Thank you all, guys. I considered your ideas, and then I code this solution. It works fine, right now I'm reading my sensor once every 30 minutes (1,800,000 miliseconds) and whenever I send the magic word. I hope it is useful to you:
void loop(){
if ((millis() - timer < 1800000) && (Serial.available() > 0)){
    magicInput = Serial.readString();
    magicInput.trim(); //Cleans input from \n at the end, otherwise never equals magicInput
    if (magicInput.equals(magicWord)){     //Elegant form for "=="
      Serial.println();
      Serial.println("  === Your request ==="); //Shows requested measurement
      Serial.println(millis() - timer); //Time since last measurement
      measure(); //
    }
  }

  if (millis() - timer >= 1800000){
    Serial.println();
    Serial.println("===== Normal mode =====");  //Indicates that measurement was not requested by user
    Serial.println(millis() - timer); //Checks that 30 "exact" minutes have run
    mide();
    timer = millis();
  }
}

Serial.readString() has a timeout of 1 sec by default, so your response has an unnecessary delay. Use Serial.readStringUntil('\n') instead.

Here is a logic snippet you can use:
unsigned long timer = 0;

void loop(){
  readSensors();
  while(millis() - timer < 10000){
    if(stringFromSerial == magicWord){
      readSensors();
    }
  }
}

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


text:
Arduino slave with 2 masters sharing the same I2C Bus?
Consider a scenario where two (or more) master devices (the NodeMCU's, in this case) share an I2C bus with one (or more) slave device(s), like thus:

Would this be a feasible setup?  In other words,  could both masters request (not simultaneously) from the slave?

Only if you can implement MultiMaster in the ESP8266's (software-based) I2C library.

care to elaborate an answer?  :)

The situation you describe is called MultiMaster. It is normally done in hardware using the I2C peripheral in the MCU. However the ESP8266 doesn't have one (or if it does, it's not used), and uses bit-banging to implement I2C in software. If you can add MultiMaster functionality to the ESP8266's Wire library then possibly yes, you could do it.
Another option is to have some other communication channel between the two masters (it could be as simple as a wire with a pullup resistor - see below) so that only one master communicates at a time.
Electrically there is no problem with your setup - I2C is a fully open-drain system (or should be implemented as such - hence the pullup resistors needed on the SCL and SDA pins), so multiple devices can drive the lines at the same time. It's just that if they do you will get data corruption and communication won't happen.

Example: Semaphore Wire Implementation

Connect any two GPIO pins together with a wire. Add a pullup resistor to the wire (10kΩ should suffice).
Both GPIO pins are set to INPUT.

When a master wants to send it first reads the GPIO pin:

If it is HIGH then it is "clear to send". So it sets the GPIO to OUTPUT and pulls the line LOW.
If it is LOW then it waits for a random amount of time and tries again.

Once communication is finished the master sets the GPIO pin to INPUT again.

would strict scheduling provide a workaround?

@tonygil Only if you have zero clock drift...  Simpler to have a semaphore signal. I have added more detail to my answer.

I try to keep drift to under 3 millis across the system (I sync a master with a network timeserver and then send the unixtime in my request) and my calls happen on the clock, every 60 seconds (plenty of time to avoid crashing).  Will check your semaphore protocol, tks.

GENIUS!   Semaphore protocol/rigging works perfectly.   will be bountified (as soon as I am allowed to open and then to award bounty (3 days, i guess).

Outstanding answer. (Voted). What (if any) Arduino boards have the hardware needed to support MultiMaster? And what library/libraries do you need to us in order to take advantage of it?

@DuncanC Most, but the software is what is lacking in (most if not) all cases.

How does the clock signal work when you have multiple masters and the semaphore approach? I thought the master generated the clock signal? Wouldn't the multiple masters fight over who asserts the clock pin unless you used some sort of switching to enable the clock signal on the active master and disable it on the others?

@DuncanC The clock signal is only there when the master is communicating. Whichever master is communicating is the one that controls both the IO lines at any moment in time.

@Majenko, when you say "Add a pullup resistor to the wire", does that mean a 10K Ohm resistor to GROUND?  Sorta like reading a reed switch?

No, that would be a pull-down. You want a pull-up. Connect it to +3.3V.

@Majenko, if the Nano is 5V shouldn't there be level conversion on SDA and SCL?

@Juraj No need. Since the ESP8266 is master the bus runs at 3.3V (the ESP8266 provides the pullups to 3.3V). The Arduino reads 3.3V just fine, and since I2C is an open drain protocol the Arduino just connects the signals to ground for 0 and releases them to the pullups (3.3V) for 1. If it were the other way around it would be trickier. You'd need to disable the internal pullups of the Arduino and manually pull the lines up to 3.3V.

@Majenko, thank you for the explanation

Changed diagram after comments and accepted answer:

Yes, except that the upper and lower ground rails on the breadboard aren't connected except via the internals of the Arduino.

adapted to reflect your comment above

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


text:
I2C master/slave maximum requestEvent message size
Using a NodeMCU master and an Arduino slave (Wire.h on both sides), is there a maximum message size (32 bytes?) for the answer that the slave sends from requestEvent()?
If so, is there any solution to circumvent such a restriction WITHOUT the use of other libraries (like I2C_Anything, for example)?

What libraries do you use on both sides? Wire on the Arduino? And what library on the NodeMCU?

The I2C protocol itself does not have a transmission size restriction. But the implementation in the Wire library only reserves a specific amount of RAM for the buffers. This site mentiones 32 bytes for normal Arduinos (couldn't find the source code currently) and I found 128 bytes for the ESP8266 in the source code.
You cannot have unlimited message length, since the buffer has to hold the whole message and the RAM on normal Arduinos is very limited.
But you can make the buffers of the libraries bigger by changing the corresponding defines in the header files to a bigger value. Keep in mind, that the actual used memory space is with a factor 2, since the buffer size gets used for both send and receive buffer.

If you need bigger messages, than is fitting in the available RAM, you should either change to a board with more RAM, or develop a way to process one part of a message, deleting it and then process the next part (multi part message). Though that raises the question, why the messages have to be that big in the first place.

I tested and the limit, without tinkering with the Wire.h library and it didnt work.

What exactly did you test how and what exactly didn't work?

i increased the char array to 64, instead of 32 bytes.  Master did not receive message.  Changed back to 32 bytes and it starts receiving again.

https://github.com/arduino/ArduinoCore-avr/blob/7a2e1cd815266fef3012a5c9b48f88d78551f838/libraries/Wire/src/Wire.h#L1

apparently, yes, the Wire.hlibrary must be tinkered with, which would make the sketch implementation non-standard.  There is no guarantee that future versions of this library will accept such tinkering.

Of course, there is never a guarantee. But it is very probable, that future implementation will still allow this, since there is no sane way to get around a fixed buffer size (dynamic allocation is bad on microcontrollers). And they already have one single define for that, so it is not very probable, that they change that to a less good way of setting the buffer size.


text:
Arduino IDE monitor multiple USB ports simultaneously
Is it possible to monitor multiple USB ports simultaneously in Arduino IDE while running only ONE instance of the IDE?
If not, which solutions come alternatively to mind?

No. It's not. It's too primitive.

tks.  chad solved it elegantly with a python script.  lightweight and easy to use.

If you are only interested in monitoring the output, a simply python script can be run to monitor the port. This sample takes an input of the port number(assuming they get named ttyUSB1, ttyUSB2, ect...  Or you can modify it to be a hard coded port.  Also make sure the baud rate matches with what your arduino is running (115200 in the example)
You can then run this script in two separate terminals, one for each port
#!/usr/bin/env python3

import serial
import sys

if len(sys.argv)<2:
    print("Please give serial port number")
    exit()
port=sys.argv[1]
ser= serial.Serial('/dev/ttyUSB'+port,115200,timeout=5)

while True:
    try:
        print(str(ser.readline().strip()))
    except:
        print(sys.exc_info())
        ser.close()
        exit()

Start the program like so
python3 ./programName.py 1 (or ./programName.py 0, etc)
The number dictates which of the ttyUSBx devices you are trying to watch (will match with what you see in the arduino IDE).

the port is stumping me.  mind clarifying?  I keep on getting Please give serial port number

start the program like so   ./programName 1 or ./programName 0  the number dictates which of the ttyUSBx devices you are trying to watch(will match with what you see in the arduino IDE)

Spot on!  Perfect, elegant, simple.  UPVOTED, ACCEPTED & BOUNTIFIED.  :)

@tonygil, to copy port input to output, you don't need python. the python script could monitor more ports and print them with different color

that is also very useful, tks @Juraj!

You can run multiple instances of the Arduino IDE to work with multiple boards at the same time. Start IDE second time with Start menu or desktop shortcut.
Of course you can monitor the COM/tty port with a common serial terminal program too.

UPVOTED because it addresses the root problem of monitoring multiple boards.  NOT ACCEPTED becacuse the solution needed depended on one and only one instance of IDE.   tks!

Short answer : No.
Long answer : Noooooooooooooooooooooooooooooooooooooo, since one window can only work with one arduino.
That being said, if you open another file, or create new file (Ctrl + N) on existing window, it doesn't make another process.
It is still on the only javaw.exe process running on your computer (you kill that, both window gone for good.)
To make it simple :

Double click Arduino icon on your desktop, and double click it again, it will run as 2 separate process.
Double click Arduino icon on your desktop, and then use open file or new file, it won't make another process.

But I think I misunderstood your question. If you're asking for arduinos in multiple USB ports, yeah, one IDE can see wherever you plug it in.

Tried your suggestion: 2 windows - 1 process.  Ubuntu creates a second process, unfortunately.

Sloeber, an open source IDE based on Eclipse on which I am a proud contributor, does have this feature, but the Arduino IDE does not.

I use Sloeber. It is a very good integration of Arduino build tools and packages into Eclipse


text:
NodeMCU 1.0 - Exception 9 `Fatal exception 9(LoadStoreAlignmentCause):`
I am getting this error in my code.
Fatal exception 9(LoadStoreAlignmentCause):
Using core version 2.4.2
Stack trace
Decoding stack results
0x40213e9c: dns_gethostbyname at core/dns.c line 1472
0x40204c21: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
0x40205038: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
0x4020306b: setPostString(int, int, Array8Int, char*) at /home/tony/Arduino/sketches/tempo1_vs11e_Master_NodeMCU_Rain_Wind/tempo1_vs11e_Master_NodeMCU_Rain_Wind.ino line 516
0x40203f8a: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs11e_Master_NodeMCU_Rain_Wind/tempo1_vs11e_Master_NodeMCU_Rain_Wind.ino line 335
0x40209080: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
0x402048e0: loop() at /home/tony/Arduino/sketches/tempo1_vs11e_Master_NodeMCU_Rain_Wind/tempo1_vs11e_Master_NodeMCU_Rain_Wind.ino line 243

struct declaration
struct Array8Int {
    int array[8];
};

loop
char post[300] = "";
int pulseChange05m = rainCheck(slaveData);
int now10 = floor(unixtimeServer/10)*10;
Array8Int slaveData = slaveCheck(now()); // update slaveData array
setPostString(now10, pulseChange05m, slaveData, post);

functions
void setPostString(int unixtimeEvent, int pulseChange, Array8Int postData, char* postStr) {
  bool flag = true;
  float rainHour = pulseChange*0.25;
  if (hour() == 10) { // 7 AM palmital
    rainCount = 0;
    rainCount05m = 0;
  }
  rainCountHour = rainCount;
  int humidityBme280HourAvg = 0;
  int pressureBme280HourAvg = 0;
  int temperatureBme280HourAvg = 0;
  int lightSensorHourAvg = 0;
  int pressureBme280HourMin = 100000;
  int temperatureBme280HourMin = 1000;
  int temperatureBme280HourMax = -1000;
  int counterLoop = counterHour;
  for(int i=0;i<counterLoop;i++) {
    lightSensorHourAvg += lightSensorHour[i];
    pressureBme280HourAvg += pressureBme280Hour[i];
    temperatureBme280HourAvg += temperatureBme280Hour[i];
    temperatureBme280HourMax= max(temperatureBme280HourMax,temperatureBme280Hour[i]);
    pressureBme280HourMin = min(pressureBme280HourMin,pressureBme280Hour[i]);
    temperatureBme280HourMin = min(temperatureBme280HourMin,temperatureBme280Hour[i]);
    humidityBme280HourAvg += humidityBme280Hour[i];
  }
  pressureBme280HourAvg = pressureBme280HourAvg/counterLoop;
  temperatureBme280HourAvg = temperatureBme280HourAvg/counterLoop;
  lightSensorHourAvg = (int)lightSensorHourAvg/counterLoop;

  strcat(postStr, stationId);
  strcat(postStr,"&3="); // chuva hora
  strcat(postStr, dtostrf(rainHour,6,2,charDummy));
  strcat(postStr,"&8=");
  strcat(postStr, dtostrf(temperatureBme280HourAvg,6,2,charDummy));
  strcat(postStr,"&9="); //temperature avg
  strcat(postStr, dtostrf(temperatureBme280HourAvg,6,2,charDummy));
  strcat(postStr,"&10="); //temperature avg
  strcat(postStr, dtostrf(temperatureBme280HourMax,6,2,charDummy));
  strcat(postStr,"&11="); //temperature avg
  strcat(postStr, dtostrf(temperatureBme280HourMin,6,2,charDummy));
  strcat(postStr,"&20=");
  strcat(postStr, dtostrf(pressureBme280HourAvg,10,0,charDummy));
  strcat(postStr,"&22=");
  strcat(postStr, dtostrf(pressureBme280HourMin,10,0,charDummy));
  strcat(postStr,"&101=");
  strcat(postStr, dtostrf(lightSensorHourAvg,6,0,charDummy));
  strcat(postStr,"&time=");
  strcat(postStr, dtostrf(unixtimeEvent,16,0,charDummy));
  strcat(postStr,"&endline=1");
  strcat(postStr, "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
}
int rainCheck(Array8Int slaveData) {
  int pulseChange = slaveData.array[0];
  return pulseChange;
}

2000 lines?  maybe narrow it down...  i'd appreciate some help with the stack -> does it point to line 243 or 1472 as last executed?  tks @Juraj

at least the code around setPostString(int, int, Array8Int, char*) at /home/tony/Arduino/sketches/tempo1_vs11e_Master_NodeMCU_Rain_Wind/tempo1_vs11e_Master_NodeMCU_Rain_Wind.ino line 516

Lescanne, you are a life saver! It works!

Fatal exception 9(LoadStoreAlignmentCause):

This is caused by you (or some code you are running) attempting to read or write a 32 bit value from memory that is not "aligned" to 32 bits.  It is most often the result of trying to cast portions of a byte array (for instance a buffer received over UDP) to a 32-bit integer.  The compiler is not clever enough to know that the byte array portion you are casting isn't at a 32-bit boundary and thus doesn't know to use the 8-bit load/store instructions to access the memory.
Mapping a struct over a buffer can also have similar issues where the buffer is 8-bit aligned and the struct contains 32-bit words.
You can combat it by forcing the alignment of any buffers which you treat in such a way with the __attribute__((aligned(4)) tag:
uint8_t __attribute__((aligned(4))) buffer[128];

You can also "pack" structures to tell the compiler "These variables are mis-aligned and should not be padded to 32-bits":
struct foo {
    uint8_t bar1;
    uint32_t bar2;
} __attribute__((packed));

If in doubt, though, just pull individual bytes out of buffers (or wherever) and build up your larger integers manually with bit shifting and OR operators (<< and |), and do the reverse for filling byte buffers.

yes, i am passing a struct.  will attempt these solutions and get back here to ACCEPT or not.  UPVOTED  :)

edited in code above, AFTER you pointed the culprit out.  Good job!

I had this error including on new cards
it worked on one card and not on another
the reason is that my eeprom was not initialized
the nodemcu 8266 that was working properly, was the one I used for development. Because i was using test to write on my eeprom so the value was put in it.
I did not understand what append After, I try flashing reload original setup etc...
I read your answer and I pass this program (which is a stupid manual writing of my eeprom)
I make it running once
and after that
I could load my other programs without problems

    #include <EEPROM.h>
struct credential {
  char WIFI_SSID [39] = " ";
  char WIFI_PASSWORD [39] = " ";
  char SMTP_HOST[44] = " ";
  uint16_t SMTP_PORT = 465;
  char AUTHOR_EMAIL[39] = " ";
  char AUTHOR_PASSWORD[39] = " ";
  char RECIPIENT_EMAIL[39] = " ";
  uint16_t  NbOfProbe = 1; //number of probe 1-to 16
  char TypeOfDevice[16] = "f";// F or f fridge R freezer O hot  exemple fRoFRr
  char AlertMin [54] = "30";//with always a sign like-10+0+2 the sign act like a separator
  char AlertMax [54] = "38";//with always a sign like-10+0+2 the sign act like a separator
  uint16_t  NbOfMinNormMail = 60 ;//time to wait in sec between 2 normal messages eg 14400 sec(4 hours)
  uint16_t  PowerOffMinWait = 1 ;
  uint16_t  TempOffLimitWait = 1;
  char AlertPowerMsg[41] = "alerte coupure de courant "; //Message alerte coupure de courant
  char AlertTempMsg[41] = "alerte temperature hors limite";
  char NormalTempMsg[41] = "Tout est ok ";
  char DateMsg[16] = "vide";
};
typedef struct credential settingcredent;
settingcredent parametersEeprom;
uint addr = 0;
void setup()
{
  Serial.begin(115200);
delay (100);
/*
  // fake data
  struct {
    uint val = 0;
    char str[20] = "";
  } data;
*/
  // commit 512 bytes of ESP8266 flash (for "EEPROM" emulation)
  // this step actually loads the content (512 bytes) of flash into
  // a 512-byte-array cache in RAM
 //                                                                          EEPROM.begin(512);

  // read bytes (i.e. sizeof(data) from "EEPROM"),
  // in reality, reads from byte-array cache
  // cast bytes into structure called data
 //
 showeprom ();

  strncpy(parametersEeprom.WIFI_SSID,"myssid",39);
  strncpy(parametersEeprom.WIFI_PASSWORD,"passmyssid",39);
  strncpy(parametersEeprom.SMTP_HOST,"smtp.gmail.com",44);
  parametersEeprom.SMTP_PORT=465;
  strncpy(parametersEeprom.AUTHOR_EMAIL,"iottest@gmail.com",39);
  strncpy(parametersEeprom.AUTHOR_PASSWORD,"iottest01",39);
  strncpy(parametersEeprom.RECIPIENT_EMAIL,"johndoe@hotmail.fr",39);
  parametersEeprom.NbOfProbe = 4; //number of probe 1-to 16
  strncpy(parametersEeprom.TypeOfDevice,"rffo",16);// F or f fridge R freezer O hot  exemple fRoFRr
  strncpy(parametersEeprom.AlertMin,"-20+0+2+23",54);//with always a sign like-10+0+2 the sign act like a separator
  strncpy(parametersEeprom.AlertMax,"-15+5+7+28",54);//with always a sign like-10+0+2 the sign act like a separator
  parametersEeprom.NbOfMinNormMail = 60 ;//time to wait in sec between 2 normal messages eg 14400 sec(4 hours)
  parametersEeprom.PowerOffMinWait = 10 ;
  parametersEeprom.TempOffLimitWait = 20;
  strncpy(parametersEeprom.AlertPowerMsg,"alerte coupure de courant ",41); //Message alerte coupure de courant
  strncpy(parametersEeprom.AlertTempMsg, "alerte temperature hors limite",41);
  strncpy(parametersEeprom.NormalTempMsg, "Tout est ok ",41);
  strncpy(parametersEeprom.DateMsg,"vide",16);
  EEPROM.put(addr, parametersEeprom);
  EEPROM.commit();

  EEPROM.get(addr,parametersEeprom);
  Serial.println("New values are: "+String(parametersEeprom.WIFI_PASSWORD)+","+String(parametersEeprom.WIFI_SSID)+","+String(parametersEeprom.SMTP_HOST));
}
void showeprom ()
{
  EEPROM.begin(sizeof(parametersEeprom));
  EEPROM.get(addr, parametersEeprom); //read data from array in ram and cast it into struct called parametersEeprom

  Serial.println("-------------------------"); //Showing the details
  Serial.print("your SSID ="); Serial.println( parametersEeprom.WIFI_SSID);
  Serial.print("your password for SSID ="); Serial.println( parametersEeprom.WIFI_PASSWORD);
  Serial.print("your SMTP_HOST ="); Serial.println( parametersEeprom.SMTP_HOST);
  Serial.print("your SMTP_PORT ="); Serial.println( parametersEeprom.SMTP_PORT);
  Serial.print("Your less secure email="); Serial.println( parametersEeprom.AUTHOR_EMAIL);
  Serial.print("Your password for not secure email="); Serial.println( parametersEeprom.AUTHOR_PASSWORD);
  Serial.print("Your email that must receive msg like MeTheBoss@MyCompany.com="); Serial.println( parametersEeprom.RECIPIENT_EMAIL);
  Serial.print("The number of thermometers probe you have is ="); Serial.println( parametersEeprom.NbOfProbe);
  Serial.print("Enter in order type of device (F)ridge f(R)ezzer (O)ven like RFFO="); Serial.println( parametersEeprom.TypeOfDevice);
  Serial.print("Enter mintemp in order per device like(suppose RFFO) -22-1+5+180="); Serial.println( parametersEeprom.AlertMin);
  Serial.print("Enter maxtemp in order per device like(suppose RFFO) -16+4+10+220="); Serial.println( parametersEeprom.AlertMax);
  Serial.print("Number of sec between 2 normal mails like(4hours) 240 ="); Serial.println( parametersEeprom.NbOfMinNormMail);
  Serial.print("Number of sec to wait before sending message Power off like 5 ="); Serial.println( parametersEeprom.PowerOffMinWait);
  Serial.print("Number of sec to wait before sending message warning temp like 5 ="); Serial.println( parametersEeprom.TempOffLimitWait);
  Serial.print("Message power down(30 char) like WARNING POWER OFF GRID="); Serial.println( parametersEeprom.AlertPowerMsg);
  Serial.print("Message temperature off min/max(30 char) like WARNING TEMPERATURE ABNORMAL="); Serial.println( parametersEeprom.AlertTempMsg);
  Serial.print("Message report state of all fridges freezer Oven like Everything is OK in the kitchen ="); Serial.println( parametersEeprom.NormalTempMsg);
  Serial.print("Enter date of the modif parameters like 08/23/21-18:25="); Serial.println( parametersEeprom.DateMsg);

}
void loop()
{
  delay(10000);
  showeprom ();

}

~
~

I hope that this experiment can be usefull
I cannot explain why it work

the eeprom has a limited amount of writes, around 100K


text:
NodeMCU Exception 28 - intermitent problem
I am SOMETIMES getting exception 28 when running a web upload (over a very unstable rural internet CPE link - wifi is fine, but feed goes on and off):
Decoding stack results
0x40213b8c: dns_gethostbyname at core/dns.c line 1472
0x40204d95: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
0x40208d7c: HardwareSerial::write(unsigned char const*, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/HardwareSerial.h line 159
0x4020519c: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
0x40208fe0: Print::println(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 190
0x402040c4: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 360
0x40208f41: Print::write(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.h line 60
0x40208f6c: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
0x40204a2b: loop() at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 258
0x402074f0: TwoWire::endTransmission() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/Wire/Wire.cpp line 151
0x40203a04: BH1750_Init(int) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 1121
0x40209d3c: loop_wrapper() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 125

My code at line 360 is
if (client.connect(serverName,80)) {

My current strategy is to keep the wifi connection open all the time.  Should I test for connection before attempting to connect to the server?

Exception 28 is, according to the exception list document:

Access to invalid address

The most common cause is trying to read or write from/to a NULL pointer.
It could be because you have debugging turned on, and that debugging is trying to print something that didn't get returned properly from another function call (the call failed) - most likely looking up a host name (hostByName()) due to your intermittent internet connection.
This may sound counter intuitive, but try turning off debugging to see if that helps reduce the number of crashes.

counterintuitive makes sense.  lemme give a couple of days' benchmarking and I'll get back.  UPVOTED, pending ACCEPTANCE.

didnt solve the issue.  trying lwIP level change to 1.4 as per https://github.com/esp8266/Arduino/issues/4078

that didnt help either...  stumped

@tonygil You should cut your program down to the absolute minimum and add in different parts until it starts failing.

tks.  will do.  will run separate rigs with different levels of complexity.


text:
Using a photo resistor to detect objects of a certain color
I am trying to build a robot that detects cubes of a certain color, and later picks them up.
I was planning to use a camera and process the image, but I was told that Arduino is not capable of image processing.
Now, I was thinking that I could maybe use a photoresistor that is enclosed by a green light filter sheet (so that only the light of a certain color can pass). Thus, if my robot is facing a cube of the color I want, the photoresistor should detect this.
Is this at all possible? I know how filters work in theory, but I have never used one before.
If not, is there another way to try to detect color using an Arduino?

Through a green filter, white, green and yellow look the same.

There are colors sensors like the TCS230 suggested below, but the object has to be near the sensor to work. They don't work for detecting the block more than a few centimeters away.

@Gerben that depends on the optics.  Coupled to a basic looking glass, these sensors could do the trick.

@Nick Heumann , dont forget to award the correct answer checkmark whenever you come to the conclusion that one answer is (the most) correct.  That will make it clear that you have ceased actively looking for a solution, since you havent posted a valid answer.  Cheers and welcome ;)

Use a TCS230 photo sensor and a 6500K light source to color correct your objects.

This hookup will get you started

This sketch, courtesy of Best-Microcontroller-Projects  will get you going.  Read the tutorial and dont forget to calibrate.
//
// Detect colors using TCS230.
//

// Arduino uno pins for control of TCS230
#define TCS320_OE 7
#define TCS320_S0 10
#define TCS320_S1 11
#define TCS320_S2 2
#define TCS320_S3 3
#define TCS320_OUT 4

#define variance 50  // Acceptable detection error 2%.

#define SEL_RED  \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,LOW)
#define SEL_GREEN \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,HIGH)
#define SEL_BLUE \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,HIGH)
#define SEL_CLEAR \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,LOW)

#define TWO_PER \
   digitalWrite(TCS320_S0,LOW);digitalWrite(TCS320_S1,HIGH);

#define debug(a) Serial.println((a));

#define NUMCOL 5

// int RGB[NUMCOL][3]; // Five colors with 3 elements.
// Array of NUMCOL strings len 10. 11 for null.
// char colname[NUMCOL][11];

// Typical values for 2% dividers (set variance to 50).
int RGB[NUMCOL][3]={
   {248,647,393},
   {188,261,265},
   {404,710,546},
   {506,493,304},
   {930,1199,837},
};

char colname[NUMCOL][11]={
"red",
"yellow",
"brown",
"blue",
"black",
};

////////////////////////////////////////////////////////////////
void setup() {

   pinMode(TCS320_OE,OUTPUT);
   pinMode(TCS320_S0,OUTPUT);
   pinMode(TCS320_S1,OUTPUT);
   pinMode(TCS320_S2,OUTPUT);
   pinMode(TCS320_S3,OUTPUT);
   pinMode(TCS320_OUT,INPUT);

   TWO_PER;

   digitalWrite(TCS320_OE,LOW); // On always.

   Serial.begin(115200);
   Serial.println("TCS230 color detector");
}

////////////////////////////////////////////////////////////////
unsigned long get_TCS230_reading(void) {
  unsigned long val;
  noInterrupts();
  val = pulseIn(TCS320_OUT,HIGH,20000); // 2000us=2ms  2Hz min.
  interrupts();
  return val;
}

static int clr,red,green,blue;

////////////////////////////////////////////////////////////////
uint16_t detect(void) {
   unsigned long val;

    SEL_RED;
    red = val = get_TCS230_reading();
    Serial.print("RED: "); Serial.print(val);

    SEL_GREEN;
    green = val = get_TCS230_reading();
    Serial.print(" GREEN: "); Serial.print(val);

    SEL_BLUE;
    blue = val = get_TCS230_reading();
    Serial.print(" BLUE: "); Serial.print(val);

    Serial.print(" \n");
}

////////////////////////////////////////////////////////////////
int withinEQ(int c, int xl, int xh) {
   if (c>=xl && c<=xh) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
// Compare a value to a value and variance.
int compare(int c, int v, int err) {
int xh=v+err, xl=v-err;
   if (withinEQ(c,xl,xh)) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
void loop() {
uint8_t chr,i,fnd;

   if (Serial.available()>0) {

      chr = Serial.read(); // Consume.

      // Find color match.
      detect();
      fnd=0;
      for (i=0;i<NUMCOL;i++) {
     if ( compare(red,RGB[i][0],variance) &&
          compare(green,RGB[i][1],variance) &&
          compare(blue,RGB[i][2],variance)
        ) { // Found
          Serial.print("Col is :");
          Serial.println(colname[i]);
          fnd=1;
          break;
        }
      }
      if (!fnd) Serial.println("NOT Found");
   }
}

Nice theory but since you're facing real-world conditions and not ideal ones, I think you'll have a hard time with this approach. I.e. your cube is likely not the same shade of green that your filter lets through. What about lighting - do you have a neutral white light source? I recommend you take a look at this Arduino RGB Sensing Tutorial using the TCS230 Colour Sensor for a headstart.


text:
Why doesn't data return when I use Sim808 http request
Why is it that when i use this code for http request on DFRobot_sim808 , I get 'fetch over' message, that means that no data is being returned?
char strings:
char http_cmd[] = " HTTP/1.0\r\n"
                        "Host: 5ac80719.ngrok.io\r\n"
                        "\r\n";
char first[] = "GET /index.php?lat=";

char requestion[100];

functions to join them:

void setup() {
  float lat = 32.685362, lon = 48.411512;
  char char_coor[10];

  mySerial.begin(9600);
  Serial.begin(9600);

// Set Http Cmd
  strcpy(requestion,first);
// For Convert latitude float to char
  dtostrf(lat, 4, 6, char_coor);
  strcat(requestion,char_coor);
// For Convert longitude float to char
  dtostrf(lon, 4, 6, char_coor);
  strcat(requestion,"&long=");
  strcat(requestion,char_coor);
  strcat(requestion,http_cmd);

.
.
.

and fetching:
sim808.send(requestion, strlen(requestion)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }

/*
The program stops at above
*/

      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

thanks

OK i mean why no data returned??

perhaps the device is not connected to the internet ... it is your job to do basic troubleshooting and update your question with a description of what you already tried

One problem I can see is the while loop has a break statement in it that "exits" the while loop before printing the data. Removing that break and printing the data out where the break "was" may help. Here's an example of what I'm trying to say:
void setup(){
  Serial.begin(9600);
}

void loop(){

  while(true){
    int ret = 0;
    if(ret <= 0){
      Serial.println("fetch over...");
      // Print out the received data here...
      Serial.print("Recv: ");
      Serial.print(ret);
      break;
    }
  }

}


text:
Arduino Due Atmel IC heats up
When i tried powering the board the Atmel IC heats up and led goes of after a second .the board does not get detected on my IDE software .
1) I have tried out finding the issues with the board and solving for same but the board does not revive .
Issues like voltage regulator gets shorted (Pin 1 and 2) .So initially i have thought that removing voltage regulator would solve the problem but still there is short between pin 1 and 2 of 3.3 voltage regulator.
2) tried removing the capacitors connecting vcc  and gnd but with no success of removing the short.
Could Someone would possibly help me to revive the board and fix for the same .

Maybe it wasn't short in regulator, but in MCU. Try to use the alcohol test (pour 100% ethanol on it and place(s) that evaporates fastest might be the short)

Ok will try it surely


text:
Strings from serial are not equal
In my code I have that string:String code = rs1 + rs2 + rs3; //rs1=034, rs2=000, rs3=017 It means that code = "034000017". But if I run if (code.equals("034000017")) Serial.println("OK"); There is nothing in serial monitor. Here is full code:
String code, rs1, rs2, rs3, readString;
void setup() {
    Serial.begin(9600);
    Serial.println("Serial ready!");
}

void loop() {
    if (Serial.available()) {
        while (Serial.available()) {
          delay(10);
          if (Serial.available() >0) {
            char c = Serial.read();
            readString += c;
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
          }
        }
    }
}

Why do you read just one character and add it to the string then split the string up as if it had at least 9 characters in it? You need to read the entire string first before splitting it.

@Majenko Why one character? I write 034000017 to serial.

No, you write "0" to the serial. Then you write "3" to the serial. Etc.

This may be of use to you: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

@Majenko And how i can fix it?

You need (a) some way of knowing the start and end of your data in the anonymous serial data stream, and (b) some way of reading that data into memory. The link I provided gives a good example.

What's the point in spitting the string and then combing it back again into the same string?

In your code there is a trivial error and a conceptual error.
The trivial error is in line 16, you wrote
rs2 = readString.substring(6, 9); //017

but it should have been
rs3 = readString.substring(6, 9); //017

(3 instead of 2)
The conceptual one is that you do not have to check the string every time; if you know that the string must be 9 chars long, check for it:
void loop() {
    while (Serial.available()) {
        readString += (char)Serial.read();
        if (readString.length() >= 9) {
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
            readString = "";
        }
    }
}

Note that in this code I cleaned up a bit your code, and MOST IMPORTANT I reset the readstring to nothing after the check (otherwise only the first string is accepted)
I left a lot of things as they were (for instance in my opinion using a string in this case is pointless - better use a byte array; or splitting the string in three for joining it again later), since I think this is part of a larger program

This is much closer to being a correct answer.


text:
Voltage and Current and Arduino
I put a LED into 3.3V of the arduino and Ground, and it blew my LED violently, smoke was everyone, the whole half top of the led blew up across my room.
However, when i program the arduino with Pin13 HIGH per say, it will not blow up. Will be lit brightly. (Both using no resistors). However, if I plug mroe stuff in the board, for example, a lcd screen, rotary switches, and pushbuttons for my program, the LED dims to such a low brightness I cannot see.
Why is this? How Do I fix it?
Schematic:

Note, that i am using a mega, and some of it is slightly changed, and LED is being powered from A0 (Or Pin 54 on Mega)

You have pin 13 tied to ground in that schematic. Are you really settling pin 13 to high output? It would be very useful to have the schematic for your actual circuit, not some other circuit which bears some loose resemblance to your circuit ☺

yep this is the circuit i am using, just with addition to the led, and some pin changes. Yes I am plugging 13 to ground according to this schematic, found it suspicious but that is what it said on schematic.

I'm surprised it's still working then. Don't tie high outputs straight to ground. Without seeing the code it's difficult to say what the right thing to do is, but probably just disconnect pin 13 and leave the switches connected to ground.

@MarkSmith does say at the bottom pin 13 stops flutter on the schematic

It also says it's configured as input. Don't set it as output then.

You must use a resistor. See The care and feeding of LEDs

How Do I fix it?

Use a current-limiting resistor.

The question is, that i have more electronics attached to it, and without a resistor it is already dim to the point i can barely see it. Adding a resistor would make it worse, i wont be able to see it at all.

No it won't. Try it.

For one thing, not using a resistor effectively channels almost all available current through your LED. That is taking power from other things that need it. Perhaps if you post a schematic?

You are Right @MarkSmith, however, it dosent improve brightness at all. I can barely see it, just like before.

What value resistor did you use, and what type of LED is it?

Used a yellow diffused led, 500ohm resistor that came with it

“I put a LED into 3.3V of the arduino and Ground, and it blew my LED violently ... the whole half top of the led blew up ...” –

Current through the LED was so high that a tiny interconnect wire blew up.  In typical LEDs, an almost-invisible wire connects from the anode lead frame to the LED chip on the cathode lead frame (at left and right, respectively, on each of the three lead frames pictured below).  That wire acted like a fuse and blew up.  With such a fine wire, it doesn't take particularly much current to pop it.
The diagram below shows how current through an LED increases exponentially as voltage across it rises.  The diagram is from "mikesflightdeck.com LED dimmer" webpage, a page which may be useful in helping you understand why LEDs need series resistors or some other form of current limiting, eg a constant-current circuit.

When an LED is powered by an Arduino port output, the port's internal resistance is enough to limit LED current to non-lethal (to the LED) values.  (However, the port itself may get burned out by delivering current beyond its 40 mA absolute max current rating.)

“However, if I plug more stuff in the board ... the LED dims to such a low brightness ...” –

The stuff being plugged in apparently is drawing enough current to drop the system voltage.  This can happen if your Arduino is powered by a low-power source like a 9-volt transistor-radio battery, or a laptop USB port that can't deliver the 500 mA that a standard USB port is rated at.
If either of those causes is behind the problem, use an external power supply, plugged into the power jack or connected to Vin and Ground.  You can buy suitable “wall-warts” online, or at an electronics store, or quite cheaply at second-hand or thrift shops.
But if neither of those causes is the problem, you may have a clone of an Arduino using substandard parts, and unable to deliver reasonable current through its regulators.  In this case, find a well-regulated 5 V supply to connect between +5V and Ground or to the USB's power pins.  Such supplies are available not only at the aforementioned venues, but also whereever USB phone-chargers are sold, since 5.0 V is what a USB phone-charger should deliver.

Good explanation, but the main point which is missed here is that you MUST use a current-limiting resistor in series with your LED. You are lucky not to have cooked the Arduino, and if you beef up the power supply attempting to stop the dimming, you WILL cook it. Different LEDs need different resistors, but 330R will probably get you started.

so what i dont get is why it is exactly doing this. To my understanding, dosent voltage affect whether or not my led blows?

@MarkSmith, the answer mentions those points.  Paragraph 3 says “LEDs need series resistors or some other form of current limiting” and paragraph 4,  “the port itself may get burned out”

@GeorgeJones, yes, voltage is involved.  As shown in that graph of LED current vs voltage, LED forward current increases exponentially with voltage instead of a linear Ohm's Law increase


text:
New Arduino Motor Shield Short Circuiting my board?
I just got this today, plugged it in my arduino, and the arduino light starts dimming until you cannot see it any more over the course of 5 seconds. The Computer disconnects the arduino when the light is off (Ding Dong Sound). I found pulling the VIN Connector Jumper/Power Jumper will stop the short circuit and work, but that defeats the purpose, as the board wouldn't even powered.
Here is the video:
YouTube
Is the motor board broken? If so in what way? are the wires on the board simply broken? Is it due to bad soldering?(I checked solder, looks fine).
Arduino Model: Arduino UNO by Elegoo
Motor Driver Model: L293D Driver Board
Ebay Listing For Item
(I tried using this with a MEGA also, would short it as well).

Please edit your question to include the name, model number, and a link for the  motor shield.  Otherwise we're just guessing

post is edited.

Does the board work ok if you pull that jumper and supply motor-power externally?  If so, maybe the Uno's power is marginal.  If not, maybe a chip or a capacitor is bad on the shield.  Looks like the chips are socketed, so you could take them out (sequentially) and see if shorting problem goes away.  If one of two LM293's is bad you could still use the other.  But before removing any chips or capacitors, get a really bright LED flashlight and carefully look all over the board for solder splashes, wire fragments, etc

I pulled all the chips out. They all work in the middle slot. The left and right slot will immediately short it, even if I place one

Have you tried it with nothing connected to the board and the jumper removed?  At the end of the day its a $2 board, from what you have described it has a fault and the seller would have a hell of a problem denying it.  Buy another from a different seller and see if you can get this one replaced although it might cost more to send back than its worth.  If you carry on testing it, trying to diagnose the fault you may trash you Arduinos.  Keep the board for spare parts, chances are you'll fry the chips. :)

Yep it's a 2$ chip. The problem is it takes 3 months to ship X_X

George, the flaw with a “all work in the middle slot” test is that the middle socket is wired for a 74HC595 shift register, vs LM293.  Note, for parts list of original Adafruit 74HC595 + 2 LM293 board  board, see Adafruit motor shield, from a 15-page tutorial on this type of board.  Also see Adafruit's mshieldv12schem.png schematic  that may allow you to check your board's wiring

I just checked. All 3 chips are identical. Is that a problem? The markings at the top are all 74HC595

Thanks to @jwpat7, I have discovered that the reason it is not working is that the seller has messed up and sent me 3 of the same chip, 74HC595N. After doing some research, I have purchased the LM293D Chips.

That's really horrible.  Though it's worth noting that the L293, even if you actually got them, isn't a great solution to begin with.  If you are facing down long shipping delays you might want to consider preemptively ordering a more modern solution overall rather than waiting for the L293's only to perhaps be dissappointed by them.  Especially at lower voltages something using a TB6612FNG or similar may be preferable.  Do note also that you really shouldn't be powering your motor drivers from the Arduino's logic supply or regulator.


text:
Arduino Robot won't move
I am building a robot for a school project. I use an Arduino Uno, 2 dc motor's and an Ultra Sonic range measurement module. I want the robot to be autonomous, he has to be able to move around on his own using the Ultra Sonic sensor. Important to mention is that I don't use a MotorShield to control my dc motors. This is my latest version of coding:

#include <Servo.h> //include Servo library
#include <AFMotor.h> //include DC motor Library
#define trigPin 12// define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);

void setup() {
  Serial.begin(9600); // begin serial communitication
  Serial.println("Motor test!");
   pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
  pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
  motor1.setSpeed(105); //set the speed of the motors, between 0-255
    motor2.setSpeed (105);
}

void loop() {

   long duration, distance; // start the scan
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); // delays are required for a succesful sensor operation.
  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10); //this delay is required as well!
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;// convert the distance to centimeters.
  if (distance < 25)/*if there's an obstacle 25 centimers, ahead, do the following: */ {
   Serial.println ("Close Obstacle detected!" );
Serial.println ("Obstacle Details:");
Serial.print ("Distance From Robot is " );
Serial.print ( distance);
Serial.print ( " CM!");// print out the distance in centimeters.

Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
    motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
      motor2.run (BACKWARD);

}
  else {
   Serial.println ("No obstacle detected. going forward");
   delay (15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
    motor2.run(FORWARD);
  }

}

Now I added an ARDUINO MOTOR SHIELD REV3 to control my dc motors. Now the wheels are actually spinning, but after a few turns they stop. I think it is software related, but I am not 100% sure. Also I think I am connecting my motors correct to my motorshield, but don't adress them properly in my code.
And I don't have any clue how to solve this problem.
Can anybody help me with this?

Break it down into parts. Test each part independently. Then you'll know which one is (or ones are) broken. You already have prints in there to tell you what's going on - so what IS going on? Is it detecting obstacles etc?  Please supply a circuit diagram.  Are you attempting to drive motors directly from the Arduino outputs? This will not work, and I would be surprised if it hadn't already cooked your Arduino.

Include a schematic of how you've connected everything and you'll probably get better answers to your questions.

I think your problem is that you connected the positive wire to the 5v pin when it said 5v and not 9v. Also, I am assuming the 6 double AA is in series creating 9v. The thing is, double AA has a lot of amps. I tested it with my multimeter and it has 7 Amps, way to much. What I would do it connect a 9v battery to the voltage in pin-Vin. That pin can take a 9v but not 7 Amps produced by your 6 AA in series. You have 2 dc motors you said.Each is running I am assuming for each of them I notice draw about 1 Amp. 9v will supply enough and be safe. Try connecting a 9v to the Vin pin. I don't think your issue is software related.

Your understanding of the way current is drawn is flawed. A circuit will draw a current - the battery cannot somehow pump a specific current through a circuit.  The short-circuit current produced by six AA batteries is not a useful or meaningful here.

The battery is not drawing, I never said that. The Vin pin is taking in voltage from the battery. Measure the Amps of a 9v and a double AA battery, you will notice a difference. All I am saying is that the 5v outputs power and not input power. Please read what I said again, I think you're misinterpreting what I am saying.

Sean, I read it the same way Mark did. I'm not sure if this is a language issue or if you need to study a little more about what current and Amps mean.Circuits will always follow Ohms law. From this you would know that voltage and resistance determine how much current a circuit will draw from it's source. If the source can't deliver that much current you'll get unreliable or no results. If the source can deliver more current it doesn't force more current into the circuit.

I do know about amps and voltage. I thought I explained good enough, but looks like I did not. The pin he is using is the 5v, not the Vin pin, the Vin pin takes power into the arduino, the 5v supplies power out to a device connected to the arduino. I was also trying to mention that a double AA battery has 7 Amps, I tested it with my multi meter many times. He has a pack, meaning it is wired in series and not parrel. I am saying his circuit is wrong. & amps is to much for the arduino. A 9v supplies about 2 amps. That is max for arduino, so it will be fine. I am considering volts and amps.

Sean, it seems like I wasn't clear enough myself. I use the Vin port for my battery pack. I use a breadboard to make all the wiring. The breadboard itself is connected to the 5V port on my arduino.


text:
Problem sending data from arduino with ESP8266 to a local mysql database
i'm currently trying to send a randomly generated number from Arduino via ESP8266 wifi module to a local mysql database estabilished with xampp, but having a problem with it. Here is my arduino and php receiving code. I should mention that i'm extremely unfamiliar with mysql, php, and the whole server & database things, so any help would be greatly appreciated.
Arduino Code:
#include <ESP8266WiFi.h>

const char* server = "192.168.1.106";
const char* ssid = "DARUSALAM C8";
const char* password = "asro4520";
const char* SensorID = "ESP001";

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);

  WiFi.begin(ssid, password);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi Connected");
}

void loop() {
float n = random(300);

Serial.print("Random Number: ");
Serial.println(n);

  if (client.connect(server,80)) {
    Serial.print("Posting data...");
    digitalWrite(BUILTIN_LED, LOW);
    Serial.println("Random Number: " + String(n));
    client.println("GET /log.php?n=" + String(n));
    client.println("HOST: ");
    client.println(server);
    client.println("Connection: close");
    client.println();

    client.stop();
    Serial.println();

    digitalWrite(BUILTIN_LED, HIGH);
  }

  delay(5000);
}

PHP code:
<?php

$db_amb = mysqli_connect("127.0.0.1", "root", "", "wemos");
if (!$db_amb) die("Gagal terkoneksi ke DB Utama. Error : " . mysqli_connect_error());

$n = $_REQUEST['n'];
if (!empty($n) &&)
{
  $s = "insert into data_random set value1='$n'";
  $r = mysqli_query($db_amb, $s);
  echo "OK";
}
else echo "ERR";
?>;

The database is named 'wemos', and the table where i intend to store the data is named 'data_random' with 4 columns named value1-value4. My intentions is to store the random number to the 'value1' field.
EDIT the problem i encountered is whenever i checked http://localhost/log.php this appears:
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\log.php on line 7

i have tried modifying the syntax in numerous ways but the problem presist. I suspect my code may have some underlying fundamental problem that is not syntax related, but i can't tell due to my lack of experience. Again, any help/clue is greatly appreciated. Thank you very much

What sort of a problem? (Please edit the answer into the question.)

The HOST should not have a newline after it, so you should have
client.print("HOST: ");
client.println(server);

In addition your PHP looks dodgy to me.  I'm not very familiar with PHP at all, but I think the &s here are left over from something you have removed, and causing syntax errors - just remove them
if (!empty($n) &&)

I believe your n parameter is going to be in _GET (not _REQUEST).  Also, you should check whether it's there, not just assume it is, so:
if isset ( $_GET["n"] )
{
    $n = $_GET["n"];
    // Do your database stuff here
}

(You should find the PHP log (where depends on what OS your server is running on) and I think it would point you straight to this problem.  No point trying to debug it blind.)

First of all thank you for cleaning up my mess. Due to your suggestion i have removed the newline after  HOST. Yes, i also suspect that the &s is what causing the syntax error because you are also correct in that i only edited someone else's program i found from browsing the internet. but now when i checked the local host i got Notice: Undefined index: n in C:\xampp\htdocs\log.php on line 6 ERR;. I installed xampp in windows 10, can you point out the PHP log location? thank you very much

I don't understand what you mean by "checked the local host". I don't know the location of the PHP log in Windows, sorry, but I think I've seen another the mistake in your code - answer ammended.

The $_REQUEST super global should work just fine. It contains the contents _GET, _POST, and _COOKIE. http://php.net/manual/en/reserved.variables.request.php.

You will get the index not defined error if you load the page in your browsers with out the "?n=" part. So to test the script in your browser use: http://localhost/log.php?n=123


text:
Dynamically control the output voltage of a 60V DC input
I am hoping to control a 60V DC input source dynamically using my Arduino so that the output voltage could vary between 0v to 60v. At first i was looking into digital potential meter, however I couldn't find any digital pot that can support 60V DC input voltage.
I have came across a few articles with similar situation (but theirs with lower voltage).
Could anyone suggest any solution to my problem?
Thanks. Any help is much appreciated.

You could use a 5V digital pot, or a 5V DAC. Then feed that through an OpAmp to convert the 0-5V to a 0-60V output.

@Gerben could you guide me on how to design /which kind of opAmp that can step up from 5v to 60v? I tried googling but none of them step up from 5 to 60. Thanks in advance

Try asking at https://electronics.stackexchange.com/ . This isn't really my area of expertise.

Does your voltage source just have to output a voltage or does it need to drive any significant current (i.e. do you want to use it as a power supply)? BTW please be careful with these relatively high voltages. They can easily damage your Arduino and can be very unpleasant to touch.

@StarCat thank you for your comment, i am looking at a current around/less than 0.1 A

Try ZMPT101B. Easy to use and very cheap
Active Single Phase Voltage Transformer Module AC Output Voltage Sensor for Arduino Mega ZMPT101B 2mA

Can this be used to control output voltage real time?

I don't see how this answers the question. This module does not do what @jetjetboi wants. I would also advise against buying a random module off aliexpress with no documentation.


text:
Xbee S2 API Data Packets dropping out
I made a setup which consists of 3 Zigbee's, 2 routers(Zigbee S2C's) and 1 coordinator(Zigbee S2). The routers are each connected to arduino nano which collects data from 2 FSR's and an IMU(frame type: zigbee transmit request and packet size 46 bytes) and sends it to the Coordinator attached to an arduino UNO. All the Xbees are in API mode 2 and working at a baud rate of 115200. I am using a library called "Simple Zigbee Library" to send all the collected data to the Coordinator. The collection and sending of data works fine except that there are packets lost in the way. The nano's sample data at a frequency of around 25Hz independently. The coordinator tries to read the data send from the zigbees(using the library of course) in every loop, but unfortunately, it seems to receive only around 40-45 samples.(Should have been 25*2=50 samples total from the 2 xbees). Can anybody suggest why this is happening. I need as less data loss as possible for my setup to achieve its motive. Any kind of help is appreciated.
P.S: It may be important to mention that the coordinator is reading the data only from one xbee in each loop.
[[As can be seen from the "Source" heading in this image of data received by the coordinator, "19" and "106" are addresses of the routers. Data drop is intermittent]]1
    void setup()
{
// Start the serial ports ...
Serial.begin( 9600 );
while( !Serial ){;}  // Wait for serial port (for Leonardo only).
xbeeSerial.begin( 9600 );
// ... and set the serial port for the XBee radio.
xbee.setSerial( xbeeSerial );
// Set a non-zero frame id to receive Status packets.
xbee.setAcknowledgement(true);
}

void loop()
{
// Each SimpleZigBeeRadio instance contains two
// SimpleZigBeePacket instances, one for storing incoming
// messages and one for preparing outgoing messages.
// This example will not send any messages to the network.
// Rather, the coordinator will receive messages and display
// the contents to the hardware serial port.

// While data is waiting in the XBee serial port ...
while( xbee.available() )
{
// ... read the data.
xbee.read();
// If a complete message is available, display the contents
if( xbee.isComplete() ){
Serial.print("\nIncoming Message: ");
printPacket( xbee.getIncomingPacketObject() );

}
}

delay(10); // Small delay for stability
// That's it! The coordinator is ready to go.
}

 // Function for printing the complete contents of a packet //

void printPacket(SimpleZigBeePacket & p)
{
Serial.print( START, HEX );
Serial.print(' ');
Serial.print( p.getLengthMSB(), HEX );
Serial.print(' ');
Serial.print( p.getLengthLSB(), HEX );
Serial.print(' ');
// Frame Type and Frame ID are stored in Frame Data
uint8_t checksum = 0;
for( int i=0; i<p.getFrameLength(); i++){
Serial.print( p.getFrameData(i), HEX );
Serial.print(' ');
checksum += p.getFrameData(i);
}
// Calculate checksum based on summation of frame bytes
checksum = 0xff - checksum;
Serial.print(checksum, HEX );
Serial.println();
}

If transmits aren't coordinated, perhaps CCA,  clear channel assessment, is wasting a bunch of time.  Perhaps have a transmit order, perhaps assign time slots?

I believe using the Xbee in API mode is supposed to take care of that. The routers are getting Acknowledgements from the Coordinator for most of the packets. The packets not acknowledged are getting dropped. I tried to decrease the frame size ,reduce the payload and remove all delays, still the data drop is present. Any kind of help is appreciated.

What happens if you turn off one router and let the other send as fast as it can?  Ie what throughput does it get, does it drop packets, etc

On working just with 1 router, I am not getting packets dropped. The nano is sending  25  packets and all of them are getting received by the UNO.

But try upping the rate of that one router (eg to 30, 40, 50, 60, 70... per second) and see how fast you can run without dropouts.  For example, if it runs ok at 60 or 70 samples/second through 1 router but only 40-45 with 2 then some interference between the two routers might be involved


text:
PWM on non PWM pins
Why does this code not function in a similar way to the example fade sketch?
I have had to resort to using bit-banging as a way to implement PWM onto non PWM pins due to  a lack of available free pins on my Arduino Pro Mini. I am using a sketch that supposedly should fade an LED ranging from maximum brightness to minimum brightness. My code however does not work. Can anyone figure out why my code does not operate in the same way the fade sketch does?
My current code is:
int brightness = 0;
int fadeAmount = 50;
void setup()
{
  pinMode(12, OUTPUT);
}
void loop()
{
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  digitalWrite(13, HIGH);
  delayMicroseconds(brightness); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 100);
}

And I want it to work in the same way as:
int led = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
  pinMode(led, OUTPUT);
}
void loop() {
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  delay(30);
}

If possible could anyone provide a correct version to help me with my project.

You seem to have a typo on the pin number: you are configuring pin 12 and driving pin 13.
In other words: pinMode(12, OUTPUT); and digitalWrite(13, HIGH); do not match.

Your code here is not quite right:
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(1000 - 100);

Your two delays should add up to the total period (wavelength), or the reciprocal of the frequency (scaled to microseconds).
Hence the - 100 in the second delay - that is subtracting the "on" time from the total time to give the "off" time.   It should be replaced with - brightness as such:
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(1000 - brightness);

And of course the brightness is in the range 0 - 1000 not 0 - 255 like analogWrite().  To make it 0-255 you should replace the 1000 with 255, which of course makes it all run at a much higher frequency. (1 / 0.000255 = 3922Hz).
digitalWrite(13, HIGH);
delayMicroseconds(brightness);
digitalWrite(13, LOW);
delayMicroseconds(255 - brightness);

Mind you, all this is not good regardless of your calculations. This is a blocking system in which you are unable to do anything else at all in your program whilst generating PWM.  Instead you should be using a timer (like the tone() command does) and switch between two different time periods each interrupt for "on" and "off" time periods. That way it can function asynchronously ("in the background") like analogWrite() does.

It's not strongly related to your question but i suggest you to use external library as SoftPWM.h
You can find the whole documentation on https://github.com/bhagman/SoftPWM

A more generic version of your approach would be like this.

Set the output pin - don't hardwire the pin number but instead use a macro for it.
Delay for it's duty cycles.
Clear the output pin.
Delay for period - duty cycles used in step 2 above.

You can put that in a routine and call it.
With that said the routine has limited use in a real application as it can drive one output pin and ties up the whole mcu needlessly.
A better approach is to use an interrupt and test for duty cycles in the interrupt . This can drive multiple pins with independent duty cycles. All without tying up the mcu.


text:
What are the benefits or advantages of Arduino CLI?
I saw that Arduino got a CLI (Command Line Interface), and my first question was "why?"  Even after reading the article, I don't see or understand its advantages.
What advantages or benefits does a CLI have for Arduino?
I haven't done much with Arduino in several years.  For example, there wasn't an Arduino SE when I was fooling around with Arduino, so I probably have an out of date context for Arduino development.

If you have to ask what the benefits are then the benefits most likely do not apply to or interest you.

it's for tooling and automation. i've used it to automatically recompile and deploy a sketch after another app updates a "hard-coded" table of IP addresses in the source, based on the results of a network scan.

Simple: you can program the Arduino without needing a GUI.
One good example: You have an Arduino connected to a Raspberry Pi built into a robot. You SSH into the Pi, edit the Arduino's program, and upload the new code. All from wherever you happen to be.
A second example: You can integrate Arduino compilation into your own software. Such as a web interface for compiling your code.  I know of one such project where the creator has made a custom website for editing their robot code and using UECIDE's CLI (which pre-dates Arduino's) to compile and upload the code to the target board.
And yes, you have an outdated context of Arduino development, as evidenced by your use of the phrase "fooling around with". Arduino is not a toy. It's a development platform and educational tool. Maybe back when you were "fooling around" with it, it was little more than a toy, but things have moved on a long long way since then. The Arduino ecosystem boasts boards with chips from every manufacturer you can imagine to fill every niche you can conceive. The API and available libraries have certainly matured.

One huge advantage that probably falls under "You can integrate Arduino compilation into your own software" is continuous integration. For example, you might configure Travis CI to compile your Arduino project every time you push a commit to GitHub. You can already do this using the Arduino IDE's CLI, but that means downloading and extracting many megabytes of GUI application that will never be used for every CI job (and there may be multiple jobs per build). That slows down the build and wastes Arduino and Travis CI's bandwidth. The arduino-cli download is only 5 MB.


text:
RGB LED strip 100m

Hello all,
I'm working on RGB LED strip SMD 5050 5m
This all setup is working on 12v 2A with about diagram.
I want to use same connection with 100m of LED strip using Arduino.
Please support regarding this topic.
H/W details :
Arduino uno
Hc-05 bt module
12v 1.2 amp supply
Td140 pnp transistor
SMD 5050 LED strip 60 LED/m

Where do you want the 100m of wire? Between the PSU and the LEDs? Between the Arduino and the transistors? Between the transistors and the LEDs? Between the Arduino and the bluetooth transceiver?

I want to use 100m LED strip

100m of 60LED/m? i.e. 6000 RGB LEDs or 18000 LEDs?

You cannot drive 100m of LED strip from one side. That would be 200A. Even at only 5m I needed to provide the power at both sites to prevent the strip from getting too hot. So you would have to provide power also every few meters into the strip.

there's a limit to how many LEDs you can address w/WS2812, i don't recall, but it's far less than 6000

100 Meters of 5050 SMD strip LEDs will require roughly 120-200 amps. However, you cannot drive a 100 meter strip from a single power supply. The thin copper traces in the LED strip can only handle so many amps before they become too hot (your LED strip would melt like ice cream on a hot summer day). This is why led strips are usually limited to 5 meters (~5A). You would need separated strips and power supplies for the 100 meters worth.
You have the correct idea with your circuit for turning the leds on/off (in fact the wiring is correct) but the transistors you plan on using are the wrong type. To switch the LEDs to ground you would need a low side switch, which would be a NPN transistor. Be careful however, transistors typically switch currents less than 1 amp. For higher power applications I would suggest using a N-channel Mosfet. A quick search on Sparkfun turns up the FQP30N06L, which is capable of handling 30A (with a heatsink, probably less than half without), and is also logic-level, meaning it can be driven with a 5 volt source (Arduino I/O pin).
Keep in mind, whatever current your LED strip draws, the ground switch (NPN transistor, N-Channel MOSFET, relay) must be able to handle the same current.
Good luck with your circuit!


text:
unexpected change of ADC value with multiple voltage dividers (thermistors and pot)
So this is my basic circuit. Three voltage dividers: one 10k pot, 2 thermistors. Fan driver circuit using TIP120 (currently just driving an LED from the 3.3v source). Board is a Leonardo clone, circuits.io only had the Uno in their library. Edit: circuit is now more simplified.
Schematic:

reality:

When I adjust the pot, the ADC value of airPinValue changes, regardless of which analog input it is connected to. meatPinValue does not change. Swapping the inputs that airTempPin and meatTempPin are assigned to has no effect, airTempPin changes the same. Physically swapping the thermistors has no effect, nor does switching which input they connect to.
Code:
#define potPin A0
#define airTempPin A5

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  potValue = analogRead(potPin);
  airPinValue = analogRead(airTempPin);
  if (i == 2000) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

EDIT: much simplified code
EDIT v2.0 : I have now swapped out the board for an official Uno, as well as swapped everything to a different breadboard and a different Leonardo, with no change in behavior.
EDIT v3 : Corrected code sample. I have also dropped my DMM onto this, reading from the 5v rail to the voltage going to A2. With the pot set to 0 I see 2.401v from the divider, pot to max, same voltage, 2.401v.
EDIT v4: with only the pot and airTemp hooked up, still happens. Further DMM probing actually shows that this only happens when the pot and thermistor are both hooked up to the arduino. If either one is disconnected, the voltage being read by airTempPin is stable/correct. Once both are hooked up to the analog pins on the arduino, that's when the voltage at airTempPin goes off...
Also update diagram, pic, and code to match what I'm currently testing with.
EDIT v5 : This is some sort of analog bleed between the analog input ports. Not really sure how I can combat this :\

if pin A1 is left floating like the schematic and used like in the code, any noise will alter it's value. Use A2 in code and it should work.

sorry, that was a copy/pasta problem. As stated in in the question, I've tried using different analog pins to see if the behavior was the same, and it doesn't change when reading from A0 or A2 (and move the physical connection to that pin too)

What do they change to?  Can you swap a pot for airPinThermistor?  maybe simplify the println(String()+String()+...) into separate lines without the string concatenation magic?

Also, did you try swapping the order of analogRead()s? If it is a sample-hold problem from the prior read, this might help identify it.  You could jumper A5 to GND or +5, and intersperse a analogRead(A5) too.

0,459,484
457,482,484
1023,515,484``` - oh, apparently can't have linebreaks in comments. This is a small sample showing the values of the pins

oh, that sample was without the String conversion and concatenation, I'll update the code sample

take a look at Edit v4

Moral of the story, the multiplexer was not switching between inputs quickly enough causing the odd reading, looking very much like bleed between the pins. By simply reading each analog input twice and only storing the value of the second reading, I was able to get a valid, stable, reading as expected.
#define potPin A4
#define airTempPin A0

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  analogRead(potPin);
  potValue = analogRead(potPin);
  analogRead(airTempPin);
  airPinValue = analogRead(airTempPin);
  delay(10);
  if (i == 50) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

How resistive are your thermistors?  I think I saw if they were on the order of 10K, they can switch pretty fast, but if lots higher, it takes more time to slew.  Maybe adding a cap to buffer/hold the thermistor signal would be good too.

They're 220k-ish, and pretty slow to change (might update to RTDs in the future, but these work for now). My supply of caps is a bit low right now, got an order of a bunch from China arriving next week.

5V/220k=22uA, which isn't a lot to fill up the sampling capacitor (14pF on the ATMega32u4 I'm used to).  The https://www.embeddedrelated.com/showarticle/110.php recommends a cap of about 1000x the sampling capacitor, or 14nF or so.

Good to know. Would I just drop that between the return leg from my thermistor and the analog pin, or parallel with the 220k resistor to ground?

R1 is a 220K? Put the hold cap between the R1 +Rtherm junction and GND.   It will charge all the time, and only discharge into the ADC sampling cap when sampled.

#define meatTempPin A0
#define airTempPin A1

Your code says A0,A1 but the circuit and picture of the wires say A0,A2.
Since A1 doesn't appear to be connected, as you scan things, the ADC could be sampling and holding some voltage from the prior conversion of potPin.
Try this instead:
#define meatTempPin A0
#define airTempPin A2

beat me by 5 secs, good work!

sorry, that was a copy/pasta problem. As stated in in the question, I've tried using different analog pins to see if the behavior was the same, and it doesn't change when reading from A0 or A2 (and move the physical connection to that pin too)

This is sort of a common problem with open-circuited analog inputs.  When you are doing your swapping of wires and pins, could one of the jumpers or one of the breadboard connections be open-circuit?

You need to have a reference voltage for ADC the problem is that you are not setting the reference voltage for ADC.Change the code in setup where you add a analog reference voltage as internal or default according to your requirement.

This is kind of a vague answer. Please consider editing it to add some example code to demonstrate exactly what you're talking about.

https://www.arduino.cc/en/main/arduinoBoardUno

Vin. The input voltage to the Arduino/Genuino board when it's using an
  external power source (as opposed to 5 volts from the USB connection
  or other regulated power source). You can supply voltage through this
  pin, or, if supplying voltage via the power jack, access it through
  this pin.

Thisi not to be used as powersource for motor/LED whatever, this is input.
Use 5V instead, maybe this would solve the problem.

or, if supplying voltage via the power jack, access it through this pin.

Aside from that, even with it disconnected, the behavior is the same.


text:
How can I alter my program to read PWM signals from Arduino Mega?
I am new to programming and Arduinos but I've decided to give a go for a project. I'm after a code that will read PWM signals from a RC receiver (Specifically aileron and throttle) and output this as 4 PWM signals to drive two H Bridges (Right motor forward/reverse and left motor forward/reverse).
This is my code that isn't working.
unsigned long timer[3];
byte last_channel[2];
int throttle;
int aileron;

void setup() {
pinMode(8, OUTPUT);//Right motor fowards
pinMode(9, OUTPUT);//Right motor reverse
pinMode(10, OUTPUT);//left motor fowards
pinMode(11, OUTPUT);//left motor reverse

PCICR |= (1 << PCIE0);  //This enables pin change intterupt enabler

PCMSK0 |= (1 << PCINT0); // This tells the mask register
which pins will cause an intterupt (Pin 2)

PCMSK0 |= (1 << PCINT1); // (Pin 3)

Serial.begin(9600); //Sets the data rate in bits per second
}

void loop() {

}
ISR(PCINT0_vect) {

timer[0] = micros(); // registers intterupt time

//Throttle_Channel----------------------------------------------------------

if(last_channel[0] == 0 && PINB & B00000001 ) { // This checks if pin has
changed from low to high

last_channel[0] = 1;

timer[1] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000001)){

last_channel[0] = 0;

throttle = timer[0] - timer[1]; //calculates the change in time and sets to

input[0]
//--------------------------------------------------------------------------
}
//Aileron_Channel-----------------------------------------------------------

if(last_channel[1] == 0 && PINB & B00000010 ) { // This checks if pin has

changed from low to high

last_channel[1] = 1;

timer[2] = timer[0];
}

else if(last_channel[0] == 1 && !(PINB & B00000010)){ //This checks if pin  has

changed from high to low

last_channel[1] = 0;

aileron = timer[0] - timer[2]; //calculates the change in time and sets to i

input[0]
//--------------------------------------------------------------------------
}

//Calculations to put output in correct form--------------------------------
int throttle_pwm = (throttle - 1500) / 1000;

int aileron_pwm = (aileron - 1500) / 1000;

int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;

int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;

int lm = v + (w/2) * 255;

int rm = v - (w/2) * 255;
//--------------------------------------------------------------------------

if (lm > 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm > 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,lm);

analogWrite(11,0);
}

else if (lm <= 0 && rm > 0){

analogWrite(8,rm);

analogWrite(9,0);

analogWrite(10,0);

analogWrite(11,abs(lm));

}

else if (lm <= 0 && rm <= 0){

analogWrite(8,0);

analogWrite(9,abs(rm));

analogWrite(10,0);

analogWrite(11,abs(lm));

//--------------------------------------------------------------------------
}
}

It compiles fine but I've tried measure PWM at the four output and it doesn't work. If anyone could offer advice or guidance it would be greatly appreciated.

It'd be really helpful if you could reformat your title ("What's wrong with my code" doesn't really tell us anything about the problem) and reformat the post so the code is easier to read. I believe four spaces on each line will format it in the "coding" format.

Thanks for the advice I've made the suggested layout edit. :)

If this is an RC controller, have you considered using a serial data protocol, like SPI over ZigBee? PWM signals are great for power control to analog devices, but when you have two microcontrollers communicating, a serial protocol would probably be better.

It looks like the code in the ISR is slow and it may compute incorrect results.
It is slow because of using floating point arithmetic in throttle_pwm and aileron_pwm calculations.  It may be so slow that the trailing edge of a PWM pulse occurs while the leading edge still is being processed.  This will delay trailing edge processing, and mis-measurement of pulse lengths.
The main thing to do to reduce the amount of code executed in the ISR is separate the input measuring phase from the output actuating phase.  You could compute pulse widths and store them in volatile variables for a loop in main to pick up and use in analogWrite() statements there.

Note, in 16-bit int arithmetic, the value of expression (t-1500)/1000 is 0 for 500 < t < 2500.   Because throttle and aileron are supposed to be RC pulse lengths in the range 1000 to 2000 μs, your  throttle_pwm and aileron_pwm will be zero.  That means you can replace the following code,
int throttle_pwm = (throttle - 1500) / 1000;
int aileron_pwm = (aileron - 1500) / 1000;
int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;
int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;
int lm = v + (w/2) * 255;
int rm = v - (w/2) * 255;

with this code:
int throttle_pwm=0, aileron_pwm=0, v=0, w=0, lm=0, rm=0;

which should save you several milliseconds of computation!  Also, having lm and rm as constant zeroes means that you don't need all those lengthy and laborious if and else blocks.   You can replace those 24 lines of stuff with just the following:
analogWrite(8,0);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(11,0);

Slightly more seriously, it looks like you intended for your arithmetic like (throttle - 1500) / 1000, etc. to determine whether to raise or lower the throttle, etc.   Instead of doing that time-consuming division, just say:
int throttle_pwm = throttle > 1500 ? 1 : -1;  // or whatever values you meant to have
int aileron_pwm = aileron > 1500 ? 1 : -1;    // ditto

Instead of all those 24 lines of stuff, just say:
analogWrite(8,  (rm>0) * Level);
analogWrite(9,  (rm<=0)* Level);
analogWrite(10, (lm>0) * Level);
analogWrite(11, (lm<=0)* Level);

where Level is some level you want to set the control to.  Note, an expression like (rm>0) has a value 1 when it is true and and 0 when it is false.  So when rm>0, you have, in effect, analogWrite(8,Level); and analogWrite(9,0);.
If instead you end up with a calculation where lm and rm are actually usable PWM levels, ie numbers from 0 to 255, you could instead say:
analogWrite(8,   (rm>0) * rm);
analogWrite(9,  -(rm<=0)* rm);
analogWrite(10,  (lm>0) * lm);
analogWrite(11, -(lm<=0)* lm);

or could say:
analogWrite(8,  rm>0  ?  rm : 0);
analogWrite(9,  rm<=0 ? -rm : 0);
analogWrite(10, lm>0  ?  lm : 0);
analogWrite(11, lm<=0 ? -lm : 0);

Also see my answer to the question  Read RC receiver channels using Interrupt instead of PulseIn and see my answer to the question  Arduino read PWM duty cycle value with input (analog / digital).

If you are trying to read a PWM signal, you should try using the pulseIn function, which reads the length of a pulse signal.

See my page about interrupts. Data to be shared between an ISR and the main code should be declared volatile which yours isn't.

Also see:
https://www.arduino.cc/en/Reference/softwareSerial

Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

It's not really clear from your post which pins you are using for the encoder, but you mention pins 2 and 3:

PCMSK0 |= (1 << PCINT0); // (Pin 2)
PCMSK0 |= (1 << PCINT1); // (Pin 3)

Pins 2 and 3 on the board are not PCINT0 and PCINT1. Also they are not in the list of supported pin-change interrupt pins.
You might be better off using external interrupts (see my page above). External interrupts are supported on pin 2 and 3. However your code needs to change a bit.

authors: николай мягких