text:
Read float and long from external EEPROM chip
I am using an Arduino to read information from an EEPROM chip over I2C with the code I found here:
https://playground.arduino.cc/Code/I2CEEPROM
It works great for int and char values but I also need to read short, long, and float values.
They are stored in this order:  1510543923
is stored as: 01011010 00001001 00010010 00110011
How can I read multiple bytes into a single variable of these types?
I tried the following but it gives me a 16 bit number:
i2c_eeprom_read_buffer(0x50, 25, (byte *)bytes, 4);
long j = (bytes[3] << 0) + (bytes[2] << 8) + (bytes[1] << 16) + (bytes[0] << 24);

By treating the variable as a sequence of bytes.

Or use a template function. You could modify this for I2C EEPROM https://playground.arduino.cc/Code/EEPROMWriteAnything

1510543923 is stored as: 01011010 00001001 00010010 00110011

This is known as “big endian”, or “MSB first”, because the most
significant byte (MSB, here 01011010) comes first.
I recommend against this order. If you can, swap all the bytes and store
the value LSB first, i.e. with the least significant byte first, and the
most significant byte last. This will make your life easier since it's
the order used internally in the Arduino. If you can go little endian,
then you will be able to read the data straight into the required
variable, with no conversion needed, as in:
i2c_eeprom_read_buffer(0x50, 25, (byte *) &j, sizeof j);

and it will work identically with any data type.
If you cannot choose the byte order (maybe you cannot control what is
inside the EEPROM), then you will have to reverse all the bytes. You can
do this either with bit shifts or by explicitly moving bytes.

bytes[1] << 16

This will not work. Per the rules of the C++ language, bytes[1] is
implicitly promoted to int type before the shift, then it is shifted
as an int. But on your Arduino an int is 16-bits long, thus by
shifting it 16 positions you are dropping off all of the bits.
Actually, this is even worse: you are invoking what is known as
undefined behavior, meaning that it is considered nonsense and the
compiler is free to interpret however it wants.
To do this properly, you first have to explicitly cast bytes[i] to
unsigned long. It has to be unsigned because changing the sign bit on
a long by bit shifting is also undefined behavior. Thus, the proper
way of reconstructing the number via bit shifts is:
long j = ((unsigned long) bytes[3] << 0)
       | ((unsigned long) bytes[2] << 8)
       | ((unsigned long) bytes[1] << 16)
       | ((unsigned long) bytes[0] << 24);

This is portable (it should also work on big-endian architectures) but
only works with integral types, not with floats.
For reconstructing a float, my preferred option would be to use a
union, in order to access the bytes of the variable explicitly. Then
you just have to copy the bytes from the buffer to the union in
reverse order:
union { float f; byte b[4]; } data;
data.b[0] = bytes[3];
data.b[1] = bytes[2];
data.b[2] = bytes[1];
data.b[3] = bytes[0];
float x = data.f;

One nice thing about this approach is that it works with any data type.

In reading the float, I correctly get 00110101-00111000-10101000-11001110 from the EEPROM but running it through the union snipit you show, gives 0.0. It should be 6.8790985E-7.

@Alphy13: I am pretty sure you got the correct number. However, Serial.println(6.8790985e-7); prints “0.00”.

Thanks for pointing that out. In case anyone has a similar issue: Serial.println(x, 10); gave the precision i needed to see a result.

It gives you a 16-bit integer because the compiler automatically makes casts. In particular:

byte << int returns int
int + int returns int

So your (bytes[1] << 16) is converted to an int, and consequently gets zeroed.
I tried to simulate this code; the results are shown as comments
int a = 0x1234;
long b = a << 8;
long c = a << 8L;
long d = ((long)a) << 8;
Serial.println(a); // a is 0x1234
Serial.println(b); // b is 0x3400
Serial.println(c); // c is 0x3400
Serial.println(d); // d is 0x123400

Personally I'd bet that int << long would result in a long, but apparently I'm wrong.
In any case, you should write
long j= (bytes[3] << 0) + (bytes[2] << 8) + (((unsigned long)bytes[1]) << 16) + (((unsigned long)bytes[0]) << 24);

This should fix your error. In any case, you can also simply write
long write_value;
i2c_eeprom_write_page(0x50, 25, (byte *)&write_value, sizeof(write_value));
long read_value;
i2c_eeprom_read_buffer(0x50, 25, (byte *)&read_value, sizeof(read_value));

Please note that accessing directly the pointers, like in this case, will respect the endianness of the compiler. In the case of a big endian implementation, the long with value 0x12345678 will be saved as 12 34 56 78, while with a little endian implementation it will be saved as 78 56 34 12. This is not a problem if you always use the same platform, but if you are trying to transfer information over a network you will have to ensure that all the devices have the same endianness or manually correct it

Please note that (((long)bytes[0]) << 24) is undefined behavior if bytes[0] happens to be larger than 127. You should use unsigned long instead.

@EdgarBonet totally agree, my bad. I fixed it in the answer. Thank you

Using template functions this could be written as:
template<class T> void i2c_read(uint16_t addr, T& x)
{
  i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(T));
}

template<class T> void i2c_write(uint16_t addr, T& x)
{
  i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(T));
}

These two functions take the data type as template parameter. Some examples:
  long x = 0x12345;
  i2c_write<long>(0, x);

  long y = 0;
  i2c_read<long>(0, y);

With auto the functions could be written as:
void i2c_read(uint16_t addr, auto& x)
{
  i2c_eeprom_read_buffer(0x50, addr, &x, sizeof(x));
}

void i2c_write(uint16_t addr, auto& x)
{
  i2c_eeprom_write_buffer(0x50, addr, &x, sizeof(x));
}

With auto the compiler will determine the data type.
Cheers!

How can I read multiple bytes into a single variable of these types?

use a pointer to read each byte of a multi-byte type and save it into eeprom;
then do the same in reading them back: use a pointer to re-assemble the data (in bytes).
sizeof() comes in handy here.
Edit: lots of wonderfully complex answers for something this simple. When I get sometime I will pin my approach down.
Btw, many i2c libraries allow blocked read or write. So take that into your coding consideration.
edit2:
so here is what I have, to demonstrate how pointers can be used to write / read data.
//simulated write to buffer
//write n bytes of data from *ptr to address starting with addr
void mem_write(char addr, char *ptr, char n) {
    do {buffer[addr++] = *ptr++;} while (n--);
}

//simulated read from buffer
void mem_read(char addr, char *ptr, char n) {
    do {*ptr++ = buffer[addr++];} while (n--);
}

in this particular example, mem_write() writes n bytes of data, from source pointer ptr, into buffer[] starting at address addr. the read does the same.
you can port in your i2c byte read / write routines here, or use block read/write routines for more efficiency.
to confirm that it works, I wrote the following:
void setup() {
    Serial.begin(9600);         //initialize serial transmission

    dat.x = 1; dat.z = 3.0;     //initialize dat
    dat_ptr = (uint8_t *)&dat;  //initialize pointers
    dat_ptr1= (uint8_t *)&dat1;

    //print serial
    Serial.print("line 0: size = "); Serial.print(sizeof dat); Serial.print(", x = "); Serial.print(dat.x); Serial.print(", z = "); Serial.println(dat.z);

    //round 1: similated eeprom write/read
    mem_write(0, dat_ptr, sizeof dat);                  //write to buffer
    dat1.x = 0; dat1.z = 0;                             //initialize dat1
    mem_read(0, dat_ptr1, sizeof dat1);                 //read from buffer
    //now, dat1 contains the same data as dat
    //print dat1 on serial -> it should read identical to line 0
    Serial.print("line 1: size = "); Serial.print(sizeof dat1); Serial.print(", x = "); Serial.print(dat1.x); Serial.print(", z = "); Serial.println(dat1.z);

    //round 2: similated eeprom write/read
    //slightly different way of doing the same
    dat.x +=1; dat.z +=10.0;                            //x=2, z=13.0
    mem_write(0, (char *)&dat, sizeof dat);             //write to buffer
    dat1.x = 0; dat1.z = 0;                             //initialize dat1
    mem_read(0, (char *)&dat1, sizeof dat1);            //read from buffer
    //now dat1.x = 1+1=2, dat1.z = 3.0+10.0 = 13.0
    //print dat1 on serial
    Serial.print("line 2: size = "); Serial.print(sizeof dat1); Serial.print(", x = "); Serial.print(dat1.x); Serial.print(", z = "); Serial.println(dat1.z);

}

it essentially writes one data element "dat" into the buffer, and read it back into "dat1"; both items are printed over serial to confirm that the write / read are successful.
then I incremented on dat, and wrote it to buffer and read it back to dat1. again, printed dat1 on the serial monitor to confirm that we have the right result.
here is what I got:

so we have the expected result.
the approach here is fairly standard. Obviously, experts usually come up with far more complex ways of doing simple things, as shown earlier answers, :)

About your simple/complex dichotomy: Both @frarugi87's answer and mine cover both the simple case (same endianness on the EEPROM and on the CPU), and the case when you have to swap the bytes. Your answer is simpler because you only covered the simple case. Notice that I explicitly recommended using the same endianness, precisely because it makes things simpler. But the “experts” know that you don't always have the choice.


