text:
Bootloader fails when two Arduinos are connected over serial port
I’d like to connect two Arduinos over serial port so that they can communicate with each other. Initially, I put all necessary code onto one device and now connected another via serial port. As soon as I connected the second one I lost the ability to upload new code onto the first one. I’m certain they are conflicting over serial pins. I tried to hold reset on the second Arduino, but it didn’t help. The only way to flash it back again with avrdude is to disconnect the second one.
Is there a way to get this setup working with serial bootloader without disconnecting pins? Thanks for your ideas.
I do not use the Arduino IDE. I believe that if someone has a solution for Arduino it will work for me. I use Atmel Studio 7 with avr gcc. The boards are Chinese clones with ATMega328P on them flashed with the optiboot bootloader. Pins connected are TxD and RxD to opposites on the second board. They are powered from the same power supply. This question is not how to communicate with another Arduino. This question is how to still be able to flash one Arduino while something else is connected to its serial port. I know that the USB to serial bridge IC is connected, but this is a standard setup on all Arduinos that have no embedded USB controller.
Board is Arduino Nano v3 clone with CH340 USB<->UART chip. Both boards work OK by themselves, once connected together they stop responding to avrdude. The connection is as following. Length of connection is only 15cm.
Nano v3 (1)        |          Nano v3 (2)
    |              |              |
RX0 o-----+------~ ~ ~------+-----o TX1
    |     |        |        |     |
TX1 o---+-|------~ ~ ~------|-+---o RX0
    |   | |        |        | |   |
      --o-o--      |      --o-o--
       CH340       |       CH340
         ^         |         ^
         |         |         |
        USB        |        USB

Which Arduino boards do you use, and which pins did you connect? Do you want to upload a sketch while the two Arduino boards are connected? Did you also connect the grounds? Please update your question with the extra information. The Atmega328p has only one serial port, and that is used to upload a sketch and for the serial monitor. How much data do you want to transfer between the Arduino boards?

Could you give a link to that clone board please. Do you have a schematic of that clone board? Is it a Arduino Pro Mini clone? Holding reset on the second board should help, so it must be something else in the circuit or wiring or perhaps a cable that is too long (the bootloader has its own baudrate).

Truly holding reset should work, but beware that the traditional UART header on the end of the board doesn't have true reset input, but just a path through a capacitor to momentarily blip reset via a serial control signal.  It's also possibly you have TX/RX backwards for the board you are targeting, or that you've failed to accomplish a timely reset of the target.

Now we know that it is a Arduino Nano board. That board has a usb-serial chip on the board. Those are also connected to rx and tx. One signal line has rx of one CH340G connected and the tx of the other CH340G chip and the other line has also a rx and a tx of a CH340G. I think that the tx of the unused CH340G is the problem. The Arduino (Pro) Micro has a spare serial port, so do the Arduino Zero and Due and the Arduino Mega 2560. I2C is possible. You could perhaps use 4 wires and create your own asynchroon communication with handshake. Why do you need two Arduino boards in the first place?

@Jot I think you're right. I have no issues with just rx pin connected from second board. Once I connect 'tx' pin it fails. tx pin of the second board has some potential, which I think confuses first CH340G. I reset both boards, but keep holding reset on the second board, and I was able to upload HEX file onto the first one.


text:
Arduino FM transmitter
I am wondering if it's possible to transmit on all frequencies at once using this module.
I know it's illegal to take over regular stations when others are trying to listen but I'm only planning to use it for short range (less than the length of my house).

No, this is a receiver only, not a transmitter.

I am wondering if it's possible to transmit on all frequencies at once using this module.

it is definitely possible to transmit on all frequencies at once NOT using that module: square waves are a combination of all sorts of frequencies and your arduino is good at producing that.

source: Stack Exchange

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

sort: votes


text:
Why is my DHT22 sensor reading 1.00% humidity?
I have a seemingly simple problem but I haven't found a solution yet. I recently got a DHT22 temp/humidity sensor and I wired it according to the guide from Adafruit.
I downloaded and installed the library. I loaded the "DHTtester" example sketch. I also included the Adafruit Unified Sensor library to be safe, because the guide said I might need to. But when I upload the sketch and check the serial monitor the humidity value is always "1.00%". The temperature also seems to be off by about 4 degrees F.
I don't know what is going wrong here. I've removed the 10K resistor but nothing changed. Does anyone know why this might be happening? Any help would be appreciated. Thanks!

Without a diagram of your setup, and the code you're using, this is akin to reading tarot cards...

My setup is exactly the same as the one in the guide that I linked to. I'm using an Arduino Uno. First pin on the DHT22 is connected to 5V, second to 5V with a 10K resistor to digital pin 2, and fourth to GND.

Then barring a mistake in the code or setup, it might probably a hardware issue -- have you tried your DHT on another board?

This problem mainly happens when DHT11 sensor is mistaken with DHT22 or vice versa. Try testing it for DHT11, can you send the picture of sensor and circuit connection if possible.

Definitely the DHT22, but I tried uncommenting different sensors anyway, and the readings were wrong.

I have 2 suggestions for you.

If you compare these 2 data sheets:
This one says "adafruit learning systems" on it
and this one is from the Adafruit website
, you'll see there is a discrepancy regarding the pull-up resistor value to use. One document says 10k ohm, the other says 1k ohm. It's a bit of a long shot, but you could try adding another 10k ohm resistor in parallel with the one you already have on the data line. This gives you an equivalent resistance of 5k ohm which works when used on a DHT11 sensor (cheaper, less accurate version of the DHT22).
There are several versions of the DHTxx library out there, so my next suggestion is to try a different one. You may have to remove the library you currently have installed before trying a new one.

I tried different resistors but humidity is still at 1.00%.The weird thing is that temperature is accurate, which makes me think that the humidity sensor is defective or broken.

After a year hanging outside my door in sunny/rainy/windy conditions my DHT22 gave up and shows 1%RH all the time. I don't recommend using it just like that. I have opened it and did some IPA cleaning. It sorted the problem for about a month. If your sensor wasn't stored in good conditions, it may be corroded/contaminated.

When I have rigged up these sensors to test, I breathe on them. Both the temperature and humidity should rise as breath is warm and humid.
From memory, I have seen the humidity rise from ~40% to ~70%, and temperature by at least 5 degrees.
If you see temperature rise but not humidity, then the humidity part may not be working (perhaps as smajli suggests).
There is also a checksum in the data, so I imagine that if there was a problem with communications, the result would be -1 or nothing at at all.

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

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


text:
How do I stop a servo motor at the current position when using a serial port? I want it to remain in one position when receiving "0"
I am working on a project where I would like values received from an Xbox Kinect will activate components on my Arduino. Currently, I am trying to get a servo motor to turn on and rotate when the value is "1" and to remain in one position (currently written as 120degrees) when the value is "0". However, I can turn on the motor and initiate rotation just fine, but when I let go of the mouse (and it shows that the value "0" is being sent in Processing and on the Serial Monitor), the motor just keeps spinning. This is my current code:
char val; // Data received from the serial port
#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
}