text:
Blend with SD Shield
Building a data logging and transmission system here. I've a RedBearLab Blend with built-in BLE capabilities and a (cheap) SD / Data logging shield that looks very suspiciously like it's copied from the Adafruit one.
Using a Stock Arduino Uno board, the Data logging shield works out of the box - both RTC TimeSet and cardinfo come back successfully.
Stacking the shield on the Blend, both examples lead nowhere. The TimeSet states that no connection could be made, and the cardinfo says it can't find the card.
I assume it's a pin conflict of some sort, but I'm really unsure what I should do to debug/fix it.
[edit] As I found out below, the SD Module works now - but I still face the problem of not getting the RTC to work. Neither on the shield nor a Tiny RTC module. Again, both work fine on the Arduino Uno.
[edit2] I had basically the same problem for the RTC module as well - see the answer below.

Sometimes it helps just adding the tags.....
The Blend is a Arduino Leonardo Chip -
and as Lady Ada helpfully points out, you need a special SD Library to use this. The advice on https://learn.adafruit.com/adafruit-data-logger-shield/for-the-mega-and-leonardo is everything I needed to get the cardinfo working, especially the     while (!card.init(SPI_HALF_SPEED, 10, 11, 12, 13)) {
part.
Also, the I2C Pins for the RTC Clock are not the "standard" Analog Pins 4 and 5, but D2 and D3 (see http://arduino.cc/en/Reference/Wire)

source: Stack Exchange

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

sort: votes


text:
Arduino subtracting chars from strings
Hello I have an Arduino programme that has a string with the words hello in it.
I can add characters and other strings to the end of that one using:
   String test = "hello";
   test+=" jack";

it would then say "hello jack"
The problem is I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

You may use remove() method to remove last character.
String s = "1234567890";
while(s.length() > 0) {
    int lastIndex = s.length() - 1;
    s.remove(lastIndex);
    Serial.println(s);
}

Could you please include an example to your answer?

@Avamander Example provided. :)

Two typos there: Sstring and lenght.

I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

This is how you could do that. Avoid using String and putting the string constants in program memory.
// A buffer for the message
const size_t MSG_MAX = 16;
char msg[MSG_MAX];

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

void loop()
{
  static int len = 0;
  // Check if it is time to create the initial message
  if (len == 0) {
    strcpy_P(msg, (const char*) F("hello"));
    strcat_P(msg, (const char*) F(" jack"));
    len = strlen(msg) - 1;
  }
  // Otherwise shorten the message
  else {
    msg[len--] = 0;
  }
  // And print current message
  Serial.println(msg);
  delay(2000);
}

You are best of learning about C-style strings rather than the String class. The String class can eventually fragment dynamic memory.
To shorten a string a simple method is to move the "string terminator" inwards by overwriting the last byte of the message with zero, like this:
const size_t MSG_MAX = 20;
char msg [MSG_MAX];

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  strcpy (msg, "hello");  // initial message
  strcat (msg, " jack");  // concatenate more stuff
  }  // end of setup

  void loop ()
    {
    if (strlen (msg) > 0)
      {
      Serial.println (msg);  // display current message
      msg [strlen (msg) - 1] = 0;  // move null-terminator in
      delay (1000);
      }  // end of any message left

    }  // end of loop

Results:
hello jack
hello jac
hello ja
hello j
hello
hello
hell
hel
he
h

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


text:
Arduino radio communications
I have an Arduino and I am building a space satellite, just for fun. I'm not going to launch it obviously.
I have built all the sensors and everything works. I was looking into communication because if a satellite is in space it needs to send down the data.
Is it possible to have radio communication between two Arduino or an Arduino and something else that are 100km apart, it doesn't need to particle, I'm just wondering if it is possible and how it works. Is it possible without going out to buy shields?

There are three basic factors that control long distance communication:

Transmitter Power
Receiver Sensitivity
Signal Directionality

The more transmission power you have the "louder" your signal is at the receiver.
The more sensitive your receiver the "quieter" the signals it can pick up.
The more directional (focussed) your signal is the more arrives at the receiver and the less gets sent off elsewhere.
So you would think get all three of those and you're laughing, but it's not that simple:

High power transmission requires high-power power source
Good focus requires heavy and bulky antennae.

Neither of those are very good on a satellite, since you want it to be as small and light as possible and use as little power as possible.
So in general you have a medium to low power transmitter on the satellite with reasonable directionality, and put all the bulk on earth.  That is why satellite dishes are so big.  They give good focus, and the large size captures a lot of the signal making them more sensitive. You can also use very precise electronics to amplify the signal more.
There is, of course, nothing like that in a shield format, so you would have to create your own. The transmitter isn't so hard, since you don't want to have anything too meaty - the hard part comes when you want to make the base station.  If you can afford enough power to transmit a strong enough signal and have it with enough directionality you can use a satellite TV dish (not a little Sky dish, one of the bigger solid round ones - Sky satellites actually have quite powerful transmitters and the massive solar panels to go with it; not really practical for a small home-built satellite).  Getting the receiver and LNB (Low Noise Booster) tuned properly as well is vital - unless you're transmitting at the same frequency as the satellite the dish is intended to receive (which you mustn't or there'll be a lot of annoyed people around - there are specific frequency ranges you are allowed to use) then you will need to ensure the antenna is exactly the right length and that the LNB amplifies and filters the right frequency range.
Once you have got over all those hurdles the receiver is just a simple receiver.
The actual transmitter and receiver circuits themselves can be something fairly off-the-shelf (the lower the frequency the better since that goes further than higher frequencies) - it's what goes between - the antenna and amplifier - that makes it much more special and long range.

Majenko covered several aspects of radio communications between a satellite and a ground station.  An additional factor to consider is that the azimuth or altitude of a low-altitude satellite changes rapidly as it passes over a ground station.  For example, a satellite 100 km up takes about 86 minutes per orbit and travels at about 7.84 Km/s, and probably would be in view for less than a minute per pass.  [See eg Orbit of a satellite Calculator at casio.com.]  Unless a phased array is used, and assuming communication is highly directional, the big dish on the ground will need to swing at up to 4.5° per second (about 270° per minute) as it tracks the satellite passing over.  The much smaller antenna on the spacecraft should rotate at the same rate, the opposite direction.
Note, an alternative to radio communications is a tight-beam laser system.  Rather than using big, bulky microwave or UHF antennas to achieve directionality, you would use a small telescope (a few cm of aperture) on the satellite and a larger telescope (as much aperture as you can afford) at the ground station.  Infrared or visible light lasers at each end of the link would be modulated to transmit at a high data rate.  Accurate tracking and aiming might end up being important research projects for this approach.


text:
This error is shown continuosly after first time it compiles successfully
I got this error:
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"
Multiple libraries were found for "LiquidCrystal.h"  Used: C:\Program
Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal
Not used:
C:\Users\siddh\OneDrive\Documents\Arduino\libraries\libraries readlink
C:\Users\siddh\OneDrive\Documents\Arduino\libraries\SimpleDHT\SimpleDHT.cpp:
The system cannot find the file specified. Error compiling for board
Arduino/Genuino Uno.

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

This is the code i use:
//We'll start by adding our libraries

 #include <LiquidCrystal.h>

 #include <SimpleDHT.h>

//Declaring digital pin no 6 as the dht11 data pin

int pinDHT11 = 6;
SimpleDHT11 dht11;

//Declaring the lcd pins

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
// Don't forget to choose 9600 at the port screen

  Serial.begin(9600);

//Telling our lcd to start up

  lcd.begin(16, 2);

}