void loop() {
  if (Serial.available())
  { // If data is available to read,
    val = Serial.read(); // read it and store it in val
  }
  if (val == '1') { // If 1 was received
    Serial.print ("1");// turn the LED on
    for (pos = 0; pos <= 120; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    for (pos = 120; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
  }
  if (val == '0') {
    Serial.print ("0");
    pos = 120;
    myservo.write(pos);
  }
}

The logic of your sketch is to move from 0 to 180 and back when receiving the character '1'. The movement is completed before checking for the next character. Your sketch does not allow stop at the current position during the movement.

Are you sure the mouse is not sending a continuous stream of 1s? If that were the case then, because of buffering, all the 1s will serviced before the servo stops. For example, a sequence of 11111 followed by a 0 will cycle the movement 5 times before it stops and prints the 0.

fairly simple:
switch (serial_received()) {
  case -1: break; //-1=nothing received
  case  0: break; //0 received
  case  1: servo_pos = ...; servo_move2(servo_pos); break; //update servo position
  case  .... //other commands
  default: ...
}

you can fill in the functions with whatever appropriate for your environment.


text:
3.3 V Pro Micro clones flashing LEDs after 1200 bit/s touch
I have several Pro Micro clones.
This morning I uploaded a sketch into one of them (that was previously unprogrammed, so it stayed in bootloader mode) and when I wanted to upload the sketch a second time, the problem began:
When I now run the reset procedure for Arduinos with integrated USB (open the COM port of the Pro Micro for example in PuTTY at 1200 bit/s and close it again), the LEDs start flashing rapidly and the Arduino disappears from the Windows Device Manager.
Hover for a (slightly annoying) image:

So then I grabbed a second, identical Pro Micro and uploaded the Blink sketch into it. It was also previously unprogrammed. The sketch executed, but when I now do the reset procedure, it exhibits the same behavior now (flashing LEDs).
I can still upload sketches just fine, by setting the COM port to a different (arbitrary) COM port to prevent the reset procedure from reaching the Pro Micro and resetting the Pro Micro manually after starting the upload procedure.
This only happens with the 3.3 V/8 MHz variant, not with the 5 V/16 MHz variant. I have selected the appropriate variant in the IDE.
How can I repair the automatic reset function?

It's not really clear what you're asking. If you open and close the CDC @1200 baud, it will reset to receive new firmware over USB. This is what the Arduino IDE uses to upload new sketches. Link 1 Link 2
What are you trying to do? Why do you need to open it at a baud rate of 1200 baud?

That's the point - it should reset and go to bootloader mode but instead it starts flashing and disappears completely from the device manager.

I was finally able to solve this by using one of the Pro Micros to re-burn the bootloader of the other one.
For reference, the process is like this:

Flash the example sketch "ArduinoISP" into the first Pro Micro
Connect the two Pro Micros like this:
Programmer (on USB)   Target
GND ----------------- GND
VCC ----------------- VCC
15 ------------------ 15
14 ------------------ 14
16 ------------------ 16
10 ------------------ RST

Choose "Arduino as ISP" as Programmer
Because both are Pro Micros, selecting a different board is not necessary.
Click "Burn Bootloader"

Striking out is not a good idea. An answer should only have the current best information. The historical information belongs in the revision history (do provide a comprehensive summary, though, as the intent is not always in the diff). If there should be information for earlier versions of the IDE then split it in two, e.g. "For Arduino IDE v. y.y.y and later: ABC" and "For Arduino IDE v. x.x.x and earlier: XYZ". Put the information that benefits more readers first (there is no requirement to have it in chronological ascending order) - that is probably for the newer versions of the IDE.

I removed the step, will (should) long be using a newer version anyway.

Arduino Pro micro will enter bootloader if you connect it with 1200 baudrate. See this pos Upload code on Arduino Leonardo using command line

I like your other post. Maybe you could expand this post a little, as it is a little short and terse.

And it doesn't answer the question. The question is about why it does not enter the bootloader. (The bootloader would be visible on the USB bus.)

@vanbwodonk, AndreKR will not receive a notification in his inbox and may see your reply, if you don't address your comment to him using an@ as I have just done to you. Repost your comment and add their name with the preceding @

@AndreKR Actually i not really understand what are you asking about. Led flashing indicate that's Arduino Pro Micro successfully jump into bootloader. Of course it will change COM port under windows (I assume you using windows).

@vanbwodonk Are you sure that it should flash when in bootloader mode? Because mine doesn't, so this might indicate something. Can you make a video of the flashing and the device manager/lsusb so I can see the timing?

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


text:
How to connect Arduino 5v pin with multiple things?
I am trying to connect a Bluetooth module and a gas sensor to Arduino.

Bluetooth module: HM-10
Gas sensor: MQ-2

I read the guides for the HM-10 and MQ-2 and they both need to use the Arduino's 5v pin. I did a lot of searching but I could not find a proper example.
I would like you to give me a link to an example that uses the 5v pin for multiple modules. It would be nice if the circuit configuration was included.

I read the guides for the HM-10 and MQ-2 and they both need to use the Arduino's 5v pin. I did a lot of searching but I could not find a proper example. do you envision it being much more complicated than wiring them, separately and individually, to the 5v pin? that's how it is normally done gazillion of times every day.

If you are trying to connect multiple things, you should first consider if it is appropriate to have their power passing through the Arduino at all.  Often it's better to give them their own routes to the power supply, and only share a common ground with the Arduino.  Additionally, the HM10 requires something like 3.3v NOT 5v.

5V is just 5V. It's not a signal, it's just a voltage level. If you need to connect multiple things to it then just connect multiple things to it. If that means connecting wires together then so be it.
Yes, you can use breadboards for it, but that's pretty wasteful if all you want to do is connect a few 5V wires together. It's simpler just to strip the ends and twist them together. Maybe add some tape to insulate them so you don't get accidental short circuits.

The simplest way is to just use a breadboard to connect your devices to your Arduino:

I can't read Chinese, so I can't check the specifications of these particular devices, but you need to be aware of the power limitations on your Arduino.
The maximum total current you can draw when the device is powered via external power supply is 1A for the Arduino Uno, 800mA for the Due and 500mA for the Nano. Check the specs for your board on the Arduino site.
Arduino-compatible devices may vary - check the specs for the device you're usiing.

Note: If you're not powering your board via USB, the total 5V current limit coming out of the Arduino is limited by the voltage regulator on your particular board, and/or your input power supply (whichever provides less power).


text:
Uploading Lua code to Arduino
I have Arduino UNO board. Can I upload programs written in Lua?
I wrote a code for simple home automation using relays to control lights and tried to upload it to my Arduino board, I get error code of "Error compiling for board Arduino/Genuino Uno"? What does this mean?
This is the code I used:
var("Switch", "ME.BI21")
var("Relay", "ME.BO21")
var("RelayState", "ME.BO41")

RelayState = 1

Relay = Switch

if (Relay == 1 then){
  print("The Relay is ON")
}
else{
  print("The Relay is OFF")
}
end

The Uno can’t run Lua code. The ESP8266 modules like the Wemos D1 or NodeMCU can, with the right firmware.


text:
Make one Arduino fire interrupt on another
Problem
I have an Arduino Duemilanove which needs to communicate with an Ardiuno Mega.  The only pin available on the Duemilanove is D13.  The Duemilanove is in charge of driving state on my robot, and the Mega is in charge of sensor readings and navigation.  The Mega needs to send drive state updates to the Duemilanove.  I2C, PWM, Serial, anything requiring different pins on the Duemilanove is out of the question at this point.
Idea
I plan to have the Duemilanove send the "pipe" pin high, triggering an interrupt on the Mega.  The ISR will send the current drive state to the Duemilanove which will change pinmode and read a digital pulse.  The length of the pulse is the drive state.
Roadblock
I am having trouble finding an example of how to set this up.  I can't get the ISR to fire, and I'm not sure why.
Mega Code
int pipe = 18;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(pipe, INPUT);
  attachInterrupt(digitalPinToInterrupt(pipe), driveStateISR, CHANGE);
}

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

}

void driveStateISR(){

  Serial.println("ISR fired");
  pinMode(pipe, OUTPUT);

  digitalWrite(pipe, HIGH);
  delay(50);
  digitalWrite(pipe, LOW);

  Serial.println("Pulse sent!");

  pinMode(pipe, INPUT);

}

Duemilanove Code
int pipe = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(pipe, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(pipe, HIGH);
  delay(30);
  pinMode(pipe, INPUT);

  unsigned long duration = pulseIn(pipe, HIGH);

  Serial.println(duration);

  delay(3000);
}

Nothing happens at all.  I'm thinking the main framework is here, but since there aren't many examples of this out there I'd love to get some other eyes on the issue.  Thanks!

You should not do delay() or Serial.print() inside an ISR. That would cause it to hang. For more information see my page about interrupts and also How do interrupts work on the Arduino Uno and similar boards?

since it is one-way communication, it should be fairly simple, as long as you decide what the protocol you intend to use.
it could be pwm for example -> the duty cycle is the encoded data; or analog output; or uart tx; ...
after that, pick who the master is and who the slave is. generally it is (much) harder to code a slave so pick the slave that has the necessary hardware on the pin you have and go from there.

PWM would be nice, but I don't have an available analog input on the Duemilanove.  As far as I know I can't read an PWM signal using pin D13, which is the only I have available


text:
Timer1 firing immediately
I'm trying to use Timer1 to get fired once a certain event occurs (about 1ms after the event). Using the timer to get a periodic interrupt works fine, but the very first interrupt fires immediately, rather than after the time I want it.
#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  Serial.println("start");
}

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  cli();
  TCNT1 = 50000;

  // if (micros() - stack[0] < 500) return; // work around guard would skip stray 1st interrupt

  stack[ctr++] = micros();

  if (ctr > ENTRIES)
    TIMSK1 &= ~(1 << TOIE1);

  sei();
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;
    cli();

    TCNT1 = 64000; // tick in around 1ms
    TCCR1A = 0;
    TCCR1B = (1 << CS10); // no prescaler
    TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt

    sei();
  }
}

When you enter t on the console it enables the interrupt and - unexpectedly - the timer fires at once. The next one comes after 1ms. A sample output looks like
start
testing
0: 8
1: 980
2: 980
3: 980
testing
0: 8
1: 980
2: 980
3: 980

Uncommenting the guard yields
start
testing
0: 988
1: 972
2: 976
3: 976

How can I modify my code (except setting a guard in the beginning of the ISR) so it is triggered once AFTER 1ms.

Interrupt flags are set even without interrupt enable flags, so there is pending overflow that you didin't cleared. And guess what happens after enabling TOIE1 flag. It gets handled by ISR. That's on behalf of Arduino's analogWrite() PWM outputs (all timers are up and running in 8bit mode and 1.024ms period).
Btw global interrupts are disabled and reenabled inside of ISR handler by hardware so you shouldn't have cli() and sei() in it.
Also there is another issue - counter mode is preset to 8bits and much bigger prescaler, so the first round is way off.
void setup() {
  Serial.begin(115200);
  Serial.println("start");
}

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  TCNT1 = 50000U;
  stack[ctr++] = micros();
  if (ctr > ENTRIES)  TIMSK1 &= ~(1 << TOIE1);
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;

    TCCR1A = 0;           // you have to change the timer mode before changes
    TCCR1B = 0;           // stop the timer
    TIFR1 |= _BV(TOV1);   // clear the overflow interrupt flag by writing 1 to it
    TCNT1  = 50000U;      // tick in around 1ms / this makes more sense if it's set correctly
    TCCR1B = _BV(CS10);   // no prescaler ?????  REALLY???? this one is prescale by 8
    TIMSK1 |= _BV(TOIE1); // enable timer overflow interrupt
  }
}

That looks like a live saver :-) Too tired now, but will check this tomorrow! Thanks

That got me wake and it's exactly what I was looking for. Thanks also for the info about the interrupt handling :-)

Ah, and one remark about the remark: The compiler knows that TCNT1 is an unsigned and will coerce literal numbers correctly. So TCNT1  = 50000; works as well.

@thomaskilian it wasn't about signess. More likely about previous setting by Arduino. You were using the value 64000. Anyway it's better to use unsigned literals especially for bit shifts.

64000 < 64k = 64512


text:
I change ESP8266 baudrate and now it doesn't work
I was trying some AT commands using the monitor of the Arduino Web Editor with an Arduino Uno and a ESP8266 module. It was working at 115200 bauds but then I changed it with AT+CIOBAUD=19200 and now it can't communicate.
How can I change the baudrate to 115200?
Now I see this:

How were you "trying" those AT commands?

Have you tried setting the web editor's baud rate to both the old and the new values? I ask because the CIOBAUD command has been obsolete for a while now so, depending on the age of your device, it may have done nothing. The command was replaced by "AT+UART_CUR" and "AT+UART_DEF" which have a different syntax.
See this answer to a similar question.
Update:
Yes, here's an example:
// Declare a serial object to talk to ESP8266
SoftwareSerial EspSerial(WIFITX_PIN, WIFIRX_PIN);  // RX, TX

void setup(void){
   // Init WiFi serial
   EspSerial.begin(9600);
   delay(10);
}

I've used 9600 baud in my example since SoftwareSerial may not work well at faster speeds.
Update 2:

Is it possible to send AT commands from the code instead of the
  monitor?

Yes, easily. Once the above code has run (and note that I've deleted an unnecessary line since update 1), you can send strings to the ESP with EspSerial.print() and EspSerial.println(). Here's an AT command example:
// Set 9600 baud, standard 8-bit frame, and save as power-on default:
EspSerial.println("AT+UART_DEF=9600,8,1,0,0");

Is it possible to set baudrate inside the code with a sentence?

Is it possible to send AT commands from the code instead of the monitor?

your question has been answered. why are you posting new questions here?


text:
Parsing sd card file to polymorphic objects
I am trying to read a file from sd card and parse them to polymorphic objects, then have an array of pointers to them so i can access them later.
I was wondering what the best format would be to save these objects in, i was looking at https://github.com/bblanchon/ArduinoJson but i don't know if it's possible to deserialize them to the right object.
Is this even possible?

There is no such thing as serialization/deserialization in C++. You can read the data values from an object, and you can write data values to an object, as long as you either expose the properties as public, or create "getter" and "setter" member functions.
It is then up to you to store and retrieve that data in whatever form you like.
You could store the raw RAM data that corresponds to an object, however if there are any pointers in that object they will be stored as just that - a pointer - which will be meaningless when reloaded. So it's better to store the data values manually.
How you store the data depends on what the data is. Yes, you can use JSON format if you so choose - it has good abstraction for storing strings, escaping special characters, etc. So it would be quite convenient - however, it's quite a heavyweight arrangement. A lighter method would be to store binary data directly, but that is inflexible and can't easily store different types of data in different ways for different objects.
CSV format is quick and easy to parse, but you have to manually deal with things like commas in data strings, etc.


text:
Getting wrong values from serial.read() connected to a Raspberry Pi
I set up a serial connection and sending integers from a Raspberry Pi to an Arduino.
This is the Python code in my Raspberry Pi:
import serial
ser = serial.Serial('/dev/ttyACM2', 9600)
ser.write(str(x_value));

And this is the command line output for x_value:

-38 -38 -38 -40 - 38 - 39 - 40 - 12 18 26 25 49...

They are x coordinate values I generated and they range from -100 to 100. And here's the Arduino code for receiving serial data:
int ByteReceived;

void loop() {
  while(1) {
    if (Serial.available() > 0) {
      ByteReceived = (Serial.read());
      Serial.print(ByteReceived);
      Serial.print("\n");
    }
  }

On the serial monitor I'm receiving these numbers:

46 45 51 48 45 53 52 45 49 52 45 52 55 55....

They are numbers between 40-60 and no way proportional to the values I sent from serial.write.
I'm really confused right now. Can someone help me to figure out what caused this problem?
Thank you so much.

You're receiving a different type than you're transmitting.

Learn the meaning of ASCII...

46 45 51 48 45 53 52 45 49 52 45 52 55 55....
. - 3 0 - 5 4 - 1 4 - 4 7 7...

ser.write(str(x_value));

Writes the string representation of the integer x_value, which is a sequence of ASCII characters.
ByteReceived = (Serial.read());
Serial.print(ByteReceived);

Reads a character (byte) and prints to the value (again as a sequence of characters).
45 51 48 45 53 52 45 49 52 45 52 55 55....

45 is ASCII character value for the character '-', 51 is the character '3', 48 is '0' and so on.
Cheers!


text:
Concave button wiring with Arduino
I am new to working with Arduino and I have a basic question.
I have an entire circuit set up and functioning, but I would like to add an arcade style button (Larger concave style) like this.
So my question is, how would I go about wiring this button to the Arduino? I don't need this button to control any lights or any other functions. The basic function of this button is for my code to register if the button is pressed or not. I also have the code done. I just want to know how to wire this.
Also I don't know if this helps, but I already have two normal tactile buttons (with 4 pins) in the circuit connected with a pull-up resistor and I know how to connect them. I just have no idea how to go about with only 2 pins.
Any help would be greatly appreciated. Thanks.

A simple switch, frequently called single pole single throw, will have only two pins. A switch works by breaking the circuit. This is shown in a wiring diagram in this manner:

It matters not that the switch in this image is not the same switch as in the image you linked, the operation is identical. You may find momentary switches with similar appearance and identical diagrams. The difference is that one has to hold the button to make (or break) a circuit, which reverts once released.
You mention four pins. Those switches are electrically identical to the SPST switch, except that you may find you can control two independent circuits that both activate when the button is pressed. That would be a double pole single throw. There is also the possibility that the four-pin switch has common connections on each side. That is to say that if you connect your circuit to one pin, it is conductive to the other on on the same side, while the closure of the switch will also equally effect the two pins on the opposite side. I've found some tiny switches that have this arrangement, ostensibly to provide for four points to solder to the circuit board, making for a more sturdy attachment.
One can find some useful switch information on Electronics Hub, which is too exhaustive to cover here.
There are many other types of switches


text:
Reading from a pin Arduino Uno (assembly)
I am creating a project in which an Arduino reads (gets) a value from
a DHT sensor. The DHT sensor returns two values:

Temperature
Humidity

My assembly code:
sbi ddrd,5
cbi ddrd,2
sbi portd,5

start:

in r16,Pind2
cpi r16,80
brne On

jmp start

On:
cbi portd ,5
jmp start

After the code, the light remains turned on, but if the sensor sends '80'
and I get it correctly it should be turned off.
Question: Am I Using the write way to read a pin?

The first thing I saw was a cartoon where apparently a schematic is supposed to be, so I quit before reading any of the text.

I'm not sure any of your code makes sense. Firstly you've got the roles of pind and portd backwards (port is for writing, pin is for reading). Secondly you haven't defined in your code what half of the stuff is (what is ddrd, what is portd, what is Portd2). Thirdly you are reading in the portd register (not an input), and then comparing it directly to a number (decimal 80, hex 0x50) - even if we assume you mean to read the inputs (pind), you haven't connected most of the pins on that port so who knows what value will return.

@TomCarpenter I am new to it can you plz write a simple code for me
which will receive data from DHT and Move it to a register? An Example Code?

This Tutorial shows how to read and write from complete Port
but I just need One Pin and Recieve Serial Data
http://www.avr-tutorials.com/digital/digital-input-output-assembly-programming-atmel-8-bits-avr-microcontrollers

in r16, PIND, assuming you are using avr-gcc. If you want just the bit 2, andi r16, 1<<2.

I'm voting to close this question as off-topic because it is about AVR assembly NOT ARDUINO and was properly asked on EESE, but IMPROPERLY MIGRATED.  The language is not Aduino, the pin specs are AVR NOT ARDUINO - the only thing "Arduino" about this is some soldermask masquerading as silkscreen on the board.

Yet another crap migration from @Nick Alexeev. Is there anything we can do about this?

Gentlemen, Nick Alexeev asked me if he could migrate this. Whilst the assembler question might be marginally off-topic, this is hardly an electronics question. The question specifically mentions an Arduino Uno. Personally I would be encouraging him to ditch assembler for such a simple task. It seems completely inappropriate.

You are simply reading the state of the input pin - this won't work.
Study the datasheet for the DHT22, available from Sparkfun or eslewhere.
To get data from the DTH22, you must first send a start signal, wait a specified time, then watch the level of the data line, measuring the time of each bit to determine whether it is a 1 or 0, and store the bits in five 8-bit variables.  You can then examine those variables to determine the temperature and humidity.

Instructions for writing to an individual output bit:-
 sbi portd,5 ; make Port D output bit 5 high (set)

 cbi portd,5 ; make Port D output bit 5 low (clear)

 sbi pind,5  ; toggle Port D output bit 5 (low -> high, high -> low)

Instructions for reading an individual I/O pin:-
 sbis pind,2 ; skip next instruction if Port D pin 2 is high

 sbic pind,2 ; skip next instruction if Port D pin 2 is low

Awsome, this answer is clear and answers the question really well.


text:
How to reduce sketch size?
How to reduce sketch size?
I got an error that “Sketch uses 30,044 bytes (104%) of program storage space. Maximum is 28,672 bytes.”
I can't reduce function in sketch.I can't change ATmega32u4,now.
The sketch has function of measuring sensor,logging on SD,connection with BLE module.
So please tell me hack.
Or,how to increase flash memory size?
I tried to change type of String to Char.

Impossible to answer without seeing the sketch in question. Some things (like long long data types) use a very large amount of program memory. You can't increase the flash memory size (on a particular processor).

Thank you.
I agree.But I think that putting the whole sketch is not good idea. because It's hard for you to read.(and comment are Japanese mainly.)
So,I will put Structure like that include,setup,loop,other method.
How about that?

If you can find some place to post the whole thing that would be better (it will be probably too big to fit here). I don't care about the comments personally because I usually ignore them.

This has 32516 characters.

Now,I pleased that I heard generic techniques from @JRobert,@dannyf,@dda,@Michel Keijzers,too. Because I'd like to know "how to reduce sketch size" for making sketch in the future.

I'm sorry that I couldn't upload code.I'm in trouble at other points, so I correspond to that.I want time, a bit more.

I bought a lot of 32u4 board. So, I wanted to use them. Therefore, I was asking this question.

Some generic techniques you can try:

Remove duplicate code and put it in a function.
If you have duplicate code that is ALMOST duplicate, parameterize it (i.e. add a function, make the difference a parameter(s) of the function and call from various locations with different argument(s).
Use a micro controller with more Flash memory.
Minimize the data storage, limiting array sizes for example (if these are in flash RAM).
If you use precalculated arrays, remove them and create a function calculating them real time (this will be a performance cost of course).
Check for dead code inside functions. A smart compiler will already remove uncalled functions, but do not check inside functions.
Remove or minimize debug/print statements. Each character cost a byte, which adds up quickly with many strings.
Try to remove complete libraries, like removing the Serial for print statements used only for debugging.

I made code the function,in some cases this increase sketch size.So,It's difficult for me.
I knew for the first time that
A smart compiler will already remove uncalled functions, but do not check inside functions.
For me, it became very helpful as well.
Thank you!

There's no magic bullet. You have to work through your code and see what you can remove safely. If you have duplicate code, put it in a function and call this. If you Serial.print a lot of text, considering saving up on that. etc etc etc

Yes,I decrease Serial.print.Thank you!

How to reduce sketch size?

without your code, tough to be specific. but generally:
1) try not to use floating pointmath;
2) try not to use printf() or its derivative;
3) try to minimize large arrays;
4) use functions instead of macros;
5) use modular programming;
...

Or,how to increase flash memory size?

1) use a bigger chip;
2) use onboard eeprom;
3) use outboard eeprom / flash / fram / ....
4) divide up the tasks among multiple chips;
...

I don't know these point.Thank you for explaining very clearly

If you're using donated libraries to run your hardware (such as the Dallas Temperature library) or provide software features (like SimpleTimer), the authors often provide a full complement of features, some of which you may not need. I often make my own versions of these libraries that provide the functionalities I must have, and cut out the others. I can always add one or two of them back into whichever sketch needs them, without burdening other sketches with their overhead.
In SimpleTimer, for instance, I seldom have need for enable/disable timer or for a timer that runs N-times and then stops, so I have a version of the library with those functions removed.
If you've declared some text strings or other data to live in Flash, and you have more spare RAM than spare Flash, let some of those objects live in RAM instead. Or reduce the length of output strings that are stored in Flash by writing more tersely, even at the cost of clarity in the output, or eliminating that outpu altogether (which eliminates not only the string data but the code to print it, as well).
Can you reduce any code segments or algorithms with more space-efficient code? Can you eliminate some functionality to save code space?
Note that trimming buffers and arrays won't help because those are in RAM, and data packing, such as storing a number of booleans as distinct bits within a word, will actually increase your code size (this is a common way to reduce RAM requirements when you can afford the code to do the packing/unpacking, but you have the opposite problem!).