void loop() {

  //These serial codes are for getting readings on the port screen aswell as the LCD display, since they'll offer us a more detailed interface

  Serial.println("=================================");
  Serial.println("DHT11 readings...");
  delay(2000);

  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;

  //This bit will tell our Arduino what to do if there is some sort of an error at getting readings from our sensor
  if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("No reading , err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("temp: ");
  Serial.print((int)temperature); Serial.print(" Celcius, ");
  Serial.print("humidity:");
  Serial.print((int)humidity); Serial.println(" %");

  //Telling our lcd to refresh itself every 0.75 seconds
  lcd.clear();

 //Choosing the first line and row

 lcd.setCursor(0,0);

//Typing Temp: to the first line starting from the first row
  lcd.print("Temp: ");

//Typing the temperature readings after "Temp: "
  lcd.print((int)temperature);

//Choosing the second line and first row
  lcd.setCursor(0,1);

//Typing Humidity(%): to the second line starting from the first row
  lcd.print("Humidity(%): ");

//Typing the humidity readings after "Humidity(%): "
  lcd.print((int)humidity);

  delay(750);
}

You should post your entire output, not just the last couple of lines. The error itself is invariably one of the first things printed, not the last. Als you should do as it suggests and turn on verbose output.

There is a bug that causes this error when you use the Arduino IDE with files located under OneDrive.
The simplest solution is to move any files that will be used with the Arduino IDE out of OneDrive to any other convenient location on your computer. It looks like you have your sketchbook folder located in the OneDrive so you will want to change that via the Arduino IDE's File > Preferences > Sketchbook location. The Arduino IDE does not automatically move the files from the previous sketchbook folder to the new folder so you will need to either move any files to the new sketchbook folder or else reinstall them.
There are some possible workarounds if you want to to continue using the Arduino IDE with OneDrive listed in the issue report:
https://github.com/arduino/arduino-builder/issues/254

I have had this problem as well and I concur with per1234 that the solution (for now) is that you have to move your sketches out of the OneDrive folder.
You used to be able to have your sketches within OneDrive (I did for many years). Since release 1.6.6 things have changed and you can no longer compile files that you once used to be able to compile inside a OneDrive folder.
In addition to per1234's great answer (ie move the sketches outside of the Ondrive folder) there are 2 other options. Firstly you could download and install version 1.6.5 which was before the Arduino Builder was incorporated. The other option is to use the Beta V1.9.0 avalable from the Beta Channel.

UPDATE:
The issue with OneDrive folders has been resolved as of version 1.8.6.
https://www.arduino.cc/en/Main/ReleaseNotes

ARDUINO 1.8.6 2018.08.23
[ide]

Updated arduino-builder to 1.4.0:

parallel build (improve compile speed)
better reuse of already compiled files
Windows: fixed build for sketch stored under OneDrive cloud folders

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.

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


text:
How to convert this sketch to keep only one if-else statement?
int ldrPin = A0;
int rainPin = A1;
int smokePin = A2;
int greenLED = 6;
int redLED = 7;

// you can adjust the threshold value
int thresholdValue = 500;
int LightSensorThreshold = 500;
int RainSensorThreshold = 500;

void setup() {
  pinMode(ldrPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(rainPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(smokePin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int rainSensorValue = analogRead(rainPin);
  Serial.print(rainSensorValue);

  if(rainSensorValue < RainSensorThreshold){
    Serial.println(" - It's wet");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - It's dry");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int smokeSensorValue = analogRead(smokePin);
  Serial.print(smokeSensorValue);

  if (smokeSensorValue < thresholdValue) {
    Serial.println(" - Smoke");
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, HIGH);
  }
  else
  {
    Serial.println(" - No Smoke");
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, LOW);
  }
  delay(100);

}

Sure:
Change these int's to byte, none have values more than 255:
int ldrPin = A0;
int rainPin = A1;
int smokePin = A2;
int greenLED = 6;
int redLED = 7;

Take these out of setup(), analog input pins don't need this:
pinMode(ldrPin, INPUT);
pinMode(rainPin, INPUT);
pinMode(smokePin, INPUT);

Take out the duplicates of these lines, pinMode() and turning them off (if LOW is off) only needs to be called once for each
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);

Get rid of two the Serial.begin(9600) lines, calling it once is enough.
Within loop(), get rid of the int's. Those variables were already globally declared, you don't need to re-declare them as type int.

how to edit those if else statement as one.

First find the duplicated code.
E.g. the fragment
  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

is repeated three times.
Then find within the duplicate code fragments, the differences, which are:

the pin number
the value to check against.
the two texts

Then make a new function containing one duplicated code fragment, and replace the differences, by variables which you pass in the function as arguments:
void checkSensor(int pin, int sensorLimitValue, char* okText, char* warningText)
{
  int sensorValue = analogRead(pin);
  Serial.print(sensorValue);

  if(sensorValue < sensorLimitValue) {
    Serial.println(okText);
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  else {
    Serial.println(warningText);
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  delay(500);
}

And call respectively:
checkSensor(ldrPin       , LightSensorThreshold, " - light"   , " - dark");
checkSensor(rainSensorPin, RainSensorThreshold , " - it's wet", " - it's dry");
checkSensor(smokePin     , thresholdValue      , " - Smoke"   , " - No Smoke");

I switched the green/red values, because I assume when the value is lower than the limit, the green LED should be on, and otherwise the red LED.
Btw, why not use smokeSensorThreshold instead of thresholdValue to keep it consistent with the other duplicated code fragments?

I've got a problem with those sketches. The greenLED is turned on and when those sensor sense something it will just turn to redLED. The sketch output is those LED is alternating. Can you help me edit my skectch?

I don't understand what you mean exactly, but I now see the Red light is on when the sensor value is too high, maybe you want to switch green and red, I will do it in my answer

You're welcome!

I'd suggested the smokeSensorThreshold yesterday, not sure why OP hasn't used it...

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


text:
Problems on convert byte[] to String
I'm reading a RFID Card from RC522 and send the data to my computer. My problem is the conversion of byte[] to String or std::string.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {0};
byte tam = SIZE_BUFFER;

// get data
status = mfrc522.MIFARE_Read(bloco, buffer, &tam);

  Serial.print(F("\nDados bloco ["));
  Serial.print(F("]: "));

// printing...
 for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      Serial.write(buffer[i]);
      str += String(buffer[i]);
  }

OUTPUT:
Dados bloco []: asdas

So, it's ok! But if I try make a string:
  String str = "";

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      str += String(buffer[i]);
  }
  Serial.println(" ");
  Serial.println(str);

The output is:
97115100971153232323232323232323232

What is the correct way to create a String from byte[]?

byte and char are the same. If you set 0 as string terminator after last character in the buffer, you get a zero terminated string. If you really must use String, you can create an instance with a constructor that takes zero terminated string.
buffer[tam] = 0;
String str((char*) buffer);

Let in the buffer a place for the zero. (char*) is cast that says that the byte array is a char array.
Note: Don't use String class in a MCU, use zero terminated character arrays.

I just need the value, but String is easy to send via Bluetooth. I can send char too, but I don't know to convert.

set 0 as string terminator after last character in the buffer. but let space for it. if the RFID numbers are 18 chars, then allocate 19

If you change str += String(buffer[i]); to str += (char)buffer[i];, it will print the ascii characters to the serial monitor.
The following sketch can be used to see the difference in binary compiled size using these two methods of "adding to the string".
// 4026 to 3758 bytes.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {
  0x61, 0x73, 0x64, 0x61,
  0x73, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20
};

String str = "";

void setup(){

  Serial.begin(9600);

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      // 4026 bytes. Prints: "97115100971153232323232323232323232"
      //str += String(buffer[i]);

      // 3758 bytes. Prints: "asdas           "
      str += (char)buffer[i];
  }
  Serial.println(" ");
  Serial.println(str);
}

void loop(){}

Casting each element in the byte buffer to Char, then adding it to the string drops the binary compiled size from 4026 to 3758 bytes. This is good, but we can really improve the sketch by not using the String object at all.
This sketch is the same as the first one, except it uses a Character Array instead of a String.
// 2074 bytes.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {
  0x61, 0x73, 0x64, 0x61,
  0x73, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20
};

// Use a char array instead of the String object.
char outputBuffer[SIZE_BUFFER];

void setup(){

  Serial.begin(9600);

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      // 2074 bytes. Prints: "asdas           "
      outputBuffer[i] = (char)buffer[i];
  }
  Serial.println(" ");
  Serial.println(outputBuffer);
}

void loop(){}

The binary compiled size is 2074 bytes. That's 1684 bytes less than using the String object.
There are many functions available to work with Character Arrays on an Arduino, such as http://www.cplusplus.com/reference/cstring/ and http://www.cplusplus.com/reference/cstdlib/.


text:
Read only selected Packet SoftwareSerial
I am reading data from RS485 which is in the following format:
void sendkwh()
{
  RS485Serial.write((byte)0x01); // Meter Address
  RS485Serial.write((byte)0x03); // Read Function Code
  RS485Serial.write((byte)0x40); // Register Address Variable (Start address high bit)
  RS485Serial.write((byte)0x34); // Register Address Variable (Start address low bit)
  RS485Serial.write((byte)0x00); // Register Quantity (High Bit)
  RS485Serial.write((byte)0x02); // Register Quantity (Low Bit)
  RS485Serial.write((byte)0x90); // CRC check code (CRC code Low bit)
  RS485Serial.write((byte)0x05); // CRC check code (CRC code High bit)
}