I learned from specific example very much.
I used to Metro library,SoftwareSerial,etc.So I can use the solution.
I did not understand this difference. (this is a common way to reduce RAM requirements when you can afford the code to do the packing/unpacking, but you have the opposite problem!). Therefore, I will be able to distinguish decreasing solution between Flash and RAM from now on.
Thank you!


text:
Garbled high bits on serial output
I'm trying to send the byte 0x5A (0b01011010) on the serial output of an Arduino Due. My program is based on this example project, but I've stripped out all the unrelated parts:
#![feature(lang_items)]
#![no_std]
#![no_main]

extern crate sam3x;

pub mod rust_base;
use sam3x::*;
use sam3x::hal::peripherals::{Peripheral};
use sam3x::drivers::led::{Led};
use sam3x::hal::rtt::{init_timer, wait_ms};
use sam3x::hal::pmc;
use sam3x::hal::uart;

#[link_section=".vectors"]
pub static VECTOR_TABLE: VectorTable =
    VectorTable {
        reset_handler : start,
        exceptions    : [0; 14],
    };

fn start() -> ! {
    init_timer();
    pmc::enable_peripheral_clock_0(Peripheral::PioC);

    let led = Led::connect(Peripheral::PioB, 27).expect("Wrong pin for led.");
    let tx = uart::Tx::init(uart::BR_9600);

    let mut led_on = true;
    led.on();
    loop {
        tx.write_byte(0b01011010);

        wait_ms(250);
        if led_on {
            led.off()
        } else {
            led.on()
        }
        led_on = !led_on;
    }
}

As you can see, all I do is send out the byte 0x5A four times a second, with some LED blinking just to show the program is running.
My problem is that if I connect a serial terminal program with 9600-8N1 settings, I am not getting 0x5A; instead, I am getting mostly 0xBA, and sometimes a 0x9A slips through.
Writing out the bits:
0101 1010    5A
1011 1010    BA
1001 1010    9A

Note that the lower nybble is always correct, which is why I don't think it's a serial communication setting issue; also, it's pretty clear from uart::Tx::init's implementation that it defaults to no parity bits.

It seems this error is specific to the Rust ARM library I am using; quoting from https://github.com/klangner/sam3x/issues/9:

It looks that at bound rate=9600 the timer sends data with the speed of ~888. And then computer can't understand the output.

Based on this, I started playing around with the baud rate I pass to the library when initializing it, and using 11000 instead of 9600 empirically seems to work (i.e. I am seeing a steady stream of 0x5A on my PC receiving at 9600).


text:
Receiving incomplete HTTP request
I have an Arduino project that needs to receive data from ThingSpeak. This is the data that I'm supposed to get.
When the data is "true" it must turn the LED on. I tried this code in hope of getting "true".
void loop() {
  Serial.println();
  Serial.println("Receiving Trigger Data...");
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    client.println("GET /channels/344468/fields/3/last?key=XXXXXXX HTTP/1.1");
    client.println("Host: api.thingspeak.com");
    client.println("Connection: close");
    client.println();
}
while (client.available()) {
  reply = client.read();
  content.concat(reply);
}
delay(3000);
Serial.println(content);
if(content.indexOf("Content-Length: 4") > 0) {
  digitalWrite(ledPin, HIGH);
}

The Serial Monitor gives this reply. I don't see the word "true" being returned at all and I don't also see the content length. I tried putting delays but still I don't receive the "true" or even just the content length. Please help.

available() is non blocking. network is not so fast. at the first gap you stop reading

I think you can to use client.connected() to determine whether there is still data coming in (since you are sending the Connection: close header).

Thank you very much. I changed available() to connected() and it worked properly now.


text:
Arduino IDE documentation for WiFi.connected()
I'm including this library "ESP8266WiFi.h" at the top of my sketch.
I can find documentation on WiFiServer.available(), but didn't find for WiFi.connected(), which is called in a server sketch after getting the client.
Clearly it's a test whether (once? I believe) the client is connected or not (and hasn't been explicitly closed in the server's side). It may seem obvious but some documented info would be helpful though.

You'll find it defined in WifiClient.h. The version I am using is, in WifiClient.cpp:
uint8_t WiFiClient::connected() {
  if (!_client)
    return 0;
  return _client->state() == ESTABLISHED || available();
}

Thank you. I think I will have to read the code thoroughly. Meanwhile I hope someone documents it...

Complain to the maintainers of the core. It's their responsibility.


text:
HC-05 Bluetooth module doesn't read data correctly from my Android phone
I have made a home automation project where am using an Arduino Uno and HC-05 Bluetooth module and an Android app. I did everything properly but when I send commands from my Android app it works sometimes and sometimes it doesn't work.
I checked these commands on the serial monitor and found that data command I recieve at serial monitor did not match the commands which I send from my Android app. For example my Android app send command "ON1" but on serial monitor it shows "OL1?". I thought it might be a problem with the HC-05 so I changed it and used a new HC-05 module, but the problem is still there.
This time I checked the commands from another Android app (Bluetooth Terminal HC-05) and there was the same problem. Sometimes it read the command correctly app and sometimes it read something else.
I am so confused weather the problem is in my hardware side or software side.I tried a lot but didn't get any solution about my problem anywhere. Can anybody help me please?
This is the Arduino code of my project:

#include <SoftwareSerial.h>
SoftwareSerial Genotronex(2, 3); //TX, RX  pins of arduino respetively
String command;
void setup() {
  Genotronex.begin(9600);
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
}

void loop() {
  while (Genotronex.available()) {
  //Check if there is an available byte
    to read
    delay(10); //Delay added to make thing stable
    char c = Genotronex.read(); //Conduct a serial read
    command += c; //build the string.
  }
  if (command.length() > 0) {
    Serial.print(command);
    if (command == "ON1") {}
    //this command will be given as an input to switch on light1
    digitalWrite(9, HIGH);
  } else if (command == "OFF1") {
    //this command will be given as an input to switch off light1 simillarly other commands work
    digitalWrite(9, LOW);
  } else if (command == "ON2") {
    digitalWrite (10, HIGH);
  } else if ( command == "OFF2") {
    digitalWrite (10, LOW);
  } else if (command == "ON3") {
    digitalWrite (11, HIGH);
  } else if (command == "OFF3") {
    digitalWrite (11, LOW);
  } else if (command == "ON4") {
    digitalWrite (12, HIGH);
  } else if (command == "OFF4") {
    digitalWrite (12, LOW);
  } else if (command == "ON5") {
    digitalWrite (13, HIGH);
  } else if (command == "OFF5") {
    digitalWrite (13, LOW);
  } else if (command == "all on") {
    //using this command you can switch on all devices
    digitalWrite (9, HIGH);
    digitalWrite (10, HIGH);
    digitalWrite (11, HIGH);
    digitalWrite (12, HIGH);
    digitalWrite (13, HIGH);
  } else if (command == "off") {
    //using this command you can switch off all devices
    digitalWrite (9, LOW);
    digitalWrite (10, LOW);
    digitalWrite (11, LOW);
    digitalWrite (12, LOW);
    digitalWrite (13, LOW);
  }
  command = "";
} //Reset the variable

Could you re-read your question please, and check it says what you want? Edit any fixes into the question, rather than posting them here. I  am confused about how the system is set up -- for example, you say the Android app sending the data didn't receive the right commands. Do you mean the Arduino didn't receive the right commands? What commands did it receive? Your method of reading until there is nothing left is dangerous, but let's find out what the problem really is before guessing solutions.

I have edit it as u mention. Thanks for ur guidness. plz let me know is that ok now ?

I suggest to have a look at this answer:
Change the baud rate of HC-05
In many case and especially when you send data from Android and receive bad data on Arduino, it's because the speed is not set correctly.
On the other side (getting data from the Arduino), it's a bit more complicated. You have to build your own "time out" system on Android as the Bluetooth library don't have such a feature.


text:
What do the pins on this KS0107+KS0108 display do?
I got this display on ebay and I have no instructions on how to use it. I can guess what most of them do but I'd rather be sure I know what they all are instead of messing around trying to guess. The ebay page said the screen is a KS0107+KS0108 128x64 display.

Is there any documentation on what these pins do and which ones I need to connect to my arduino uno to get it working?

glcd-arduino (GLCDv3) is an unofficial Arduino library that supports Graphic LCDs (GLCD) that use the KS0108 (or equivalent) chip.

Ah I see there is a diagram there with the numbers 1-20. Is this some kind of standard arrangement for these kinds of LCDs?

In most cases, yes. Sometimes there are LCDs in which CS1, CS2 (CSEL1, CSEL2 ) have an inverted input.

This LCD corresponds to Pinout B according to the table.


text:
Arduino Yun not showing anything on the serial monitor
I am having issues with the ArduinoYun. It's not showing any data in the serial monitor. The sensor lights up when I plug it in but that's about it and the code seems to compile but nothing is coming through. I am using the Adafruit color sensor. I have SDA/SCL connected to pins 4 and 5. The servo is connected to pin 3. The rest is just on Vin and GND.
#include "Servo.h"
#include "Wire.h"
#include "Adafruit_TCS34725.h"

const int redPos = 160;
const int orangePos = 130;
const int yellowPos = 100;
const int greenPos = 70;
const int bluePos = 30;
const int nonePos = 0; // Kein Objekt erkannt

Servo myservo;

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_1X);

void setup() {
  Serial.begin(9600);
  Serial.println("Makerblog.at - MuMs Color Sensor");
  if (tcs.begin()) {
    Serial.println("Sensor gefunden");
  } else {
    Serial.println("TCS34725 nicht gefunden ... Ablauf gestoppt!");
  while (1);
  }
  // Der Servo hängt am PWM-Pin 3
  myservo.attach(3);
  // Servo in Grundstellung fahren
  myservo.write(0);
  delay(1000);
}

void loop() {
  uint16_t clearcol, red, green, blue;
  float average, r, g, b;
  delay(100); // Farbmessung dauert c. 50ms
  tcs.getRawData(&red, &green, &blue, &clearcol);
  average = (red+green+blue)/3;
  r = red/average;
  g = green/average;
  b = blue/average;

  // Clear-Wert und r,g,b seriell ausgeben zur Kontrolle
  // r,g und b sollten sich ca. zwischen 0,5 und 1,5
  // bewegen. Sieht der Sensor rot, dann sollte r deutlich über 1.0
  // liegen, g und b zwischen 0.5 und 1.0 usw.
  Serial.print("\tClear:"); Serial.print(clearcol);
  Serial.print("\tRed:"); Serial.print(r);
  Serial.print("\tGreen:"); Serial.print(g);
  Serial.print("\tBlue:"); Serial.print(b);

  if ((r > 1.4) && (g < 0.9) && (b < 0.9)) {
    Serial.print("\tROT");
    myservo.write(redPos);
  } else if ((r < 0.95) && (g > 1.4) && (b < 0.9)) {
    Serial.print("\tGRUEN");
    myservo.write(greenPos);
  } else if ((r < 0.8) && (g < 1.2) && (b > 1.2)) {
    Serial.print("\tBLAU");
    myservo.write(bluePos);
  } else if ((r > 1.15) && (g > 1.15) && (b < 0.7)) {
    Serial.print("\tGELB");
    myservo.write(yellowPos);
  } else if ((r > 1.4) && (g < 1.0) && (b < 0.7)) {
    Serial.print("\tORANGE");
    myservo.write(orangePos);
  } else {
    Serial.print("\tNICHT ERKANNT");
    myservo.write(nonePos);
  }
  Serial.println("");
  delay(100);

Assuming the code works, you should be able to change the position of the servo by altering the initialized color values.  Currently they are:
 const int redPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int greenPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

If, for example, the positions of Red and green are to be swapped all that is needed is to alter the code like this:
 const int greenPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int redPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

The numbers, according to the Arduino's servo driver web page, are the angle in degrees the servo will be moved to after executing the call to the Arduino servo driver.
Given the above, if a new color violet were to be added to the original set of colors the first change would be to move the servo positions slightly higher to make room for the new color.
 const int redPos = 160;
 const int orangePos = 135;
 const int yellowPos = 110;
 const int greenPos = 85;
 const int bluePos = 60;
 const int violetPos = 35;
 const int nonePos = 0;

The next change would be to alter the ranges of the color test code.  As you did not specify what hardware you are using to detect colors, you will have to experiment to find the combination of red, green & blue which matches the new color violet.  The code used for detecting blue is:
 else if ((r < 0.8) && (g < 1.2) && (b > 1.2))

Likely violet contains more red and may be detectable with a line of code like this:
 else if ((r > 1.0) && (g < 1.2) && (b > 1.2))

The position of this test may be important depending on how the detector works.  It may be best to place it after testing for orange.  Remember to use the new initialized variable such that you code may look like this:
else if ((r > 1.0) && (g < 1.2) && (b > 1.2)){
  Serial.print("\tVIOLET");
  myservo.write(violetPos);
}

you are the best, thank you so much for breaking down the code for me.

Well, i am having issues with the arduino yun, showing any data in the serial monitor. The sensor lights up when i plug it in but that is about it and the code seems to compile but nothing is coming through.

Wow, I've never seen anyone edit a question like that.  My recommendation is to change back your question to its original wording.  Then post a new question about not getting the expected results.  Add a comment here if you can not figure out how to change your question back to its original form & I will try to do it.  By the way, you should try the original Adafruit example code and verify your hardware is connected properly and is working before trying unknown code.

I tried using the example codes in the arduino ide but i was still having the same issue. i read other post and they said that it had to do with using serial.begin instead of consol.begin.I found that suggestion impractical to my situation since i was not using wifi for the yun, i attempted using console.begin anyways just to see whether that would help but it did not. so, i am still having the same issue.

We can't have a discussion in the comments.  The "stackexchange bots" will start suggesting we move.  But I would test the code w/o the servo in an ordinary situation where the example code works.  Then dropping printing out the color and just use the detector and servo and finishing off your testing.


text:
How to get ESP8266 firmware version?
I am going to update the firmware of an ESP8266 module, but first I would like to know the current version or name.
How can I get it? Maybe with an AT command?
This is my ESP8266 module:

ESP8266 and the AT firmware are products of Espressif. They have everything documented on the web site.
The AT command for version is AT+GMR.


text:
Serial.print / sprintf causes program crash
The following code
  int i;
  char msg[16]; // Serial data.

  Serial.println();
  Serial.println("===============");

  sprintf(msg, "Sequence:  %4d", runNum);
  Serial.println(msg);

  Serial.print("LED colour: ");
  Serial.println(colours[colour]);

  Serial.print("Max mA:      ");
  Serial.println(mAmax);

  Serial.println("  mA    mV");
  for (i = 1; i <= mAmax; i++) {
    sprintf(msg, "%4d", i);          // <--- Line 1.
    Serial.print(msg);               // <--- Line 2.
    sprintf(msg, "%6d", i * 3);
    Serial.println(msg);
    delay(50);
  }

crashes after the first pass as shown below:
===============
Sequence:     1
LED colour: red
Max mA:      30
  mA    mV
   1     3

If I comment out "Line 1" and "Line 2" the loop runs correctly.
I suspect that something odd happens with either the two sprintf calls or the Serial.print / Serial.println calls in quick succession.
Can anyone spot an error or know of an issue that I've missed?
Development environment: create.arduino.cc

Not from that snippet, no. You need to show your full code, or a version of the code that at least compiles and demonstrates the problem. As it stands we cannot know what is happening because we don't know what your code is doing. What are your variable types? What values do they contain? What else is going on with your code that could have a bearing on it?

Please add the declaration of msg. The string buffer might be too small.

I forgot about the declaration. I've added that. I've also stripped down my code to the snippet above plus the setup, etc., and it works. Darn! More digging. I'll update later when I have more info.

%4d does not limit the maximum size. When the number is 20000 the whole 20000 is printed and your buffer will overflow. You assume that the loop runs correctly when those two lines are commented out. I doubt that. Data on stack that is overwritten or ram problems or heap overflow is not always detected. We still need a full working sketch that shows the problem.

avr-libc does have snprintf(), or you could check the value for limits before sprintfing it.

Where does runNum come from?

Please show your full code. See How to create a Minimal, Complete, and Verifiable example

Hold off for a bit, thanks, guys. I've got the code working now but I'm struggling to find what the original problem was. The stripped down version ran fine. More later and I'll post my findings.


text:
MAX7219 library that can compensate for poorly designed/miswired 8x32 panel?
I have this sample code:
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

#define MAX_DEVICES 4
#define CLK_PIN   11
#define DATA_PIN  12
#define CS_PIN    10

MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

void setup(void) {
  P.begin();
  P.print("PPPPPPPP");
}

void loop(void) {
}

And this is how it lights up the display:

I presume that the code displays text incorrectly, because the display manufacturer has connected individual 8x8 displays "differently than any library expects" (i.e. in red I have annotated the column addresses for my display, while with green I have annotated what they would have to be for this library to show text correctly).
I have two questions:

Is there any good Arduino graphics library that would allow me to fix from software the addressing issue specific to my display?
Since in the future I plan to make a 16x64 display out of 4 of these, then is there a library capable of doing that as well (i.e. have vertical font size of 12-16 pixels)?

No software will work properly when hardware doesn't.

@IgnacioVazquez-Abrams I imagine that if there was graphics library that would allow me to render pixels in memory buffer instead of hardware directly, then I could compensate this hardware bug by using LedControl library and calling something like setColumn((7-addr&0x7)+addr&252,value). So is there a library that allows to render  pixlels in memory buffer?

This may help. It's hard to say if you have bad hardware or a bad library.

The issue is minor. It looks like the library was designed for a slightly different matrix display / wiring.
Take a look at the library and it likely maps the input buffer to segment / dot-matrix information. Play with that.
The author did 99% of the work for you. You just need to finish the last 1%.

You mean to change the code in library itself? This somewhat puts maintenance burden on me to share a fork of patched Parola library with my code until I get these Parola changes upstreamed and downstream (ie. Arduino Web IDE) picks them up. So I would prefer to use a library that can deal with this issue out of the box, if there is one.

the solution is really simple: swap bit orders. so you just need to write a function that swaps bit 7 <-> bit 0, bit 6 <-> bit 1, bit 5 <-> bit 2, bit 4 <-> bit 3. very easy to do.


text:
Arduino int problem
I made a counter to count pulses:
int count  = 0 ;
.
.
.
setup()
{
}

while (count <= 35000)
{
  digitalWrite(9, HIGH);
  delayMicroseconds(500);
  digitalWrite(9, LOW);

  count = count + 1;
}

But when I try while(count <= 40000), it does not stop counting.

int in AVR GCC is 16 bits. All possible int values are less than 32767.

To be precise, the maximum value of int on this platform is 32767. If you add 1 to 32767 you get -32768 which then counts back up to 0, then up to 32767 and so on.

If you made it unsigned int then the maximum value is 65535 which would work for counting up to 40000.

You have reached the maximum number that an int can represent. That is 32767.
int is a variable type that is made up of 16 bits. It is signed, meaning that it can represent positive and negative numbers.
Out of the 65536 (ie. 2^16) possible numbers from the 16 bits, half of them represent negative numbers and the remaining half represents positive numbers (including zero). Or in other words, -32768 to 32767.
If you don't need negative numbers, then you can change your variable type to unsigned int which  will use numbers up to a maximum of 65535. So it becomes:
unsigned int count = 0;

But when I try while(count <= 40000), it does not stop counting.

"int" has a range from -32k to +32k-1. so "count <= 40000" will always be true as count is "int".


text:
Global variable won't update inside void loop arduino
I need to update my global variable once I get a 'overdtrue' response and light up my LED but only my LED is lighting up but my global variable is not updated.
Here is my code
int x = 0;

void loop() {
if (content.indexOf("ovrdtrue") > 0)
 {
  x++;
  digitalWrite(ledPin, HIGH);

 }
fsrReading = analogRead(fsrAnalogPin);
Serial.print("Analog reading = ");
Serial.println(fsrReading);
Serial.print("X: ");
Serial.println(x);
}

The x value should be 1 but only the LED has light up. Please help.

once I get a 'overdtrue' response - if (content.indexOf("ovrdtrue") > 0) - is it overdtrue or ovrdtrue?

Sorry for the confusion. it's "ovrdtrue"

My guess is that there is more to this code (which actually looks like parts from an HTTP server). Your snippet is leaving out the part that could explain this behavior. Either post a working snippet with the error or post more of the actually code.

It seems like I forgot to include an if else condition above the ovrdtrue.
if(content.indexOf("true") > 0)
{
  digitalWrite(ledPin, HIGH);

}

Arduino is reading this condition even though the data received "ovrdtrue" but this contains some word "true" so this is the one getting read and not the ovrdtrue condition. I just changed the condition variable not close to the word true and it worked fine. I'm sorry for this.

You never set the LED pin to LOW, so it will stay lit up regardless of the global variable.

Yes I want it to stay lit at the same time change my global variable x value from 0 to 1 with the digitalWrite(ledPin, HIGH); command but somehow it's ignoring the x++; and just lights up the LED

You need to post more code. What pin is ledPin? Is ledPin ever set to output? Do you change x elsewhere? Do you change ledPin elsewhere? Is x declared elsewhere? Global variables definitely update inside loop so your problem is elsewhere.

Are you sure the LED is not lighted from the start?
It's unclear if in the Setup you set the light on or off (or it is default on or off).
Print a Serial print inside the if statement to be sure that the if block is entered, also print before the if the value of content to be sure if 'ovrdtrue' is found in the string.
Also, since you want the LED on in this situation, explicitly set it off in the setup.

the LED are not lighted from the start. I think it has found the "ovrdtrue" because it is lighting the LED with the HIGH during the if and that's ok but my problem is why is it ignoring the x++ and not updating my global variable inside the if.

Here is my code

your code ran without setup()?
you are conditionally incrementing "x", and if your condition doesn't hold true, the increment doesn't take place.


text:
HC-05 receives only first few bytes
I have an android device and stm32f103 + HC-05 bt dongle. I'm sending 10 bytes "0123456789" string from android to stm32, but I'm receiving only random 1-5 bytes. code on stm32 side:
long received = 0;
const unsigned long buffer_size = 128;
uint8_t buffer[buffer_size];

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

[...]
void loop() {
    [...]
    if(Serial1.available()){
        received += Serial1.readBytes(buffer + received, bufferSize-received);
    }
}

So, if will send "0123456789" from android, let say, 3 times every 1 second, on stm32 i will receive 3 portions like this:
"0", "0567", "047"
or something like this, i.e. I always receive first byte and it's always correct, but it looks like the rest bytes could be randomly lost.
any idea what am I doing wrong?
P.S.> On stm32 side I'm using Arduino STM32 library. Serial1 is a UART interface, which is located on stm32f103's PA9 and PA10 pins.
I tried to use other bod rate (19200, 38400), but in this case the data is completely corrupted, i.e. just random bytes.
When I'm sending data from stm32 to Android everything works just fine, i.e. I'm receiving all the data on android side.
I'm using standard BluetoothSocket on android side. So, code looks like this:
BluetoothSocket socket;
OutputStream outStream;
[...]

void init(...) {
    socket = ConnectToSTM32(...);
    [...]
    outStream = socket.getOutputStream();
}

void send(byte[] bytes) {
    outStream.write(bytes);
}

[...]
String strToSend = "0123456789";
send(strToSend.getBytes());

Without seeing the rest of your code we can't help you. There's nothing obviously wrong from that snippet, so the problem is likely elsewhere.

Indeed without the rest of the code we can't tell, but I bet £1 you're assuming that all the data will arrive in one lump and that when Serial1.available() returns false you've got it all, which is a bad assumption. Still, edit the question so that it's useful for others.

Have you set values to your HC-05? Meaning changing the rate? Android send data at about 115200 bauds. So if you try to receive them at 9600 and display at this speed, this can explain whay's happening. Also, on Android side, performing a Log("info") must be a good idea to be really sure of what you send. Also, from where came "Serial1"?

@Majenko Added some extra details

@MarkSmith I don't assume anything - I just read available data from Serial1. I don't know how many bytes are available - just read them all and write this data continuously to a buffer

@Peter I've added some extra information. I've tried to use different speed, but not 115200 - will try it today. I didn't find any information how can I setup bluetooth speed on android side (actually, I thought it should be negotiated automatically). What exactly can I log to ensure of what I'm sending? I use Java OutputStream's write method to send data.

I think you'll get much better quality help if you post a minimal, complete, verifiable example of the problem.

@MarkSmith Will do it today, but I doubt you could repro it because of hardware specific. I suspect that problem is on android side and it, probably, related to stm32 serial stream implementation.

@Tutankhamen I've found nothing on Android to set Bluetooth speed. My App use it at 115200 as it seems to be the "basic speed". The problem came from from the fact this speed is not avaible with the SerialSoftware lib  on the Arduino (higher than 19500, the lib start to loose bits). On Arduino I use the basic RX and TX pin with Serial.begin(115200).

@Tutankhamen Contact me via my profil and I'll send you the Android code from my App, for Bluetooth. Maybe this would help;

@Peter I don't think there is a way to send private message in StackExchange

Just tried the same code with the same HC-05 module, but with Arduino Nano - everything works just perfect

Try adding a delay (10) inside if (serial1.available())

@MITURAJ For what?

Cz UART data reception is slower than microcontroller execution

And how delay could help? The logic now is: if (data_available) read_data();

https://stackoverflow.com/questions/9901058/arduino-cant-read-serial-properly

@MITURAJ It shouldn't work like this, but anyway it's not the case. I'm polling data from the local buffer, not from remote device.

So, the problem was in disabled interrupts. I just remove a library which is forcibly disabling interrupts and everything is working now.

Okay. You have not posted the full code. So we can only assume based on current code snipping.


text:
Gas Sensor output voltage to concentration
I am using figaro tgs gas sensor (2600, 2602 and 2620) to sense breath from human. What I obtained is the output voltage. However, I would like to convert the voltage to concentration in ppm? Since these gas sensors can sense more than one gas. Is there any way?? Thanks.

I would like to convert the voltage to concentration in ppm?
Is there any way??

the datasheet for those devices would have the answers for you. Generally, you read the datasheet BEFORE deciding on using them or not. not that otherway around.

This is one of the datasheet. I have calibrated it using the clean air factor in datasheet and got the Rs/R0 ratio. However, from there, I not sure how to find the concentration for each gas.

The conditioning is 7 days. Turn it on with all wires connected and wait 7 days. Then you have to calibrate it with a known concentration of the gas that you want to measure. You might also use the data from the datasheet, for example from the "sensitivity characteristics" graph. A single sensor detects multiple gasses, and there is no way to tell which gas it is. If you combine more than one sensor, you might distinguish a few different gasses, but that is not in the datasheet. I think you have to use a known concentration of a gas and collect the data from all sensors.

Thanks for the reply. I refer to https://jenslabs.com/category/electronics/ketosis-detector/ and http://sandboxelectronics.com/?p=165  For the first link, I not really sure where the value got to convert from resistance ratio to ppm...The second link use the gradient in the datasheet for each line and generate the ppm value from ratio got. Can it be use?

The TGS2600, TGS2602 and TGS2620 are not designed to breath on. The TGS822 (in the first link) is. In the datasheet is a graph of ppm versus Rs/Ro. The most common (and also cheapest and poor quality) are the "mq" gas sensors. You can find examples for ppm when you search for: arduino mq gas sensor ppm

But 2600, 2602 and 2620 also show the Rs/Ro versus ppm graph. I can obtain the Rs/Ro ratio, will it means if I use the same method shown in the link I can get the concentration as well?

I think that is specific for the TGS822. Every sensor might have the same shape of the curve, but for the TGS822, the calculation is split into two parts. A calculation for the resistance below 3600Ω and a calculation above that. I don't know if the 3600Ω can be used for other sensors. The overall accuracy is not very good, perhaps a simple calculation will do.

If you want to measure concentrations of individual gases you would have to separate them and detect them separately using a chromatography column. In the case of gases this is known as gas chromatography (GC) and for liquids it's LC, with the most popular one being HPLC (high performance liquid chromatography, or sometimes called high pressure liquid chromatography). This is actually a really fun thing to do as a project and I stumbled on this question because I want to make my own GC using the sensor you mentioned.
The principle is fairly simple. Most modern GCs have a carrier gas, usually an inert gas like nitrogen or helium, at a steady flow rate and it passes through a column. You inject your sample into this carrier gas flow and then your sample also passes through that column.
Most columns are packed with a material like silica gel or long alkanes (usually around 18 carbon atoms). Silica has more affinity for polar compounds (like alcohols) while alkanes have more affinity for non-polar compounds like butane, hexane, etc.
If you have a mixture of compounds, like in human breath or lighter fuel, they pass through that column at different rates depending on affinity for your stationary phase (the column) and also size of the molecules (heavier molecules like hexane pass through it more slowly than the lighter propane just due to size).
At the end of the column you get the gases coming out separately, depending on the quality of your separation with the ones being less retained by the column coming out first.
A small problem with this is that the separation takes time and can take up a lot of time depending on conditions. Most GCs operate at about 200 degrees Celcius to increase the speed but also to make sure that everything actually is in the gas phase.
For a hobby project I just want to do it at ambient temperature first using lighter gas (which I know is a gas at room temperature) and for a column I will use bentonite clay, which they used back in the old days before silica and it's cheap. Kitty litter is made from bentonite clay as well so it's easily available. As a carrier gas just normal air using for example an aquarium pump or other small membrane pump.


text:
How to send signal ONCE when within constant range of sensor?
I am working on a project to have a open/close a solenoid at certain ranges (using HC-SR04 ultrasonic sensor).
#include <NewPing.h>2

#define Relay1 7
#define Relay2 8

NewPing SonarRight(12, 11, 400);

void setup() {
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
}

void loop() {

  unsigned int uS1 = SonarRight.ping();
  delay(50);

  if (uS1 / US_ROUNDTRIP_CM > 15)
    digitalWrite(Relay1, HIGH);
    delay(100);
    digitalWrite(Relay1, LOW);
    delay(1000);

  if (uS1 / US_ROUNDTRIP_CM < 5)
    digitalWrite(Relay2, HIGH);
    delay(100);
    digitalWrite(Relay2, LOW);
    delay(1000);
}

I got the sensor to ping correct and the distances are reading accurately.  I have it to where once sensor reads that the object is more than 15cm away, the solenoid opens but it keeps clicking open until the object goes back to the dead zone (5-15cm).  Same thing when less than 5cm.  Essentially what i am trying to accomplish is to have the solenoid fill up a tank when the water level get low.  So when the water drops 10cm (x>15) the solenoid opens and then once the water is replenished (x<5), the solenoid closes.
How do i go about doing this without sending a constant OPEN/CLOSE to the solenoid?  Is there a way to make a loop to have it send a the signal only once until it exits that defined range?
Please note that i have not actually used it for its intended purpose im supply moving an object back and forth to simulate water distance.
Thanks

You have to add a (global) variable that stores the last send command (to open/close).
When you send a command, you save it in the global variable.
And you only send a command when it is different than the command send the last time, so only CHANGES are sent.
The best way to do this is to make a specific function, e.g. SetSolenoid(bool open);
#define SOLENOID_OPEN  TRUE
#define SOLENOID_CLOSE FALSE

bool _currentSolenoidStatus = false; // Assume closed

In your loop:
...
if  ... condition when solenoid should be be opened
{
    SetSolenoid(SOLENOID_OPEN);
}
...
if  ... condition when solenoid should be be closed
{
   SetSolenoid(SOLENOID_CLOSE);
}

Function to open/close solenoid open (only when changed):
bool SetSolenoid(bool status)
{
    if (_currentSolenoidStatus != status)
    {
        // Send status to solenoid
        _solenoidStatus = status;
    }
}


text:
ESP01 + Arduino UNO
I spent on this question more than 2 weeks of googling with no success.
I do not get a response from ESP8266 version 01 on AT commands.
I need to access Wi-Fi from Arduino via ESP8266-01. I know that ESP8266 can be programmed to work without Arduino and so on, but I need it to be a Wi-Fi module for Arduino. On most of the websites Arduino is used as UART for direct programming of ESP8266-01, but I am making this setup to make it work as a Wi-Fi support for Arduino:
  esp       Arduino
  ---       -------
   RX <---> pin 6 (TX) via voltage divider (5V-3.3V)
   TX <---> pin 5 (RX) (3.3V)
  Vcc <---> 3.3v
  GND <---> GND
CH_PD <---> 3.3V via 10k resistor
GPIO0 <---> 3.3V via 10k resistor
GPIO2 <---> 3.3V via 10k resistor

Then I upload this code on Arduino:

SoftwareSerial espSerial(5, 6);

const int COM_BAUD = 9600;

void setup() {
  espSerial.begin(COM_BAUD);
  Serial.begin(COM_BAUD);
  Serial.println("Setup done");
}

void loop() {
  if ( espSerial.available() )
    Serial.write( espSerial.read() );
  if ( Serial.available() )
    espSerial.write( Serial.read() );
}

It prints on AT monitor:
Setup done
But when I send AT command it is not even printed on AT monitor.
One more point -> New wifi called "AITHINKER..." is being created and I even connect to it, of course, this does not grant me access to the web. But this is a good sign telling that ESP8266-01 is working, both current and voltage are enough for operation.
So it does not respond or receives AT commands.
There is no documentation for correct connection of esp01 as wifi of Arduino Uno and I will be very happy if you could share some websites using ESP8266-01 as Wi-Fi of Arduino Uno correctly.
There are some points which are usually resolved other problems of such kind, but did not resolve mine:
- External power supply with common to Arduino ground -> done
- Change RX, TX pins -> done
- Replace ESP8266-01 -> having 5 of them, protecting from over voltage
Please, help me... Losing any hope on this...
P.S. It responds to AT commands when I connect it directly to the computer via USB UART cable.
The problem comes when I connect it to Arduino as the module...

How have you constructed your voltage divider?

30k is far too high. 220/430 may be too low. The best I have found is 1x1k + 2x1k (1k+2k).

@Majenko
I constructed voltage divider in 2 ways. First a 30k potentiometer with in of 5v and out of 3.3 v and typical voltage divider with R1= 220 and R2 = 430 ohms. In both ways I checked in and out voltage via multimeter

The AT command firmware for the ESP8266 modules have not always been set to 9600 bps. You might try 115200 and 57600 bps settings and see if that shows the result.
Also, connect the ESP8266 module directly to an FTDI or similar UART-USB bridge, temporarily eliminating the Arduino, so you can do more experimentation with the baud rates, etc. Then you would be able to easily see if the startup output from the ESP8266 looks garbled (which might indicate a serial speed mismatch), or if there is no output at all.
Another possibility is that the AIThinker module doesn't have the AT command firmware on it. From what source did you obtain the module -- what documentation is provided by that vendor?

Thank you for answering! Yes, I changed baud rates. Also forgot to tell that sometimes it prints me reset cause error #4. I am sure that it should response to AT commands since it does respond when I connect it via UART directly

@MadinaBektayeva: And those commands and responses were sent/receieved at 9600 baud, as in your sketch?

I see in your code example that you are echoing the regular serial port to the SoftwareSerial (ESP) port. Part of debugging would be to eliminate various things from your code to isolate the problem area. So, try eliminating that loop and just hard-code the AT command to send to the ESP8266.

@JRobert I changed them both in sketch and in serial monitor. Tried all of them and most of possible combinations which are >1200 &<115200

I have previously written an Instructables article about how to set up an ESP8266 ESP-01 Wi-Fi module available here: Definitive Guide to Setting Up Your New ESP01 Module, which includes more or less everything you need to know to set up and interface your ESP8266 chip with either your computer or your Arduino Uno (on step 4, which mentions that you should reduce the baud rate).
The main problems you might be facing right now are:

The Arduino Software Serial ports only support speeds up to 57600 baud if I'm not wrong, but the ESP-01 module typically comes out of the box with 115200 baud.
The Arduino 3.3V regulator may not have enough current to supply the ESP8266. It's a very power hungry chip relative to an Arduino. If you don't mind, do post a picture of your Arduino Uno (or compatible) so I know if it's a power supply issue.
The Arduino 3.3V pin does not provide adequate power supply decoupling, which may cause the ESP8266 to malfunction with cheap power supplies.

I designed a PCB called the ESPBlaster which you may be interested in. It takes a USB-TTL module on one side and has a socket for an ESP8266 module on the other to facilitate direct communications from your computer to the ESP8266 so you can set it to the correct baud rate so that you can interface it with an Arduino Uno, and contains a specially designed voltage regulator which does provides adequate current and decoupling.


text:
delay(time); vs if(millis()-previous>time); and drift
Going through an old project, I had code on two Arduino Due that looked like this
void loop()
{
  foo();
  delay(time);
}

taking to heart the majority of literature on using delay(); I recoded this as
void loop()
{
  static unsigned long PrevTime;
  if(millis()-PrevTime>time)
  {
    foo();
    PrevTime=millis();
  }
}

However, this seems to have created a situation where the two devices drift over a period of time when they didn't previously
My question is twofold:

Why would if(millis()-PrevTime>time) cause more drift than
    delay(time)?
Is there a way to prevent this drift without going back to delay(time)?

What is the order of magnitude of "period of time" over which you notice the drift? Are the two devices in the same location, thus at the same temperature? Are they run on a crystal oscillator or a ceramic resonator?

Personally I prefer Majenko's solution, and always use it (I put the incrementing before the other instructions, but this is just a preference). Note, however, that this timing is PRECISELY 100ms, while the other code (foo; delay;) has a period longer than 100ms (it is 100ms + time of foo). So you will experience drift (but it is the delay-implemented SW which is drifting). In any case, keep in mind that even perfectly equal implementations "drift", because clocks are not equal; if you need complete synchronization use a signal to, well, synchronize the two programs.

The two devices are next to each other, after running from Friday at 17:00 to Monday at 9:00 there was a 4 min drift.
I'm deciding that I'm going to use a digital pin to synchronize the inputs as per your suggestion

"The two devices are next to each other, ..." that doesn't mean the timing mechanism is not accurate you are talking about an error rate of ~800ppm, high for two crystal oscillators but reasonable for even one ceramic resonator. you have to compare it vs. a reasonably accurate timing standard to be sure: crystals are typically within 20ppm, and tcxo's can do sub 1ppm. that would be my way of doing it.

There's one important thing that you need to remember when working with time on an Arudino of any form:

Every operation takes time.

Your foo() function will take an amount of time. What that time is, we cannot say.
The most reliable way of dealing with time is to only rely on the time for triggering, not for working out when the next triggering should be.
For instance, take the following:
if (millis() - last > interval) {
    doSomething();
    last = millis();
}

The variable last will be the time the routine triggered *plus the time doSomething took to run. So say interval is 100, and doSomething takes 10ms to run, you will get triggerings at 101ms, 212ms, 323ms, etc. Not the 100ms you were expecting.
So one thing you can do is to always use the same time regardless by remembering it at once specific point (as Juraj suggests):
uint32_t time = millis();

if (time - last > interval) {
    doSomething();
    last = time;
}

Now the time that doSomething() takes will have no effect on anything. So you will get triggerings at 101ms, 202ms, 303ms, etc. Still not quite the 100ms you wanted - because you're looking for more that 100ms having passed - and that means 101ms or more.  Instead you should use >=:
uint32_t time = millis();

if (time - last >= interval) {
    doSomething();
    last = time;
}

Now, assuming that nothing else happens in your loop you get triggerings at 100ms, 200ms, 300ms, etc.  But note that bit: "as long as nothing else happens in your loop"...
What happens if an operation that takes 5ms happens to occur at 99ms...? Your next triggering will be delayed until 104ms. That's a drift. But it's easy to combat. Instead of saying "The recorded time is now" you say "The recorded time is 100ms later than it was". That means that no matter what delays you get in your code your triggering will always be at 100ms intervals, or drift within a 100ms tick.
if (millis() - last >= interval) {
    doSomething();
    last += interval;
}

Now you will get triggerings at 100ms, 200ms, 300ms, etc. Or if there are delays in other bits of code you may get 100ms, 204ms, 300ms, 408ms, 503ms, 600ms, etc.  It always tries to run it as close to the interval as possible regardless of delays.  And if you have delays that are greater than the interval it will automatically run your routine enough times to catch up with the current time.
Before you had drift. Now you have jitter.

Because you reset the timer after the operation.
static unsigned long PrevTime=millis();

unsigned long t = millis();

if (t - PrevTime > time) {
    foo();
    PrevTime = t;
}

no. notice that PrevTime is static.

@dannyf, yes, and?

if you knew what "static" means, you would know why your answer isn't correct.

I know what static does with local variable.. I do not understand why you think my answer has something to do with the static. I just moved the current millis reading before foo() is invoked.

For what you are trying to do, delay() is the appropriate way to implement the code. The reason you would want to use the if(millis()) is if you want to allow the main loop to continue to loop so your code or some other code outside of that loop can do other processing.
For example:
long next_trigger_time = 0L;
long interval = DESIRED_INTERVAL;

void loop() {
   do_something(); // check a sensor or value set by an interrupt
   long m = millis();
   if (m >= next_trigger_time) {
       next_trigger_time = m + interval;
       foo();
   }
}

This would run foo() on the specified interval while allowing the loop to continue to run in between. I put the calculation of next_trigger_time before the call to foo() to help minimize the drift, but it is inevitable. If drift is a significant concern, use an interrupt timer or some sort of clock/timer synchronization. Also remember that millis() will wrap around after some period of time and I didn't account for that to keep the code example simple.

Hate to mention this: rollover problem in 52 days.

I already mentioned the rollover issue at the end of my answer.

Well, solve it.

My standard consulting fee $100/hr if you want me to write code for you. I think what I have written is a sufficiently relevant.

Are you aware that Majenko posted a more complete and better answer that yours? Are you aware that your code doens't compile? That long m - millis() doesn't do what you intend to do? That's on the house.

Then vote for his answer if you like it better.

I fail to see the point in posting a deficient solution when a good one has already been accepted. Majenko's solution doesn't suffer from the rollover problem, and it shows that the drift is not “inevitable”, but rather very easy to avoid. This answer provides no added value.

@EdgarBonet, Majenko's solution doesn't discuss why you might choose to not use delay() even if it does cause drift. My code example was meant to highlight that, not provide a "complete" solution. So my answer does add value to the discussion, but I guess you didn't actually read my answer either.


text:
Combing two codes to make it work on the same time but not affecting the other code?
I am trying to make a game where there are arrows going towards an object (in this case I printed x) and you have to evade the arrows. When you press the button it is supposed to print x on the top row and clear the bottom row with printing nothing and if you don't press the button its supposed to print x on the bottom row and nothing on the top. Then the for loop is supposed to print arrows randomly going from right to left.
Problem: When I actually run the code I only see the x every time the arrow hits the (0,1) or (0,0) position.
I want the x to be there all the time.
#include <LiquidCrystal.h>
// init the lcd display according to the circuit
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

String line2 = " x ";
int xPosition;
int yPosition;
int yConstant;

void setup()  {
  lcd.begin(16, 2);
  // put your setup code here, to run once:
  int switchState = 0;
  pinMode(7, INPUT);
  int leftjump = 0;
  pinMode(8, INPUT);
}

void loop() {
  ///////////////////////////////
  //supose tp print arrow randomly going from right to left
  xPosition = 15;
  yPosition = random(0, 10);
  if (yPosition > 5) {
    yConstant = 1;
  }
  else yConstant = 0;
  lcd.setCursor(xPosition, yConstant);
  for (int xPosition = 15; xPosition > 1; xPosition--) {
    lcd.print("<-");
    delay(100);
    lcd.clear();
    lcd.setCursor((xPosition), yConstant);
  }
  ////////////////////////////
  // suppose to print x on the top row and print nothing on buttom row
  //and otherwise when button is not pressed print x on bottom and
  //print nothing on top row
  int rightjump = 0;
  rightjump = digitalRead(7);
  if (rightjump == 1 ) {
    lcd.setCursor(0, 0);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 1);
    lcd.print("  ");
  }
  else if ( rightjump == 0 ) {
    lcd.setCursor(0, 1);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 0);
    lcd.print("  ");
  }
}