and I need to read only the 4th and 5th frame of the packet. I am doing it the following way:
RS485Serial.listen();
  if (RS485Serial.available() > 0)
   {

    if(RS485Serial.read() == 0x01)
    {
    for(int i=0; i<4; i++) {

   byte discard = RS485Serial.read();

   }
    byteReceived = RS485Serial.read(); // 4th frame
    byteReceived2 = RS485Serial.read(); // 5th frame

which is working fine. I wanted to know if there is a method to discard the packets without loop?
As in I have changed the sendkwh() as below:
byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };
RS485Serial.write(SendKWh, sizeof(SendKWh));

But don't know how to proceed with tapping the 4th and the 5th frame. Your help is appreciated.

What are the significance of the other bytes in the packet?

But the 4th and 5th frame actually needs to be sent to a server later in the code

If there was no significance they wouldn't exist. What do they all mean? As in - is there a packet header? A checksum? A packet length? What?

In a nutshell: your current reading methodology is seriously flawed and you're lucky it works at all.

Ok, sorry I didn't get your question at first. The other bytes have significance, as in Meter Address, Function Code, CRC code , etc

Can you suggest me how to improve it, or a reading that I may go through. Request your help on this!

That much is obvious. But you still haven't answered me. For me to help you I need to know precisely what the meaning of each individual byte is within the packet. Not just an "oh, it's such and such and such and such", but a list of "The first byte is... The second byte is... The third byte is..." etc, including how they are calculated (in the case of a CRC) or statically defined.

I am updating the question @Majenko

Your reading methodology is flawed from the start and you need to completely change how you do things.  First off, you wait until there is at least one byte in the incoming buffer, then if that byte is 0x01 you then try and read 5 more bytes - even if there is only (say) 2 bytes in the buffer.
Instead you need to set up a sliding window for receiving the data. A sliding window is basically an array that is the same size as the data you are receiving, and as bytes become available they work their way down from the "top" to the "bottom" of the array. When the contents of the array match a certain pattern you know it is a "good" packet and you can use the data form it.
For example, you may have something like:
uint8_t window[8];

void loop() {
    if (RS485Serial.available()) {
        uint8_t b = RS485Serial.read();
        // Slide the contents of the array down
        for (uint8_t i = 0; i < 7; i++) {
            window[i] = window[i+1];
        }
        // Insert at the top
        window[7] = b;

        // If the array starts with 0x01,0x03,0x40,0x34...
        if ((window[0] == 0x01) && (window[1] == 0x03) &&
            (window[2] == 0x40) && (window[3] == 0x34)) {
            // Do something with window[4] and window[5]
        }
    }
}

You could also add checking the CRC to that by comparing the calculated CRC for the incoming packet (however that is done in this protocol) with the last two bytes of the array.

Just one quick question, What is the need to slide the contents of the array down ?

To make room for the new incoming byte. Yes, you could wrap around instead, using a circular buffer, but that gets more complicated to both code and understand. Think of the data as socks on a washing line. You are only interested in the 8 socks that begin with the sequence red, blue, green, yellow. The "window" is the gap between your hands held out in front of you (fingers up, palms away from you, thumb tips touching). You move the "window" (slide it) along the socks until you see just 8 starting with the right sequence.

If I give the condition as (window[0] == 0x01) && (window[1] == 0x03) &&  (window[2] == 0x40) && (window[3] == 0x34) to (window[0] == 0x01) && (window[7] == 0x05) to confirm the window is covering the complete frame, then will I go wrong?

Yes, because window[6] and window[7] are the CRC and will change from packet to packet. You should, as I say in the last line of my answer, calculate the CRC and compare that to windows 6 and 7.


text:
One FTDI on Three Atmega
I'm doing a schematic for an arduino project-based and I can not proceed. I'm facing a problem which I have no idea how can I solve it so that's the reason I'm writing back to you.
The thing is: I have three atmega 328 and I want to program them using a single ftdi or a USB-UART converter. I can not put the chip outside the board and program them one by one, so the ftdi should be in the PCB.
I was wondering if I can do it using a switch with three positions with the help of 3 MOSFETs but I found it impossible, is it? Do you have any idea how can I solve this clue?
Many Thanks!

Sounds like you are talking to serial bootloaders, so you need to both block data input to the wrong ones, and only connect data output from the right one.  You could indeed do that with MOSFET pass gates, discrete or integrated.  Ultimate simplicity would be jumper blocks.  You could probably also come up with a clean software solution using a 16u2 instead of FTDI and soft serial to the targets - see the firmware source for the one on the Uno.

This is off topic as it is an EE design problem, not an arduino question.  It belongs on EESE where it was properly asked.


text:
SDA/SCL pins Arduino Uno
I am trying to figure if SDA and SCL pins from Arduino Uno is a TTL or a CMOS technology. I am not able to find this info anywhere but regarding it is a I2C protocol it does make sense to be a TTL technology. Can someone kindly confirm this info, please?

This is another X-Y question. In your comments below you start to reveal the real issue. How about amending the question to describe the real problem?

It is CMOS in that the IO pins of the MCU use MOSFETs not BJTs.
However I2C is slightly different in that it is open-drain not push-pull, so it's not really either TTL or CMOS since it doesn't conform to either logic level standard (since there is no "high" voltage, only what is pulled up by the external resistor). That said, since the ATMega is normally CMOS when in input or push-pull mode the logic levels of the I2C should conform to CMOS not TTL in order for the Arduino to read them properly.
It's closer to RTL than TTL or CMOS.

Many thanks for the help. I am struggling in establishing an I2c communication between arduino and pic32mx, and it seems I have a prob here.  As you said arduino is RTL and pic is a CMOS technology. Arduino is at 5V and PIC at 3.3V and I am facing many issues in order to release the bus line. Probably this is the reason why. Do you have a clue?

PIC is CMOS like the Arduino, just a different voltage. More strictly, it's LVCMOS - CMOS at 3.3V. CMOS itself is 5V normally. How are you dealing with the PIC32MX side of things?

I already started this conversation in this chatroom a few days ago http://chat.stackexchange.com/rooms/37934/discussion-between-tisteandii-and-scuba
let me know if there's any problem in entering the room.

connect both SDA and SCL via a pullup resistor (about 4.7k-10k) to 3.3V

This app-note describes one way to mix voltages on a I2C bus simply: http://www.nxp.com/documents/application_note/AN10441.pdf

Your question makes no sense. I²C uses open-drain/open-collector drivers which can even be discrete transistors or FETs although the inputs correspond to CMOS/TTL. These can be mixed - the Arduino uses MOS technology.
Of more significance is the supply voltage and the high/low trigger points (and of course the value of the mandatory pullup resistors which determine speed and/or range).
It is possible to use mixed 3.3V/5V levels. I use a Pi (3.3V) to communicate to Arduino (5V) which works (provided pullup is to 3.3V) although technically the Arduino input high levels are marginal.


text:
How to make universal remote controller?
I am trying to make simple TV remote using Arduino.
I got this link from Google for making a remote.
Code uploaded perfectly on my device. But all it does is blink a the LED on pin 13.
I hope I have got right code. I have tested it on my TV at home. Is that the correct way of testing it?
IR receiver I have is TSOP-15
P.S. I am completely new to Arduino
The below shown is my Arduino board(induino r3)

As you've stated in your question, the TSOP-15 is a receiver. That means it detects infrared signals rather than sending them out.
To make a remote control with that code, you need a simple infrared light emitting diode.
It's also important to note that you need to know what signals to send. Different TVs will have different IR codes, depending on the manufacturer. That information can be detected using your receiver module along with your TV's proper remote control.

By infrared light u mean IR led? Because there is IR LED- 14 on the board

@Freddy Yes, an IR LED is correct. You would need to modify the code to operate on pin 14 instead of 13 though.


text:
How can I create a power rail on my Arduino shield?
I have an Arduino that has 4 devices within an enclosure.  Each of the 4 devices needs 5 V and GND.  I have a shield with lots of unused pins (see photo).  I'd like to "bridge" one row of the pins to create a power rail, and I'd like to bridge another row to create a ground rail.
I think most people are using an external breadboard for this.  Also, I see that there is a shield that has power rails, but I don't have room for it.  I'm looking for a female header, or another way to bridge these unused pins.
Note: I'm not asking about wiring voltage in parallel or amperage consumption.

Just use some bare copper wire, and solder it to a row of pads.

Just bridge them.  Wire in your +5V connections then join them together on the back with lots of solder.  Maybe with a strand of 0.6mm single core wire along it for extra ruggedness.

Have you considered "Conductive Silver Paint"? With this you can literally paint tracks to join any arrangement of holes you so desire.
Everybody from Maplins to Rapid Electronics sell it. There are many brands to choose from. Here is one at random: http://www.rapidonline.com/mechanical-fastenings-fixings/kemo-conductive-silver-paint-180423 ...I like Rapid because they have a helpful Q&A section for each product.

+1 : This method turns the proto-board style into stripboard-style, i.e. you end up with conductive 'tracks' while leaving the holes intact. As you're constructing power rails, I recommend painting both sides of the board for extra current-carrying capacity.

Would this method work even if you're pushing 12-24V through the conductive paint?

@clifgray I have repaired the rear-windscreen-heater in a car with silver paint, so it definitely handles 14V ...I would suspect your bigger concern is how many Amps you wish to carry ...If you want to carry a lot of current, I would NOT paint a line "as thin as a fuse wire"

@BlueChip I'm running pretty low current. Around 24V and maybe .5A.


text:
Querying streaming sensor data on the Arduino board
I am new to Arduino and this forum, so please forgive me if I am asking something really trivial and stupid.
I have an Arduino board which collects sensor readings from an MPU6050 sensor (acceleration+gyroscope). The next step for me would be to process these data directly on the board. I want to somehow store N last sensor values and then query this set (collection, vector, array, whatever you call it) to fetch certain values. This set will be constantly updated with new values, whereas older values will be pushed out, so that only the most up-to-date values are stored in the set. For example, I want to know if the acceleration exceeded 10 m/s in the last minute.
In the literature this kind of set with most recent values is sometimes called window - this approach allows limiting an unbounded sequence of constantly generated tuples to a bounded bag and then apply traditional SQL-like query operators. For example, Oracle has come with CQL - an engine and a query language for handling streaming data.
Before I start implementing this, I am wondering if there is a similar (and, of course, much simpler) library for Arduino? If not, which data structure should I use to implement such functionality?
Also, my intention is to query not just individual values, but certain patterns and sequences - e.g., I want to know if the acceleration first decreased and then increased again (something similar to the WHERE condition of an SQL query). Does it look realistic to implement with Arduino?

A circular buffer sounds like what you want. The library mentioned by Majenko sounds like it implements that.

It sounds like you are after my Average library:

https://github.com/MajenkoLibraries/Average

It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).
You can then do various forms of analysis on the data - get the mean average, the mode average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.
It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).