There is one big problem with your program, and it is here:

delay(100);

Using delay() is bad practice. The Arduino does nothing useful while
delaying. Quite importantly, it cannot respond to user input. And to
make matters worse, you have this delay inside a loop. This means your
program will be stuck inside the loop for 1.4 seconds. And during
this time it will not take care of reading the button, nor drawing the
player on the screen.
The solution is to use millis() to manage your timings, and never
block your program while waiting for something. The approach is well
explained in the Blink Without Delay Arduino tutorial. In a
nutshell: on every loop iteration, you check the clock and, if it's time
to do some particular task, you do it. If it's not time, well, you
simply don't do it. Most importantly: you don't wait. If you don't do
something on this loop iteration, no worries, you will do it on some
other iteration.
With this approach, there are some pieces of information (e.g. arrow
position) that will have to be remembered from one loop iteration to the
next. This can be done by storing that in global variables. I prefer to
to use static local variables though, to keep the information confined
to where it belongs.
Here is my try at your loop(). Notice that both the arrow and the
player are managed through the same pattern:
if (it needs to be updated right now) { update it; }
void loop() {
    static uint32_t last_arrow_move;  // last time the arrow moved
    static int arrow_x, arrow_y;
    const int player_x = 0;
    static int player_y;

    // Update the arrow position every 100 ms.
    if (millis() - last_arrow_move >= 100) {
        last_arrow_move += 100;

        // Erase the arrow at its old position.
        lcd.setCursor(arrow_x, arrow_y);
        lcd.print("  ");

        // Move one cell to the left.
        arrow_x--;

        // If too far left, then send a brand new arrow.
        if (arrow_x < 2) {
            arrow_x = 15;
            arrow_y = random(0, 2);
        }

        // Draw the arrow at its new position.
        lcd.setCursor(arrow_x, arrow_y);
        lcd.print("<-");
    }

    // Get the updated player position.
    int new_player_y;
    if (digitalRead(7) == HIGH) {  // "jump" button pressed
        new_player_y = 0;
    } else {
        new_player_y = 1;
    }

    // Update the player if he moved.
    if (new_player_y != player_y) {

        // Erase the player at its old position.
        lcd.setCursor(player_x, player_y);
        lcd.print(" ");

        // Move.
        player_y = new_player_y;

        // Redraw at the updated position.
        lcd.setCursor(player_x, player_y);
        lcd.print("x");
    }
}