Thanks for your reply!
A few more questions. Given that I am running your code on Arduino Yun, am I right that the maximum number of elements I can store in the rolling set is limited to 2.5k (which is the size of RAM of ATmega32u4, where variables are stored)?
Also, are you still working on your library? Any plans to further extend it with features I mentioned at the bottom of my previous post (e.g. querying sequences and patterns)?
Thanks!

The number of variables depends on the type of variable and how much space each entry takes up. I am always open to suggestions for enhancements to my libraries.

I presume you can always query the current contents of the window at any time. Thus a simple set of tests would let you conduct any custom queries you want.

Yep.  The .get(n) method lets you access any raw entry in the circular buffer you like.  There's also a Least Squares function, and one that uses that function to predict the value at some finite point in the future.  I use it to control the heaters in my reflow oven to prevent overshoot.

Thank you both for your comments and suggestions! I'll give it a try.


text:
How to return a message when calling by a TCP connection?
I am working on a communication between Android and Arduino board.
The Android makes a TCP connection with the board and successfully sends some strings to the board.
The problem is, there is an int in my Arduino code (e.g. int distance) and I would like to pass that back to my Android device.
I have handled the Android side already, but I do not know how to return a message from Arduino.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

This is the Android side code but I think that it is not a specific Android problem, there should be some way for Arduino to make a response of an integer variable (without concern what is the source device)?
What I should do in Arduino for making that response?

is serial.println(distance); correct? thanks

The binary representation of integers varies between Arduino (16 bit) and Android (32) bit, and while both an Arduino and most native-level Android implementations are little-endian, Android java code is big-endian.  So transferring your values in a string format may ease compatibility, as well as making it easy to debug the system by substituting a terminal emulator.

I'm assuming that you are using an Ethernet shield, as nothing about this is stated. But solution is really similar between many network solution.
Once a TCP connection has been established, it can be used like you would use the Serial;
you'll probably end up having something similar to:
EthernetClient client = server.available(); //accept a new connection
if (client) { //if valid connection
  client.print(distanceValue);
  client.close(); //close connection
}

look at the official API reference for a more detailed list of available command.


text:
Add a watermark to text message in an Arduino
I'm trying to add a watermark to the text in the Arduino and there are several levels of watermarks (fragile, semi-fragile, robust). What is the difference between these levels in terms of algorithms used?

I don't understand what you are trying to accomplish. Can you explain what your "text in the Arduino" is?

The term watermarking is usually used in the context of images. I can't make sense of the idea of watermarking text.

"Robustness", in the context of digital watermarking, specifies the ability to detect the watermark after some signal processing modification (for images, this might be translation, rotation, scaling, compression, etc.) Some digital watermarking techniques are robust against some operations but not against others. The classifications are:

Robust: The watermark should be able to survive against any and all
modification. This is often used in copyright protection, for
example.
Fragile: This kind of watermark is designed to be destroyed by any
modification to the original. This allows any manipulation, even
slight changes, to be detected. Fragile watermarks are generally used
to enable authentication and integrity verification.
Semi-fragile: The watermark should be "robust" against certain,
defined, modifications, but "fragile" against others. In other words,
the watermark should survive intact under the operations you want to
allow, but be destroyed by anything else. Again, these are used to
enable authentication.

For more information, you might find the 2005 paper A Review Study on Digital Watermarking by L. Jian and H. Xiangjian (in the journal Information and Communication Technologies) useful.

Watermarking is used to detect changes against the original source. In images this is done by changing some pixels, almost invisible to see, but enough to check the source or see if changes have been made.
For text this is not possible normally, since changing the text will visible change the output (when you print it).
Instead a so called CRC (cyclic Redundancy Code) is used and stored separately. E.g. a certain text has a specific CRC code. When the code is changed, the CRC code should be changed too. But if someone only changes the text, you can check the text against the (unchanged/encrypted) CRC code to see it has been mangled with.


text:
My Arduino Code but it will not compile, I cannot find what is wrong with it
I tried convining and LCD display, ultrasonic sensons, LEDs and an IR reciever code into one main code. Seperately they work fine, but when I put them toguether it gives me the following error: "Error compiling for board Arduino/Genuino Mega or Mega 2560."
The full error when I compile is :
Arduino: 1.8.5 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_13'
libraries/IRremote/IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld: Disabling relaxation: it will not work with multiple definitions
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

https://drive.google.com/file/d/1YNOqxE0mAZJsQrV7_zMbRZ_jkur19rXt/view?usp=sharing

have you tried adding two at a time, rather than all or one approach - perhaps then you can determine which two don't co-exist (if all 6 conbinations of two at a time always works, then try 3 at a time) - at least, that's how I'd approach the issue if the error messages did not indicate the nature of the problem

You must post your code and you must also use proper formatting or your question will get closed very quickly

I attached the Code to the post

Your code should be pasted into the question, a link to the code might expire. If it is too long to include then it should be reduced down to a Minimal, Complete, and Verifiable example.

The processor has a fixed number of hardware devices such as timers and serial ports. If two libraries try to use the same device (in this case it looks like timer 2) then you won't be able to compile (let alone run) the code without resolving the issue. Possibly one of them could be altered to use a different timer, however this may not be trivial.
As an example, say you have one alarm clock, but you want to have it ring at both 5 a.m. and 7 a.m. You can't do that per se, you might need to get a second clock.

Looking at the source code in (install directory)/hardware/tools/avr/avr/include/avriomxx0_1.h I see that vector 13 is indeed for Timer 2;
/* Timer/Counter2 Compare Match A */
#define TIMER2_COMPA_vect_num   13
#define TIMER2_COMPA_vect       _VECTOR(13)
#define SIG_OUTPUT_COMPARE2A        _VECTOR(13)

It is Timer2 interrupt with tone() and IRremote, same as here: https://forum.arduino.cc/index.php?topic=120955.0

Judging by the datasheet _vector_13 is "Pin Change Interrupt Request 2" so it might be something to do with pin change interrupts. I didn't look at the code as it wasn't posted above.

When I use the library manager and install IRremote by shirriff and add a tone() call and compile it for the mega 2560, then I get a __vector_13 error. I don't know how vector number 13 is related to Timer2, but it is.

Thanks Jot, i was able to figure out what to do.

@Jot you are right - I looked it up in the source.


text:
How to store values from a sensor inside an empty array?
I need to store the value of the distance in the dist array, then calculate the maximun value and print the index associated with this value:
The problem is when starting the nested for inside another for, the servomotor stops working
// Includes the Servo library
#include <Servo.h>

// Array y valores para funcion valor maximo

int max=0;

int angle=0;

int distance=0;

// Defines Tirg and Echo pins of the Ultrasonic Sensor

const int trigPin = 10;

const int echoPin = 11;

// Variables for the duration and the distance

long duration;

//int distance[180];

Servo myServo1; // Creates a servo object for controlling the servo motor

void setup() {

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  Serial.begin(9600);

  myServo1.attach(12); // Defines on which pin is the servo motor attached
  }

void loop() {

distance = calculateDistance();
  if (distance <= 15 && distance >=2)
  {

  // rotates the servo motor from 1 to 179 degrees and calculate the distance at each angle

  for(int j=90;j>=0;j--){

  myServo1.write(j);

  delay(30);}

  for(int j=0;j<=180;j++){

  myServo1.write(j);

  int i=0;

  int  dist [i] = {calculateDistance()};

      for (i=0;i=180;i++){           <--------------------------------------

       if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);}

  }
      }

  // Repeats the previous lines from 179 to 90 degrees

for(int j=180;j>90;j--){

  myServo1.write(j);

  delay(30);

  }
}
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds

  distance= duration*0.034/2;

  return distance;

}

  int i=0;
  int  dist [i] = {
    calculateDistance()      };

I'm not sure what you are thinking here, but you obviously cannot store data into a zero-length array. You also cannot put a function call to populate an array of variable length.
You need to decide how many elements you need in the array, in advance, and allocate an array of that size.

Maybe more like this:
 int  dist [180];

  for (i=0;i<180;i++){
    dist [i] = calculateDistance ();
    if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);
    }

  }

Also, this is wrong in your code:
for (i=0;i=180;i++){

You need to test for < 180 here. Your for loop will assign 180 to i and then check to see if it is non-zero, which will always be true.

I modified this part of the code and the problem is the same. Actually I do not know if I'm saving the data in the array with this instruction :/

It doesn't do the first for loop instruction, the servo only runs from 0 to 90 degrees and stops working.

You need to put in some debugging "prints". It's hard to tell what is happening. What value gets stored in distance, for example?

In distance variable gets stored the value of distance which was measured of the Ultrasonic Sensor.

Obviously. I meant what number are you seeing? Zero? 20? 100?


text:
CH340G Uploading problem
I've tried to copy CH340G from other schematics and existing Arduino Uno Clones...
Searched online & StackExchange but no good :/ My problem is almost the same as this one
Here is my schematic

I can read & send data from the serial monitor

OS: Win 10 64 Bit
USB Driver: 3.5.2019.1

Upload Options:

Arduino IDE version: 1.8.12
Board: Arduino Uno (also tired nano & nano old bootloader options)

What I've tried:

With & without the driver
Rebooted the computer
Tried different ports
Different cables
In case of IC not working, I've desoldered IC from working UNO
Changed RX, TX vice versa
Without R1 & R2
Different capacitors on C6 and C3
Buuut results are always the same as below

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xf3

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I appreciate any help, idea, suggestion
Regards

Have you installed the bootloader?

Yes @Majenko, I've burned bootloader and uploaded code via ISP. I can communicate with it already, but can not upload code via USB

What else is on the RESET line?

If you can use the CH340 as a Serial-USB bridge (Serial.print and Serial.read work) but you cannot upload a sketch without using a programmer, the bootloader (or fuses) are bad for some reason.

@KIIV, 10k resistor like Uno and Nano (5V and reset signals)

@DataFiddler, How we're uploading program to Uno in your scenario? We're only hitting the upload button, not upload with the programmer. Can you explain this, please?

There is what you have to check: 1) toggling DTR should reset the MCU 2) check if the clock is running properly (upload blink sketch and check the frequency) - then reupload the bootloader

Btw, on newer arduino boards there is also fast diode between RESET and Vcc power rail to suppress voltage spike to 10V - as it might be enough to enter High voltage serial programming mode.

The schematic is totally working. My mistake was after burning bootloader, I was uploading code via ISP. If you upload code via ISP, you're removing bootloader.
Thank you everyone who helped me to I wasn't mistaken at schematic and else...


text:
sending ctrl-z in a struct?
I have a set of buttons wired to an arduino leonardo that are meant to send either single keystrokes to a computer "a, b, c..." etc, or a key sequence like ctrl+z (to perform an undo command.) Effectively this is a little usb keyboard with pre defined buttons. The way the struct is now, I can only manage to send one keystroke, never a modifier key+letter like I need.
The full code is listed here under "working code": Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?
It just debounces the buttons and sends back actions (just single letters right now) using the ones defined in the struct. (thanks very much jwpat7)
The part in question is this
struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A'},
  {0, sw1, 'B'},
  {0, sw2, 'C'},
  {0, sw3, 'D'},
  {0, sw4, 'E'},
  {0, sw5, 'F'},
  {0, sw6, 'G'},
  {0, sw7, 'H'}};

I effectively want to replace the 'A' in {0, sw0, 'A'} to something that sends ctrl+z keystroke/keysequence instead of the letter 'A'.
I've tried KEY_LEFT_CTRL, setting a variable like char ctrlKey = KEY_LEFT_CTRL; and trying {0, sw0, ctrlKey, 'z'}, the "substitution" hex here: http://www.nthelp.com/ascii.htm and a number of other things.
I've read through a lot and I can't seem to find anything relevant. I've been told it's possible to use pointers to create a key-sequence but a -> operand in there just throws errors. I'm new and I realize I might have a core principal wrong, but isn't there some simple syntax to send a ctrl+z command (and then releasing it obviously) using that space? When I put {0, sw0, KEY_LEFT_CTRL, 'z'} it just reports "Lz", using the last letter in KEY_LEFT_CTRL instead of treating it as a modifier.  I'm so confused
(Also right now one press = one character and doesn't continually report like holding down a key on a regular keyboard.  I'd like to fix that too but I'd settle for just a bloody ctrl+z at this point.)
EDIT: Current Code (compiled!)
    enum { sw0=2, sw1=3, sw2=4, sw3=5, sw4=6, sw5=7, sw6=8, sw7=9}; // Switchbutton lines
enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, charMod, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'z',  KEY_LEFT_CTRL},
  {0, sw1, 'B'},
  {0, sw2, 'C'},
  {0, sw3, 'D'},
  {0, sw4, 'E'},
  {0, sw5, 'F'},
  {0, sw6, 'G'},
  {0, sw7, 'H'}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
Keyboard.begin();
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char tosend, char chmodi) {

if (chmodi) {    // See if modifier needed
   Keyboard.press(chmodi);
   Keyboard.press(tosend);
   delay(100);
   Keyboard.releaseAll();
} else {
   Keyboard.write(tosend);
}
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceEnd) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (b->bounceEnd < millis()) {
    b->bounceEnd = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP, b->charMod);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

If you don't use swiActR take it out of the struct.  In current code, {sw0, 'R',  KEY_LEFT_CTRL} inits bounceEnd equal to sw0, swiNum to R, and swiActP to KEY_LEFT_CTRL.  Initializers have to be in the right order, ie have to match the order declared in struct.  Values can be left off at the end, to default to 0, but can't be left off the front

Ah, I see that, but even if I use {0, sw0, 'z',  KEY_LEFT_CTRL}, it appears I still get declaration errors in void doAction() like "'tosend' was not declared in this scope" and a few others

Both tosend and b aren't  declared in the scope of doAction.  Just change  char action, char chmodi to  char tosend, char chmodi  and delete the two lines with b-> at front.  In doButton add b->charMod to the first doAction call.  Delete else {         doAction(b->swiNum, 'R', b->swiActR); if you don't plan to do an action for button releases, else perhaps fix the code up with a modifier for the release action char.  Just make the function calls and function defs match up, only use vars that are in scope, etc

Woot! That compiled!  It was throwing each button like zP, AP, BP, etc but I just had to change the doAction to doAction(b->swiNum, 'P', b->swiActP, b->charMod); to order it correctly.  Awesome! I've updated the compiled code. It looks to be swiActR that is unused. Before cleaning that I just wanted to ask, is the current code handling key releases correctly on single characters without Keyboard.releaseAll(); after Keyboard.write(tosend); ? It's acting very well but I was under the impression swiActR was used for release before. Thanks so much! Checkmark+upvote on the way after you read this!

In some early code, swiActR held a character to be sent when a button on the arduino was released.   It wasn't related to sending a key-up to the PC.  IOW, Keyboard.write sends a key press and then a key release, so it was taking care of the PC side

Awesome, you walked me through this and I understand much better now, all my thanks!

First off, consider trying '\032' or '\x1A' for the ctrl-z.  (See, eg, How to send ctrl+z in C on stackoverflow.)
To send a ctrl-z, use something like:
Keyboard.press(ctrlKey);
Keyboard.press('z');
delay(100);
Keyboard.releaseAll();