You have a nested loop. When your for loop is finished moving the arrow to column 0 then, and only then, the " x " is displayed, exactly as predicted. You can start by drawing the x from inside the for loop (before the delay) that will make it visible all the time.
It's a start anyways.

Combing two codes to make it work on the same time but not effecting the other code?

the simplest would be to have two arduino and run each piece on one of them.

is there a way to it with one arduino because i need it on one lcd, the only problem is that i need the x to be there all the time.

technically, no. arduino has one execution unit so at any given point in time, it is either running code A, nothing else. for you to run both pieces on one arduino, you have to relax your constraints. no other way around that.

it runs on both but i just need the x to show all the time.

Is there a way to show the x all the time, without having it clear with the for loop.


text:
Error: `nullptr` was not declared in this scope. Arduino IDE
I try to use this ArduinoThread library. In the Arduino I go Sketch->Import Library->ArduinoThread. After that I have the following line in the beginning of the sketch:
#include <ThreadController.h>
#include <Thread.h>
#include <StaticThreadController.h>

I leave setup() and loop() empty and try to verify or upload the sketch on my Arduino board. But I get the following errors:

Is this about the library or I do something wrong?

How old is your Arduino setup?  Maybe https://stackoverflow.com/questions/24845127/error-constexpr-does-not-name-a-type-m-arduino-ide would help