For more examples of using modifier keys, see the KeyboardPress page at arduino.cc, and the example program KeyboardLogout.ino.  [To coordinate this with the struct data structure approach, you could use code somewhat like
tosend = b->actionChar1;
if (tosend < ' ') {    // See if modifier needed
   Keyboard.press(ctrlKey);
   Keyboard.press(tosend+96); // or is it 64?
   delay(100);
   Keyboard.releaseAll();
} else {
   Keyboard.write(tosend);
}

[You'll need to test which offset, 96 or 64, works in the above code; I don't have a Leonardo or similar to run this on, and haven't looked at the Keyboard library source to see how it treats this.]  Another way is to add a modifier-byte field in the struct, and issue it if its non-zero.]
Second, suppose the current form of ButtonStruct is analogous to
struct ButtonStruct {
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
  // Switch number, press-action and prev reading
  byte swiNum, actionChar1, swiPrev;
};

where actionChar1 is the action character in use now.  You could add another byte to the struct, say actionChar2, and after a statement like Keyboard.write(b->actionChar1); add the following:
if (b->actionChar2)
  Keyboard.write(b->actionChar2);

which says to write out actionChar2 if it is non-zero.
In some of the questions linked to the previous question, you may see advice that Keyboard.write won't send non-printing characters.  I don't know if that's so, but in any case, there are mods available for Keyboard (ie, changes to the library) that allow non-printing characters and special characters to be sent.
Also note, if your program gets close to using all the RAM memory, you may want to keep buttons[] in ProgMem and access it from there so it doesn't need to be copied into RAM.  (See the three ProgMem questions that are linked in the top right sidebar . . .)   If you change the struct to use strings instead of single chars for its actions, using less RAM will increase in importance.
Edit re:  “what I don't know how to change ---> {0, sw0, 'A'}”:
{0, sw0, 'A'} initializes an element of buttons[].
In buttons[], each element is a ButtonStruct, because buttons[] is an array of ButtonStructs.  (For more about structs, see syntax and examples in eg Struct (C programming language) in wikipedia.)
You control what information can be in each element of buttons[] by modifying the definition of ButtonStruct.  If you need more data items in each buttons[] entry, then add more data items in the definition of ButtonStruct.  Likewise for fewer.
After you decide what information you need to have available to process a button press, modify ButtonStruct to contain exactly that information.  It may be that some information will apply in some cases but not in all.  If so, when you initialize buttons[], have some value (say 0) that stands for not-used, and fill in not-used spots with that value.
For example, if you need key modifiers (shift, ctrl, alt) add a modifier item to ButtonStruct.
Whenever you change ButtonStruct, you need to change buttons[] initialization to match.  For example, if ButtonStruct were to include Keyboard Modifiers and looked like
struct ButtonStruct {
  // Switch number, press-actions and prev reading
  byte swiNum, actionChar, charMod, swiPrev;
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
};

[with some items in a different order than before!] your initializer elements in the buttons[] declaration could look like
  { sw29, 'Q' },

where charMod, swiPrev, and bounceEnd are left to default to zero, or like
  { sw37, 'R',  KEY_LEFT_CTRL},

where swiPrev and bounceEnd default to zero.
Then, in your button-action code you could say:
tosend = b->actionChar;
chmodi = b->charMod;
if (chmodi) {    // See if modifier needed
   Keyboard.press(chmodi);
   Keyboard.press(tosend);
   delay(100);
   Keyboard.releaseAll();
} else {
   Keyboard.write(tosend);
}

For those elements of buttons[] where you specified a modifier, the if's first branch executes, and for those where you didn't, ie, for plain unmodified characters, the second one does.
There are all sorts of variants on these methods.  For example, instead of specifying action characters and modifiers in the buttons[] array, you could change it so that you specify function names, or could have several classes of actions.  If 80% of the actions were to issue one simple character, make that class 0, so the action class can usually default to 0.

I'm afraid this doesn't help. Using {0, sw0, '\032'} or the '\x1A' reports nothing when the button is pressed. I have also previously tried the method of adding another action but it still leaves me with no clear syntax when trying to report a modifier like KEY_LEFT_CTRL in the struct. It never registers a ctrl at all much less combines it with 'z'..

This post is mistaken as it overlooks the fundamental fact that keyboards don't send ASCII codes - rather they send scan codes.

@ChrisStratton, yes, physical keyboards send scan codes, but the Arduino Keyboard library API accepts (for most calls) ASCII codes, not scan codes.  It also accepts some modifier-key codes like I mentioned in an answer-edit a few minutes ago

I apologise, I haven't made something clear.  THIS is what I don't know how to change ---> {0, sw0, 'A'}   I haven't used a setup like that before.  All these methods and I still need to know what goes in here---> {0, sw0, 'A'} to get new output.  I need some kind of alternate example for that bit of code to understand why I'm seeing the strange output I'm seeing.  The only thing that ever works in there is 'A' or a single character. If I use this setup without knowing how to change it I'm going to try something like  {0, sw0, actionChar1} or worse and It's going to fail again and again.

@sylcat, see edit

(sorry for the late reply, thank you for being patient with me) If I understood correctly, I add a charMod to the struct (And also needing and action character, I left actionChar as swiActP from the earlier code before.) If I'm right doButton is just the deBounce so that is left alone waiting to get to doAction, then in doAction I implement the if(chmodi) statement. I've edited in |current code| above which gets scope errors. Did I incorrectly pass char chmodi or place the tosend+chmodi declarations in the wrong place?

@sylcat See comment to Q


text:
Problem with action that should happen in loop(continuously)
I’m using WeMos D1 R2 and latest Blynk library and app. I am also using Arduino IDE 1.6.13. I am trying to read a button from the app, which works fine, but i want to read it continuously. Through the Serial Monitor I can see that the board changes modes as it should. However, even if sensors read values when we get through the first “if” states, the values do not continue to show up in Serial Monitor. I believe that’s happening because it is not working as a loop. Also, the relays are not working(they start as open as they should, but their state never changes), as I believe program freezes at some point.
Here is the code:
//Start of program
#include <dht11.h>
#define BLYNK_PRINT Serial//
#include <ESP8266WiFi.h>
#include <Blynk.h>
#include <BlynkSimpleEsp8266.h>
#include <NewPing.h>
#include <SimpleTimer.h>

#define TRIGGER_PIN2 D4 // Arduino pin tied to trigger pin on the ultrasonic sensor 2.
#define ECHO_PIN2 D5     // Arduino pin tied to echo pin on the ultrasonic sensor 2.
#define MAX_DISTANCE2  23// Height of the Water Tank 2 (in centimeters).
#define DHT11_PIN D6

char auth[] = "****";
char ssid[] = "8888";
char pass[] = "psw";

int Relay1 = D1;
int Relay2 = D2;
int val2 = 0;
int tankwater1 = 0; //water in tank 1 in liters
int tankwater2 = 0; //water in tank 2 in liters
int fieldsize1 = 0; //size of field1 in m^2
int fieldsize2 = 0; //size of field2 in m^2
int sensor_pin = D7;
SimpleTimer timer;
//NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE1); // NewPing setup
of pins and maximum distance.
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2); // NewPing setup of
pins and maximum distance.

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
  //pinMode(led_pin, OUTPUT);
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
}

void loop()
{
  Blynk.run();
  timer.run();
}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8, 23 - val2); // virtualpin 8 distance
}

BLYNK_WRITE(V1) {
  int pinValue = param.asInt();

  if (pinValue == 0)
  {
    val2 = sonar2.convert_cm(sonar2.ping_median());
    Serial.println("Irrigation mode is active");
    Serial.println("Water level is at:");
    Serial.println(23 - val2);

    if (digitalRead(sensor_pin) == HIGH)
    {
      if (val2 <= 15) //Water level reaches the Top of the Tank2
      {
        digitalWrite(Relay2, HIGH); //Pump2 off
        delay(500);
      }
      else if (val2 > 15) // Water is empty on the Tank2
      {
        digitalWrite(Relay2, LOW); // Pump2 ON
        delay(500);
        //delay(86400000); one day delay. not suitable for experiment
      }
      else if (digitalRead(sensor_pin) == LOW)
      {
        digitalWrite(Relay1, LOW);
      }
    }
  }
  else {
    Serial.println("Fertilize mode is active. This does nothing now");
    //val3 = sonar2.convert_cm(sonar2.ping_median());
    //tankwater2 = (10-val3)*fieldsize2; //calculation of water in tank2
  }
}
//End of program

The BLYNK_WRITE(V1) function is only called when a Blynk app widget sends data to your hardware. It does not run in a loop. If you want something to run in a loop, put it in loop().
The WRITE aspect is from the point of view of the App, not of your hardware, so your hardware uses BLYNK_WRITE() to receive information from the app. And it's only called when the app chooses to send that information. For example, when a button in the Blynk smartphone app is pushed.

So if i want all of these actions to happen in a loop, i have to put them into loop and just receive the state of button of the app by using BLYNK_WRITE()?

You probably want to have a global variable in your sketch that holds the virtual pin state. You use the BLYNK_WRITE() function to update that global variable, as that function is only called when the app sends new information to the hardware.


text:
Not showing output when using pins other than 10 and 11 with SoftwareSerial library on Arduino Mega
I am  trying to run below code on Arduino Mega using GPS module(skg13 bl). It is working fine with pins 10, 11 as rx, tx in the SoftwareSerial but it is not showing output when other pins such as 4, 5 are used.
I further have to send this data through RF module using virtual wire library.
Code is as follows:

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
TinyGPSPlus gps;

SoftwareSerial mySerial(10, 11);

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  Serial.println("GPS start");
}

void loop() {
  while (mySerial.available()) {
    gps.encode(mySerial.read());
  }

  if (gps.location.isUpdated()) {
    double a = gps.location.lat();
    Serial.println(a);
    Serial.println(gps.location.lat(), 6);
    double b = gps.location.lng();
    Serial.println(gps.location.lng(), 6);
  }
}

Thanks in advance!!

Thanks for your help that problem is solved but another problem is arise working with virtual wire library it is not showing gps data code is as :

From https://www.arduino.cc/en/Reference/softwareSerial:

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

So you will need to use one of the pins from that list for RX, pin 4 or 5 will not work.


text:
Can an Arduino Micro receive commands from another microcontroller when hardwired together?
I plan to build functioning reaction wheels, controlled by an Arduino Micro. Ideally, I'd like to have the reaction wheels, and the micro, be a single unit which would receive external commands from another microcontroller.
I know you can link Arduino microcontrollers, and every time I've seen it done it has been with a RC module such as XBee. Is it possible to link units using something like the micro-usb on the Arduino Micro?
If this is possible, is it as simple as connecting the micro-usb ports on my microcontrollers, and then working out the programming?

Eh, I didn't know there was an Arduino.SE... I probably should've looked harder.

You cannot do this with the micro USB ports.  You will need to use I/O pins.  Either serial or I2C would be good options.  It might be advisable to use I2C if you want to control multiple 'slave' microcontrollers as they can all sit on the same bus.  Using the serial port would require multiple transmit and receive pins on the master controller, likely requiring software serial ports (high overhead).  Also, if you don't use the serial port for comms, then you can use it for debugging.

It might be worth explaining WHY you can't "just connect the micro-usb ports". There are two issues here:

USB is not symmetric, and an Arduino micro is only designed to act as a client. One of your microcontrollers would need to have USB OTG support to act as a host.
Even though there are microcontrollers that do have USB OTG support, you'd still have a nontrivial hurdle writing the software for them (Pretty sure the Arduino USB code is client specific as well, though I'm not familiar with the details of the serial over USB protocol).

In short, your basic idea is not physically or technically impossible, but would be fairly difficult to execute, while there are much simpler solutions available.

Usually the RF links (xbee included) just replace a set of wires connecting two serial ports. You can very easily connect the serial ports on two arduino's and communicate between them without any special hardware in between. You will only need 4 wires (power, ground, transmit, receive).

For me, it would be easier (I know now that the other way is easy too) to just connect the micro-usb ports. Would that work just as well?