I am using Arduino 1.8.5. I think it is pretty recent, isn't it?

It works with 1.6.8 and 1.6.9 those are the ones I have and it compiles without errors.

What do you have selected in the Tools > Board menu? You should always post text as text, not a picture of text.

Sorry for that. It turned out I was using old version of Arduino IDE indeed. Seemingly, I have installed IDE twice. Two different versions. One manually and other is by apt-get. arduino command, of course, was for the old version. Now it works. Thank you.

Please write an answer to your question to help out anyone else who also encounters this issue.

I installed Arduino IDE in two different ways (only god knows why). The first one was via using of manager apt-get and other was manually via downloading, unzipping and installation through the install.sh file.
It seems that on Ubuntu 14.04 the
sudo apt-get install arduino

command provides an installation of an old version of Arduino IDE.
So eventually I was launching Arduino IDE by arduino command in my terminal (actually I was using d-menu in i3). No surprise it ran the old one installed by apt-get. I just removed that version by
sudo apt-get remove arduino

And now I am using executable arduino inside unzipped folder. Actually, I am not using Arduino IDE explicitly at all. I am using a Makefile from here.


text:
Help: Using if-else on two switch state
Problem
I'm stuck on triggering different switch. I'll explain what each of  my switch should do. Output of this setup : No output from relayPin
mainPin

Main power of the switch to control relayPin — keeps on/off
Override reedPin state
Let SecondState

reedPin

Secondary power switch to control relayPin — depends on mainPin on/off state
Overridden by mainPin
Let FirstState

*another explanation in comment
Is it caused by coding or hardware? Pardon my ignorance, it is my beginner code. I would appreciate any help, thank you.
Code
const int reedPin = 8; // Reed Switch
const int mainPin = 9; // Main Switch
const int relayPin = 6; // Relay

int FirstState = 0;
int SecondState = 0;

void setup() {
    pinMode(relayPin, OUTPUT);
    pinMode(reedPin, INPUT);
    pinMode(mainPin, INPUT);

}

void loop() {
    FirstState = digitalRead(reedPin);
    SecondState = digitalRead(mainPin);
    if (FirstState == HIGH) {
        digitalWrite(relayPin, LOW);
    }
    else if (SecondState == HIGH) {
        digitalWrite(relayPin, HIGH);
    }
    else {
        digitalWrite(relayPin, HIGH);
    }
}

Only else if (SecondState == HIGH) { works in output.
Schematics

Your problem statement is very hard to understand. A pair of switches can be in four different states (off/off, off/on, on/off, on/on): please clearly state what the program should do in each of these four cases. 2. Do not connect the relay directly to the Arduino: first search the Web for “connect relay to Arduino”, then use a suitable transistor.

Thank you for your response, actually I'm using relay alone on schematics because I'm using module instead. There is 2 switch, first one acts like normal and override second switch which are reed switch. IF first one is on, then second one has a function to on/off. IF the first one is off, then second one has NO function

Only you know what “first one acts like normal and override second switch” means. Again, please, tell us what the Arduino should do in each of the four possible situations. If you are unable to tell us what your Arduino should do, then you will never be able to program it to do what you want.

Alright, first switch SW1 is main switch - referred as firstState in code.
when this is off, U1 (referred as secondState in code) has no function
What U1 does is simple on/off (reed switch).
What SW1 does enables U1 function
Sorry for confusion.

The first one "enables" the second one ? You are missing a pinMode(switchMain, INPUT). Please use 'relayPin' instead of 'relaySwitch'. Use consistant names for everything. Please use always the same name for the first one, second one, and so on. Both in your sketch and in your explanation. Update your question and the sketch as well.

Draw a truth table and look at it from there.  From your words, it is confusing.  From your code it looks like this:
mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     HIGH

So:
void loop() {
      digitalWrite(relayPin, !digitalRead(mainPin));
}

If you want:
mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     LOW

then:
void loop() {
      digitalWrite(relayPin, !(digitalRead(mainPin) || digitalRead(reedPin)));
}