No, you cannot just connect the usb ports

You can use a USB connector (micro) (mounted on a custom PCB) for whatever you want and route the connector's pins to whichever Arduino pins you want. It will not be USB, but you could, at least, use USB cables for ease-of-connection.
This is un-wise, at best, because someone is, eventually, going to plug in a real USB cable.


text:
Random(min,max) Function only giving ~50 range no matter what the values?
I can't get the min,max range to function properly. Monitoring the serial, only gives out ~50 difference from the min. I then added truerandom.ino to try to fix, but no help.
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
//long interval = random(800, 8000); // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
long interval = random(800,8000);
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
Serial.println(interval);
}
}

Added truerandom.ino still ~50 range:
// TrueRandomSeed.ino
//   This example sketch shows how to provide a truly random seed value to the built in
//   library pseudo random number generator.  This ensures that your sketch will be
//   using a different sequence of random numbers every time it runs.  Unlike the
//   usually suggested randomSeed(analogRead(0)) this method will provide a much more
//   uniform and varied seed value.  For more information about the basic technique used
//   here to produce a random number or if you need more than one such number you can
//   find a library, Entropy from the following web site along with documentation of how
//   the library has been tested to provide TRUE random numbers on a variety of AVR
//   chips and arduino environments.
//
//   https://sites.google.com/site/astudyofentropy/project-definition/
//           timer-jitter-entropy-sources/entropy-library
//
//   Copyright 2014 by Walter Anderson, wandrson01 at gmail dot com
//

#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <util/atomic.h>
// The following addresses a problem in version 1.0.5 and earlier of the Arduino IDE
// that prevents randomSeed from working properly.
//        https://github.com/arduino/Arduino/issues/575
#define randomSeed(s) srandom(s)

volatile uint32_t seed;  // These two variables can be reused in your program after the
volatile int8_t nrot;    // function CreateTrulyRandomSeed()executes in the setup()
                         // function.
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated

void CreateTrulyRandomSeed()
{
  seed = 0;
  nrot = 32; // Must be at least 4, but more increased the uniformity of the produced
             // seeds entropy.

  // The following five lines of code turn on the watch dog timer interrupt to create
  // the seed value
  cli();
  MCUSR = 0;
  _WD_CONTROL_REG |= (1<<_WD_CHANGE_BIT) | (1<<WDE);
  _WD_CONTROL_REG = (1<<WDIE);
  sei();

  while (nrot > 0);  // wait here until seed is created

  // The following five lines turn off the watch dog timer interrupt
  cli();
  MCUSR = 0;
  _WD_CONTROL_REG |= (1<<_WD_CHANGE_BIT) | (0<<WDE);
  _WD_CONTROL_REG = (0<< WDIE);
  sei();
}

ISR(WDT_vect)
{
  nrot--;
  seed = seed << 8;
  seed = seed ^ TCNT1L;
}

void setup()
{
  CreateTrulyRandomSeed();
  randomSeed(seed);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  // The preceeding two function calls will take approximately 0.5 second to execute if
  // nrot is set to 32 ... the rest of your setup code should FOLLOW from here.
}

void loop()
{
  long interval = random(800,8000);
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
Serial.println(interval);
}
}

can you give some example outputs of random sent through serial?

818
847
800
842
802
801
818
817
813
849
817
810
808
805
808
810
828
814
818
810
813
817
803
830
803
802
824
829
836
844
804
806
813
849
831
848
806
803
802
833
842

I suspect it actually is generating other values and it's your program logic that's at fault.
Here's what I think you meant your program to do:

Generate a random interval.
Wait until that interval has elapsed.
Start again with a new interval.

Here's what's actually happening:

Generate a random interval.
Check if that interval has elapsed.
Whether or not it has elapsed, generate a new random interval anyway.

Note that you're generating a new random interval every time round loop(). This means your condition just keeps trying new random intervals until one happens (by chance) to be less than the amount of time that's elapsed since the last interval. You're only outputting the interval when that occurs, and evidently it happens on average at least every 50ms.
You can test this theory by outputting interval to serial as soon as you've generated it (i.e. before the if statement). I think you'll find it will flood the serial monitor with a huge range of values.
Fixing the problem should be pretty easy. Just generate your first interval value during setup(). After that, only generate a new random interval value when the old interval has elapsed (i.e. inside the if block). Don't do it every time round the main loop.

I had the same problem (random, milliseconds), and in my case what I needed to make was a toy, able to Blink its eye (LED) in a more human way, with variable intervals, so I used the basic "blink without delay" and tweaked until I got a result I wanted.
This is my first post here so I hope I'm doing it correctly. Here is the code that worked for me:
const int ledPin =  13;      // the number of the LED pin
unsigned long previousMillis = 0;        // will store last time LED was     updated

 long interval = 4000;           // starting interval at which to blink   (milliseconds)

void setup() {
Serial.begin(9600);
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}

void loop()
{
digitalWrite(ledPin, HIGH);

unsigned long currentMillis = millis();

if(currentMillis - previousMillis >= interval)

{
  // save the last time you blinked the LED
  previousMillis  = currentMillis;
  interval = random((3, 14) * 1000);

Serial.println("Blink");
Serial.println(interval);  // Just so I can confirm if the effect seems natural
digitalWrite(ledPin, LOW);
delay(250);
digitalWrite(ledPin, HIGH);
 }
}


text:
Help with Flappy Bird Sketch
I am compiling the sketch found here. I just downloaded the .ino and .h files and opened them, so I have not modded the code at all. I keep getting the following error.
In file included from flappyDuino.ino:7:0:
Sprite.h:3: error: variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_1[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x78, 0x8A, 0x84, 0x8A, 0x82, 0x42, 0x82, 0x3E, 0x44, 0x41,0x38, 0xBE, 0x20, 0x41, 0x18, 0x3E, 0x07, 0xC0 };

                                                 ^
In file included from flappyDuino.ino:7:0:
Sprite.h:4: error: variable 'flappybird_frame_2' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_2[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x20, 0x8A, 0x40, 0x8A, 0x40, 0x42, 0x7C, 0x3E, 0x82, 0x41, 0x84, 0xBE, 0x88, 0x41, 0x78, 0x3E, 0x07, 0xC0 };

                                                 ^
Sprite.h:5: error: variable 'bar_bottom' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_bottom[] = { 0xFF, 0xFF, 0xFF, 0x42, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E };

                                         ^
Sprite.h:6: error: variable 'bar_top' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_top[] = { 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x42, 0xFF, 0xFF, 0xFF };

                                      ^
variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

I'd appreciate any help.

What it says... make those variables const.

This is embarrassing. . . But how?

By adding the word const after the word static.

Thank you. I had const on the back of my head but wasn't sure where to put it.

The arrays need to be tagged with the keyword const.  It is possible that the original sketch was written using an earlier version of the IDE that you are using (or a later version?) and your version requires the const keyword whereas the author's doesn't.
Basically any arrays that are PROGMEM need the word const adding to them.  For instance, lines that start:
static unsigned char PROGMEM ...

need changing to:
static const unsigned char PROGMEM ...

Thank you for answering why the sketch would not contain the necessary const. BTW Does the ! symbol mean not throughout the Arduino IDE, so that the statement "if (!player.isDead()) means if isDead is not true then. . .

Yes, ! is logical negation - true becomes false, false becomes true.  So !player.isDead() would logically be the same as (if the function existed) player.isAlive().


text:
Read signal from USB mouse on an Arduino ?
I've got a project where I'd need to read my mouse's signal. My mouse is a G700S (so USB) and the thing was I don't really know how to do and even if it's feasible.
I'm using an Arduino Micro and my initial idea was to get a PS/2 to USB Adapter (I already have one) and then to plug it to something like this wired to my Arduino.
So my question basically is "will it work ? and if not, why ?"
The main idea is not to use USB (like an USB Host Shield) because Arduino doesn't have any USB mouse driver.
Thank you in advance

You won't be able to operate a USB peripheral without something that can act as a USB host controller.  USB host "shields" are not cost effective, but there are options out there which both have USB host ports and are far better embedded computers than an Arduino, at lower price.  Both the KL25Z and KL46Z freedom boards can do this, as can the STM32F4 Nucleos, and likely some others.  In the KL25Z case the chip itself actually costs a few cents less than an ATmega238p, and has twice the flash and four times the RAM. But you will be using a traditional toolchain or mbed.org rather than Arduino.

Is there any way to discuss with you about this ?

This would be possible only if the mouse actually supports PS/2. USB to PS/2 adapters are entirely passive, and in order to function it requires that the controller in the mouse is designed to communicate in both protocols. Modern mice, especially wireless ones don't tend to have this capability anymore as PS/2 is all but a dead standard.

Mmh ok so I should try if my mouse works with the adapter prior to buying the stuff for the Arduino, right ?

@ThomasKowalski Yes. I would see if you can find a datasheet for your mouse (or at least a spec sheet) which should tell you its capabilities.

Well I tried to find a datasheet or something but I didn't find anything on Google. And I didn't find anything about backwards compatibility for PS/2. Anyway it's there if it can help.

I would say it's "unlikely" at best.  Better to buy a cheap PS/2 mouse and have done with it.