text:
How to HTTP post a data to Node express API from a Arduino esp8226?
I am HTTP posting a data to this web API https://morning-cliffs-85779.herokuapp.com/api/users from an Arduino connected to esp8226. I am using the wifiesp library to HTTP_POST data.
The REST APIs are hosted in Heroku.
When I post it the Arduino gives the response

Connected to server
  [WiFiEsp] Data packet send error (2)
  [WiFiEsp] Failed to write to socket 3
  [WiFiEsp] Disconnecting  3

and the Heroku server gives the response

at=error code=H13 desc="Connection closed without response"

Below is the Arduino code:
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    String content = "id=5bc58842bdfea0153bb27214&volt=7";
    client.println("POST /api/users HTTP/1.1");
    client.println("Host: morning-cliffs-85779.herokuapp.com:80");// ("Host": host:port)
    client.println("Accept: */*");
    client.println("Content-Length: " + content.length());
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(content);
  }

This is the Node Express API:
app.post('/api/users', function (req, res) {

console.log('here');

if (req.body.id) {
    DevReading.findByIdAndUpdate(req.body.id, {
        volt: req.body.volt
    }, function (err, reading) {
        if (err) throw err;

        res.send('Update Success');
    });
}

else {

var newDevReading = DevReading ({
    deviceName: 'test',
    volt: req.body.volt
});

newDevReading.save(function (err) {
    if (err) throw err;
    res.send('Reading Post Success');
});
}

});

you must use SSL to connect with https

how can i do it?

see WebClientSSL example

The Host header shouldn't contain the port. Change Host: morning-cliffs-85779.herokuapp.com:80" to Host: morning-cliffs-85779.herokuapp.com"

Did it heres the code
`if (client.connectSSL(server, 443)) {
Serial.println("Connected to server");
// Make a HTTP request
String PostData = content + volt;
Serial.println(PostData);
client.println("POST /api/users HTTP/1.1");
client.println("Host: morning-cliffs-85779.herokuapp.com");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
}`

Hope it helps some one


text:
Get accelerometer values from BNO055 using adafruit's Unified Sensor Library
If I understand correctly using the Adafruit_Sensor one can extract information from the sensor specific information. These sensors are currently mentioned in the README. I am using the BNO055 for two things:

Orientation values (Heading, pitch, roll)
Linear Acceleration values

My code is similar to the Example mentioned Adafruit_BNO055's bunny
Code
I tried the following in my loop()
void loop() {
  // put your main code here, to run repeatedly:
  sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.x);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.y);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.z);
  Serial.println(F(""));

  Serial.print(F("Acceleration: "));
  Serial.print((float)event.acceleration.x);
  Serial.print(F(" "));
  Serial.print((float)event.acceleration.y);
  Serial.print(F(" "));
  Serial.print((float)event.acceleration.z);
  Serial.println(F(""));

  delay(BNO055_SAMPLERATE_DELAY_MS);
}

Created sensors_event_t event and used the orientation and acceleration parameters to obtain the orientation and acceleration values in x, y, z directions.
output
The orientation and accleration values are the same:
Orientation: 105.50 -20.56 -101.00
Acceleration: 105.50 -20.56 -101.00
Orientation: 97.81 -14.69 -119.56
Acceleration: 97.81 -14.69 -119.56
Orientation: 93.81 -10.94 -125.56
Acceleration: 93.81 -10.94 -125.56
Orientation: 94.44 -12.25 -122.56

I tried adding another event event1 in the loop() but I still get the same results
sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.x);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.y);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.z);
  Serial.println(F(""));

  sensors_event_t event1;
  bno.getEvent(&event1);
  Serial.print(F("Acceleration: "));
  Serial.print((float)event1.acceleration.x);
  Serial.print(F(" "));
  Serial.print((float)event1.acceleration.y);
  Serial.print(F(" "));
  Serial.print((float)event1.acceleration.z);
  Serial.println(F(""));

  delay(BNO055_SAMPLERATE_DELAY_MS);

Can't the BNO055 along with the Adafruit_Sensor library not provide the acceleration and orientation values as events or is the library used only to obtain orientation values from the BNO055?

does I2C scanner find it?

@Juraj yes I get addresses 0x28 and 0x68. Also I have an RTC connected to the I2C bus.

according to bno's datasheet 0x28 is the secondary address and hence it is detected.

Findings
If I use the same sensors_event_t in the code and use event.acceleration and event.orientation within the loop() and they provide me exactly the same values. I in fact get the same values for heading, pitch, roll and acceleration in x, y, z direction.
sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.heading);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.pitch);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.roll);
  Serial.println(F(""));
 Serial.print((float)event.acceleration.x); // same as roll
 Serial.println(F(""));
 Serial.print((float)event.acceleration.y); // same as pitch
 Serial.println(F(""));
 Serial.print((float)event.acceleration.z); // same as heading
 Serial.println(F(""));

Sensor
I have a Blue Dot BNO055 sensor and it has marking on it for X, Y, Z directions as follows:

I crossed checked with the logic of Euler Angles from Wikipedia
If i rotate along the x Axis, I do in fact get roll (0 to 360) and so on.
Inference
The Adafruit_Sensor library provides only orientation values when used with BNO055 and Linear acceleration values need to be called separately using the Adafruit_BNO055.
code for Linear Acceleration and orientation
  sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.heading);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.pitch);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.roll);
  Serial.println(F(""));
//  Serial.print((float)event.acceleration.x); // same as roll
//  Serial.println(F(""));
//  Serial.print((float)event.acceleration.y); // same as pitch
//  Serial.println(F(""));
//  Serial.print((float)event.acceleration.z); // same as heading
//  Serial.println(F(""));

  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  Serial.print(F("Li. Acc.: "));
  Serial.print((float)li_ac.x());
  Serial.print(F(" "));

  Serial.print((float)li_ac.y());
  Serial.print(F(" "));

  Serial.print((float)li_ac.z());
  Serial.print(F(" "));
  Serial.println();

  delay(BNO055_SAMPLERATE_DELAY_MS);

You must set the operation mode from adafruit_bno055_opmode_t enum. Use bno.setMode.
For modes see section 3.3 in the datasheet.
The sensors_event_t is an union struct so the same memory is accessed with different member names.

I am not sure which mode to use and I tried setting it to IMUPlus and also tried it with NDOF but I get the same values for event.acceleration and event.orientation

doesn't help much. I referred to the datasheet after you answered and set them in the code's setup() and it provides the same output

as I write the struct is an union. it contains array of 4 floats. this floats are accesible as [0], [1], [2], [3] or over one of sensors_vec_t type aliases named acceleration, magnetic, orientation and gyro. the first float has additional aliases like temperature, distance. The event can return only one reading

read the description of modes "In  the  IMU  mode  the  relative  orientation  of  the  BNO055  in  space  is  calculated  from  the
accel
erometer and gyroscope data. The calculation is fast (i.e. high output data rate)"

So I guess with this library I can only use event.orientation and obtain the roll, pitch and roll and I have to use the Adafruit_BNO055 to obtain the linear acc. value separately

you can read data of the separate sensors or the fusion modes. I don't see how to read data with this library for combined modes like the AMG  mode

source: Stack Exchange

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

sort: votes


text:
More than 4 PWM output at 25khz?
Is it possible using an arduino to control more than 4 PWM fan at 25khz ?
I have found this but 4 PWM limited with an UNO
https://arduino.stackovernet.com/fr/q/8407
An other arduino, like a 2560 could be used ?
Thanks
Best regards
Sébastien

I would like replace this : https://www.nzxt.com/products/grid-plus-v3 in my work station

See answers in https://arduino.stackexchange.com/questions/3182/what-is-the-frequency-of-pwm-output-on-arduino for a guide on how fast Arduino PWM can be.

You could also use timer0, but then delay and millis won't work anymore. Second option is to use a external chip. You could also use a MEGA like you suggested, or the newer ATMega328PB (I don't think the latter is already used in the UNOs)

why would you need individual control of the 4 fans? ... just use one PWM signal to control all four.

'328P supports 6 analogWrite() outputs on D3,5,6,9,10,11. Won't all 6 do 25 KHz?

Indeed you could use a Mega. See this answer: it explains how
you can use Timer 1 on an Uno to provide two PWM channels at
25 kHz. This is the only 16-bit timer on that board. The Mega, on
the other hand, has four 16-bit timers: Timers 1, 3, 4 and 5. These
timers are almost identical to the Uno's Timer 1, except that they
provide 3 PWM channels each. So you have potentially up to
12 PWM channels that you can run at 25 kHz.
Now, look at this pinout diagram. Every pin labeled OCnx,
where n is either 1, 3, 4 or 5, and x is a letter, is a 16-bit PWM
output. Just take the code from the answer I linked to and adapt it to
the Mega. You configure all those timers in the same way, and you set
the duty cycle for pin OC3B by writing to the register OCR3B (and so
on...).

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


text:
What is the smallest duration that can be measured using micros()?
What is the least value of time that I could measure(count) using micros()?

What's unclear about the official docs?

Which board? I know you added the arduino-micro tag but I suspect you didn't add that because you're using an Arduino Micro board.

What is the least value of time that I could measure(count) using micro() in Arduino board?

The answer is 64 clock cycles or 4 us @ 16 MHz. Please see the Arduino AVR core[1] for more details.
Cheers!
Ref. [1] https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L25

is there is any other way to count in nano seconds or 0.05 micro seconds?

@krishnamoorthijayakumar yes, by using a Timer and setting the prescaling to 1 (no prescaling). This will give a counter with 62.5 ns per tick @ 16 MHz.

Please accept and mark the question as answered!


text:
I2C communication is not working
I have been working on my project but I get an error and I need some advice or correction.
I use I2C method to communicate between master and slave. I've got two questions:

I send 7 inputs (from master) to the slave but only receives 6
Will my coding make an output like this video

Master Code
// Master Code
#include <Wire.h>
byte nChar =0;
char input[7];

void setup () {

  Serial.begin(9600);
  Wire.begin();
}

void loop()
{
  if (nChar < 7) {if (Serial.available()) { input[nChar++] = Serial.read();}}

    else {

      Wire.beginTransmission(1);

      //a
      Wire.write(input[0]);
      Serial.print("Drawer : ");
      Serial.println(input[0]);

      //x
      Wire.write(input[1]);
      Serial.print("Output : ");
      Serial.println(input[1]);

      //00
      Wire.write(input[2]);
      Wire.write(input[3]);
      Serial.print("Output : ");
      Serial.print(input[2]);
      Serial.println(input[3]);

      //y
      Wire.write(input[4]);
      Serial.print("Output : ");
      Serial.println(input[4]);

      //00
      Wire.write(input[5]);
      Wire.write(input[6]);
      Serial.print("Output : ");
      Serial.print(input[5]);
      Serial.println(input[6]);

      delay(15);

      while (Serial.available())
      {
        //Remove extra
        Serial.read();
      }
      Wire.endTransmission();
        nChar = 0;
    }
  }

Slave Code
#include <Wire.h>
byte ledPins[] = {12, 11, 10, 9, 8, 7, 6};
byte ledPins2[] = {12, 11, 10, 9, 8, 7, 6};
byte count;
byte nChar;
char c;
char input[8];
char data[30] = "";
int n;
#define nBits sizeof(ledPins)/sizeof(ledPins[0])
#define nBits sizeof(ledPins2)/sizeof(ledPins[0])

void setup()
{
  Wire.begin(1);
  Serial.begin(9600);
  for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins2[i], OUTPUT);
    }
  Serial.begin(9600);
}

void loop()
{
  if (nChar < 8) {                    //accumulate three characters
    if (Serial.available()) {
      c = Serial.read();
      input[nChar++] = c;
    }
  }
  else {
    input[8] = 1;                   //atoi() expects string terminator
    n = atoi(input);                //convert the input characters to integer
    dispBinary(n);
    delay(100);                     //wait for any additional characters
    while (Serial.available()) {    //ignore them
      c = Serial.read();
    }
    nChar = 1;
  }
}

void receiveEvent(int howMany)
{
  while (1 < Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

void dispBinary(int n) //Vertical
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins[i], n & 1);
      n /= 2;
    }
  }
}

void dispBinary2(int n) //Horizontal
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins2[i], n & 1);
      n /= 2;
    }
  }

}

void b()
{
  if (data[0] != 'a')
  {
    dispBinary(atoi("00"));
    delay(100);
    dispBinary2(atoi("00"));
    delay(100);
    goto fin;
  }
  if (data[1] = 'x')
  {
    char xdata[2] = {data[2], data[3]};//(data[2], data[3]);
    dispBinary2(atoi(xdata));
    delay(100);
  }
  if (data[4] = 'y')
  {
    char ydata[2] = {data[5], data[6]};//(data[5], data[6]);
    dispBinary(atoi(ydata));
    delay(100);
  }

fin:;
}

Where is the Wire.onRequest ?

Most coders would your while (1 < Wire.available()) { write as while ( Wire.available() > 1) { and read it "repeat while there is more the 1 byte available". but wait, why leave that one byte there? you want "repeat while there is no more byte available".
you need while (0 < Wire.available())

Which coding sir ?

change while (1 < Wire.available()) to while (0 < Wire.available())

Another question why it became on same line. Why not it become one line one output. I cant put image to share with you. How to do ?

replace Serial.print(c); with Serial.println(c); ln is line


text:
Difference between 3.3v & 5v
 Im quite new to arduino in general and i'm sorry for the beginner question.
could someone explain what the 3.3v and 5v on boards do? I know their voltages. but can you run one on the other? whenever i try to search about it i see people saying that most newer modules are running on 3.3v so they convert their 5v arduino to 3.3v. something about if you run one on the other it could break it.

the arduino I bought looks like it has both! is that even possible?
 I also purchased this LED matrix as I wanted to make a wifi enabled scrolling text display. the matrix says it requires 5v. since this arduino says vin is 5-12v the two should connect and work properly, right?

The first link is to Amazon and shows a dev board with ESP-12F and USB connector. the other link is a dot matrix with max7129.

the main question here is "will the 3.3 V clock and data signal be read by the 5 V max7129 chip?"

I was not sure if I understand the max7129 datasheet, so I didn't write an answer. CrossRoad gives you an answer. It will not work. You must use logic level conversion.

The difference for different voltage boards lies in the parts, that are soldered on it. Often microcontrollers support more than one supply voltage, but impose different performance limits on the system. Take for example the Arduino Uno: It uses the Atmega328p, which can run both on 3.3V and 5V. But on the UNO there is a 16MHz quartz, which generates the controllers clock signal. The Atmega328p cannot run 16MHz with only 3.3 volts. To run a board on a voltage, for which it wasn't directly build, mostly requires you to resolder it with the correct parts.

whenever i try to search about it i see people saying that most newer modules are running on 3.3v so they convert their 5v arduino to 3.3v

There are special chips, called voltage regulators/converters. They come with various working principles, but basically they are converting one voltage to another. The Arduino Uno has one connected to Vin, so that you can apply between 7V and 12V to Vin and the Arduino itself will only see the 5V it get's from the regulator. Some modules also have a voltage regulator, but not all. Be careful not to provide more than the specified voltage to any board or you may destroy it.

the arduino I bought looks like it has both! is that even possible?

First, as Juraj wrote, this is not an Arduino. It is an ESP8266, a totally different chip and board. But you can also program it through the Arduino IDE, without it being an Arduino. Second: When they write, that you can provide it with either 3.3V or 5V, they mean, that you can provide 5V through the USB jack and a voltage regulator will convert it to 3.3V for the ESP, which runs completely on 3.3V. You should not connect 5V to any other pin.

since this arduino says vin is 5-12v the two should connect and work properly, right?

As stated above the 12V is only, what you can at maximum provide at Vin. The ESP8266 runs on 3.3V, so you will have to provide 3.3V (or more over the Vin pin). The LED matrix runs at 5V, as you stated. So you need a 5V source and a level shifter for the 2 lines between the ESP8266 and the matrix. If you connect them directly, you would damage the ESP8266. So: No, you cannot use it directly. It is up to you, if you want to use a level shifter or buy another matrix display, which can be controlled by a 3.3V signal.

in the last section you assume Uno. OP wants to connect the matrix to esp8266. the matrix has a control chip which communicates over 2 pins clock and data. will the 3.3 V signal be good for  max7129?

Ah, I misread the question and didn't know, that he already has an ESP8266. I will edit my answer

the esp8266 will not be destroyed. it can tolerate 5 V communication over digital pin. and I doubt there is any  from the max chip to esp. but the 5 V chip will not understand the 3.3 V as HIGH

As seen in the OEM data sheet for the MAX7219
https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf
the MAX7219 needs a supply voltage of 4 to 5.5V.
with a minimum signal voltage for High of 3.5V when Vcc = 5V.
Folks often get counterfeit parts from e-bay or elsewhere, with unknown characteristics.
For best results, I would power the '7219 from 5V, and use a buffer chip powered from 5V, such as 74AC125,
http://www.onsemi.com/pub/Collateral/MC74AC125-D.PDF
which will take ~ 2.5V with Vcc = 5V
to boost the ~3V output from the ESP2855 to 5V levels.

who and why down-voted this answer? (it zeroed my upvote)


text:
ESP8266 too many argument to function
My project uses ESP8226 to allow:
    1) user to set an alarm.
    2) after 20 sec of the alarm ringing, it will notify to phone via blynk app using motion sensor.
    3) after 40 sec it will turn off sensor and will not send notification
       again.
There are two problems that I have:

Got error with coding (digitalRead(nilai_sensor, LOW);) "too many arguments to function 'int digitalRead(uint8_t)"
I need help with coding for turn off the sensor and
will not nofify again.

Below is my Arduino code:
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>
BlynkTimer timer;
WidgetRTC rtc;
WidgetLED led1(V10);
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "a7d4522186464dd297870f2ab8e53250";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "NabiL";
char pass[] = "limaringgitlimapuluhsen";
int flag = 0;
int buzzer = 12;
int motor = 13;
int sensor = 4;

int saat;
int on_delay;
int off_delay;
int ok_delay;

int get1 = 0;
int get2 = 0;
int nilai_sensor = 0;

void blinkLedWidget()
{
  if (led1.getValue()) {
    led1.off();
    Serial.println("LED on V1: off");
  } else {
    led1.on();
    Serial.println("LED on V1: on");
  }
}

void clockDisplay()
{
  // You can call hour(), minute(), ... at any time
  // Please see Time library examples for details

  String currentTime = String(hour()) + ":" + minute() + ":" + second();
  String currentDate = String(day()) + "/" + month() + "/" + year();
  Serial.print("Current time: ");
  Serial.print(currentTime);
  Serial.print("Current Time: ");
  Serial.print(currentDate);
  Serial.println();

  // Send time to the App
  Blynk.virtualWrite(V1, currentTime);
  // Send date to the App
  Blynk.virtualWrite(V2, currentDate);
}

BLYNK_CONNECTED() {
  // Synchronize time on connection
  rtc.begin();
}
BLYNK_WRITE(V5) // Timer
{
  Serial.println(param.asStr());

  if (param.asInt())
  {
    on_delay = saat + 20;  //20Saat
    off_delay = saat + 10;  //10Saat
    ok_delay = saat + 40;  //40Saat

    digitalWrite(buzzer, HIGH);
    digitalWrite(motor, HIGH);
  }
}
BLYNK_WRITE(V6) // Timer
{
  Serial.println(param.asStr());

  if (param.asInt())
  {
    on_delay = saat + 20;  //20Saat
    off_delay = saat + 10;  //10Saat
    ok_delay = saat + 40;  //40Saat

    digitalWrite(buzzer, HIGH);
    digitalWrite(motor, HIGH);
  }
}
BLYNK_WRITE(V0){
  Serial.println(param.asStr());

  if (param.asInt())
  {

    digitalWrite(buzzer, HIGH);
    digitalWrite(motor, HIGH);

  }
  else

  {
    digitalWrite(buzzer, LOW);
    digitalWrite(motor, LOW);

  }
}
BLYNK_WRITE(V12){
  Serial.println(param.asStr());

  if (param.asInt())
  {

    digitalWrite(buzzer, HIGH);
  }
  else

  {
    digitalWrite(buzzer, LOW);
  }
}
BLYNK_WRITE(V13){
  Serial.println(param.asStr());

  if (param.asInt())
  {

    digitalWrite(motor, HIGH);
  }
  else

  {

    digitalWrite(motor, LOW);
  }
}
void setup()
{
  // Debug console
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  setSyncInterval(10 * 60); // Sync interval in seconds (10 minutes)

  // Display digital clock every 1 seconds
  timer.setInterval(1000L, clockDisplay);
timer.setInterval(1000L, blinkLedWidget);
  // Setup notification button on pin D1

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(4, INPUT);

}
void loop()
{
  saat = millis() / 1000;

  if(saat == off_delay)
  {
    digitalWrite(buzzer, LOW);
    digitalWrite(motor, LOW);
  }

   if(saat == on_delay)
  {
    Serial.println("Time Up");
    get1 = 1;
  }

     if(get1 == 1)
    {
     Serial.println("Program Sensor");

   nilai_sensor = digitalRead(sensor);

    if(nilai_sensor == HIGH)
    {
      Serial.println("Still sleeping");
     Blynk.notify("Still sleeping");

    //delay(5000);
   }
  }

if(saat == ok_delay)
  {
    Serial.println("Shut Down Sensor");
    get2 = 1;
  }
 if(get2 == 1)
  {
    Serial.println("turn off Sensor");
    nilai_sensor = digitalRead(sensor);
   digitalRead(nilai_sensor, LOW);

  }

  Blynk.run();
  timer.run(); // Initiates BlynkTimer

}

how do you want to turn off a sensor over the pin you use to read it? simply don't read it

The function digitalRead() has only one argument: the digital pin that you want to know the state (high or low).
You must change the use of this function, to something like this:
int state = digitalRead(nilai_sensor)

if (state == low) {
    //do something here
}

Hope you can find helpfull :D


text:
Serial monitor returns "48" when I enter "0"
I am going through an Arduino Learning Book(978-1-59327-448-1) and I've run into the same issue twice now.
When I enter data into the serial monitor, the number that it reads and displays(when asked to print) is way different than what I'm entering.
In diagnosing the problem, I went to https://www.arduino.cc/en/Serial/Read
Copied the code into a new sketch, and tried to run it.
When I Enter 0, I get 48, and a second line saying 10. Enter 1, I get 49 and 10, etc. Here are the results when I enter 0, then 1, then 2, then 3
I received: 48
I received: 10
I received: 49
I received: 10
I received: 50
I received: 10
I received: 51
I received: 10
here is the code I'm using
int incomingByte = 0;   // for incoming serial data

void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);
    }
}

I have the serial monitor set to 9600.
All sketches have worked fine so far, including those that use Serial.print functions, but when I use Serial.read, things seem to get screwed up.
I'm sure I'm missing something stupid, but I've googled around and all the answers are much higher level than just trying to run the code in the Arduino.cc example
Thanks in advance for helping a first timer!
PS: I Tried to get all of the code into the grey box with various line spacing and indenting strategies, but it's not perfect. Does anyone have any tips on that?

You just missed this.

Please explain further. I was wondering if its wanting ASCII input instead of regular numbers, but the code in my book, and that site doesn't make any special provisions for or mention of different input styles.

you are seeing the ascii code of the char you fed it. you can use Serial.print((char)49); to coerce it back into 1

Comments under questions are for clarifying the question, not answering it. Please make an answer if you wish to answer, which has the benefit that you get reputation if it is voted up or accepted.

I Tried to get all of the code into the grey box with various line spacing and indenting strategies, but it's not perfect. - what grey box? In what way isn't it perfect? Do you mean the forum or the Arduino IDE?

ok now i see, its reading as "symbol" on that linked page or "char" elsewhere, and storing the associated ASCII Code. I can trick it into toring anything down to 33 with "!" as the answer, but for the sketch in the book i need it to store values from 0 to 255(Im playing a guessing game with the board). So whats my workaround for that? The book just expects their code to magically work, and the code looks similar to arduino.cc Lastly where does that extra "10" come from? as in "I received: 10" in the serial monitor(original arduino.cc example)

@nick, the grey box on this page. In my original question.... wait nevermind, now it all in the box, it wasnt before i asked the question. but for reference, the code after my line "here is the code im using" and thank you again to all

@Mechanical-ish  About the "the grey box on this page". That was me. I edited your question so the entire sketch fit in to a "Code Sample". You can highlight a sketch and format it using the "Ctrl+K" keyboard short cut, insert 4 blank spaces in front of each line of code, or highlight the sketch then click the "{}" link in the editor.

           Serial.println(incomingByte, DEC);

You told it to print the incoming byte in decimal, so that is what it did. 48 is the decimal equivalent of ASCII '0'.
Change that line to:
Serial.println((char) incomingByte);

That casts the thing you are printing to a character, and then the appropriate version of Serial.println prints it as a character, not a decimal number.

10 is the decimal equivalent of a new line (newline) so that is why you are also seeing 10 printed.

I need to convert the incoming stuff into integers so that it can see if im guessing right or not

Assuming you mean an integer other than 0 to 9 (like, 42 for example) then you need a bit more work. I have a page about that sort of thing:
http://www.gammon.com.au/serial
Example code:
/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

In this example, the function process_data is called when there is a complete number to be handled.

Ok i changed it as you suggested, and got "I received: 1
I received: " so thats working for printing the number i enter, still confused as to why its printing that extra line. Also, when i go back to the guessing game in the book, i need to convert the incoming stuff into integers so that it can see if im guessing right or not.

The extra line is the linefeed you are echoing back. You will have configured the terminal monitor to send a linefeed after pressing Send.

You can use Serial.parseInt() to read a number sent from Serial Monitor. parseInt waits for all numeric characters of the sent text, so it blocks the execution of your sketch for a very short time until all characters are received. At higher baud rate it will be faster. If your sketch doesn't need to loop as fast as possible, then you can use it. parseInt stops at first character that is not a digit (for example a newline character) and returns the received number as long.
void setup() {
  Serial.begin(115200);
}

void loop() {
  if (Serial.available() > 0) {
    long number = Serial.parseInt();
    Serial.println(number);
  }
}


text:
Sketch with multiple classes (.h and .cpp) - how to interconnect classes
I wanted to move most functionality of my sketch into different classes, to keep things better organized. One class worked just fine, but when I had to use multiple classes and pass information between then things stopped working.
I have two classes, my main Remote class, and my RemoteDisplay class. The main class takes care of fx, measuring battery voltage and I want to display this through the RemoteDisplay class. To do so I initiate the Display class with a pointer to the Remote class, so I can access the voltage function. This, however, doesn't work, even though I forward declare the Remote class in the Display class.
Remote.ino
#include "Remote.h"

Remote Remote;

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

void loop() {
  Remote.display.showBattery();
}

Remote.h
#include "RemoteDisplay.h"
class Remote
{

public:

  RemoteDisplay display;

  Remote( void );

  float voltage;

};

Remote.cpp
#include "Remote.h"

Remote::Remote(void)
{
  display.initiate(this);
}

RemoteDisplay.h
class Remote;

class RemoteDisplay
{

public:

  RemoteDisplay(void);

  void initiate( Remote * _pointer );

  void showBattery( void );

private:

  /* Reference to the remote class */
  Remote * pointer;
};

RemoteDisplay.cpp
#include "RemoteDisplay.h"

void RemoteDisplay::initiate( Remote * _pointer )
{
  pointer = _pointer;
}

void RemoteDisplay::showBattery( void )
{
  Serial.println( pointer->voltage );
}

I get the errors:
error: invalid use of incomplete type 'class Remote'
showBattery( pointer->voltage() );

note: forward declaration of 'class Remote'
class Remote;

Why is it so? Any help is much appreciated.

In RemoteDisplay.cc you are using Remote in the Initiate method.
Also, since you use the voltage property, you need to include "Remote.h" within (as first line normally) in RemoteDisplay.cpp.
Also it is advised to use within every header file the following pattern (example for RemoteDisplay.h):
#ifndef REMOTE_DISPLAY_H
#define REMOTE_DISPLAY_H
...
...
#endif // REMOTE_DISPLAY_H

This prevents problems that two include header files forever include each other.

I see, thanks! It was the #inlcude "Remote.h" in the display class that did the trick. And yeah good idea with the #ifndef etc.

Good luck with your project (and great you try to keep your software organized).


text:
Low-Power library question
i'm study the Low-Power library to better undertand how it works.
In this part of code i have some question.
Sometime he uses commands like:
power_timer1_disable();
power_timer0_disable();

but in other part of code, example "TIMER2_OFF":
if (TCCR2B & CS22) clockSource |= (1 << CS22);
if (TCCR2B & CS21) clockSource |= (1 << CS21);
if (TCCR2B & CS20) clockSource |= (1 << CS20);

// Remove the clock source to shutdown Timer2
TCCR2B &= ~(1 << CS22);
TCCR2B &= ~(1 << CS21);
TCCR2B &= ~(1 << CS20);

power_timer2_disable();

he uses the register code and, in the end, the function.
Someone can explain to me why?

It's doing basically this:
clockSource = TCCR2B & (_BV(CS22) | _BV(CS21) | _BV(CS20)); // store prescaler
TCCR2B &= ~(_BV(CS22) | _BV(CS21) | _BV(CS20));             // select "no source" - disable clock source
power_timer2_disable(); // disable whole timer2 in Power Reduction Register

Definition of power_timer2_disable macro is:
#define power_timer2_disable()  (PRR |= (uint8_t)(1 << PRTIM2))

In short, you have to turn off the clock source before the power gets cut off by PRR register (to avoid unexpected behaviour).

Power Reduction Register
The Power Reduction Register (PRR), provides a method to stop the
clock to individual peripherals to reduce power consumption. The
current state of the peripheral is frozen and the I/O registers can
not be read or written. Resources used by the peripheral when stopping
the clock will remain occupied, hence the peripheral should in most
cases be disabled before stopping the clock. Waking up a module, which
is done by clearing the bit in PRR, puts the module in the same state
as before shutdown. Module shutdown can be used in Idle mode and
Active mode to significantly reduce the overall power consumption. In
all other sleep modes, the clock is already stopped.

Thx KIIV!
Is it in the datasheet those advice before use the, for example, power_timer2_disable?

@MarkCalaway It's definitely mentioned for the ADC module. I didn't checked it for the Timers.


text:
Sorting voltage data from pin A0 to 3 variables (ranked)
I don't have any code for this yet but I would like some ideas on coding it.
I have a directional antenna that is rotating at a slow speed and a ham radio connected to the antenna.  I have an output port on the radio that will put a voltage out from 0 to 5 volts for signal strength.  I also have the rotational degree data that is captured.  The question I have is do I try to do a long if then else statement to capture the 3 highest voltages and directions as variables for later processing or is there a better way.   An example would go a long way as well.

you need to think about what you are asking .... radio signal strength varies almost continuously ... the three highest voltages could come from only one source

That is true, That would be ok until I got closer with my vehicle where there would be more separation with the micro transmitters.  If the 1st, 2nd and 3rd highest signals were the same bearing, that would actually be a bonus because I would know the transmitters were further away.  When I get closer they would separate.

do you know how to read the analog pin in Arduino sketch? I am sure you do. The rest of your question is about common coding in C++, so take a coding course, if you don't know how to code what you want

It needs a bit more work but I would suggest using arrays to store the signal and positions something like this..
From (G7WJD) EXPIRED!
#define signalPin A0
#define degreePin A1
int signalStrength;
// STORE DATA IN ARRAY
// 0 [strength, direction]
// 1 [strength, direction]
// 2 [strength, direction]
int signals[3][3];
int degree;
bool positionSavedFlag = false;
void setup() {

}

void loop() {
 signalStrength = analogRead(signalPin);
 degree = analogRead(degreePin);
 // comapare with previous data
 for (int x = 0; x < 3; x++) {
  // have we saved data for this position before?
  if (degree == signals[x][1]) {
    // yes
    positionSavedFlag = true;
    // is it stronger than previous signal at this position
    if (signalStrength > signals[x][0]) {
      // yes so save / update it
      signals[x][0] = signalStrength;
    }
  }
 }
 // now since position not already stored , store it

 }

Thank you Brian, this helps a beginner at coding very nicely.  Kudos to you!


text:
Transmitting serial data over Wi-Fi
I have a device that outputs a TX RX RS232 serial string. Is there a way I can take this locally to an Arduino and send over Wi-Fi to another Arduino?
I'm relatively new to all of this so any advice will be greatly appreciated!

Serial-to-WiFi Tutorial using ESP8266

you need a RS232 to TTL Serial converter to connect a RS232 device to Arduino

Yes, and there are many tutorials how to do it.
Most popular one uses ESP8266 module. What is even more interesting you can use ESP module as an Arduino (and yes, you can program it using Arduino IDE).


text:
Quaternion values from BNO055 not available
I am trying to obtain Quaternion values from a BNO055 connected to ESP32-PoE board by Olimex.
Code
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

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

  if (!bno.begin()) {
    Serial.println("No BNO055 Detected!");
    while(1);
  }
  delay(100);
  bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
  bno.setExtCrystalUse(true);
}

void loop() {
  // put your main code here, to run repeatedly:
  imu::Quaternion quat = bno.getQuat();
  imu::Vector<3> euler = quat.toEuler();

  Serial.print("W: ");
  Serial.print(quat.w());
  Serial.print(F(" "));

  Serial.print("x: ");
  Serial.print(quat.x());
  Serial.print(F(" "));

  Serial.print("y: ");
  Serial.print(quat.y());
  Serial.print(F(" "));

  Serial.print("z: ");
  Serial.print(quat.z());
  Serial.print(F(" "));

  Serial.print("X: ");
  Serial.print((float)euler.x());
  Serial.print(F(" "));
  Serial.print("Y: ");
  Serial.print((float)euler.y());
  Serial.print(F(" "));
  Serial.print("Z: ");
  Serial.print(float(euler.z()));
  Serial.print(F(" "));
  Serial.println("");
  delay(200);
}

output
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00

The sensor seems to be working since I tried a simple script and the values are avaiable.
Is there some specific setting missing during setup() in order to obtain Quaternions.
Purpose
For Absolute orientation, the Quaternion values need to be converted to Euler .

why setExtCrystalUse? has the module an external crystal?

I think it is for I2C clock. It is set to true in most applications.

Apparently in the setup() it is preferable to have a delay(1000) as opposed to delay(100).
Code
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <math.h>

#define DEG (180/M_PI)

Adafruit_BNO055 bno = Adafruit_BNO055(55);

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

  if (!bno.begin()) {
    Serial.println("No BNO055 Detected!");
    while(1);
  }
  delay(1000);
  bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
  bno.setExtCrystalUse(true);
}

void loop() {
  // put your main code here, to run repeatedly:
  imu::Quaternion quat = bno.getQuat();
  imu::Vector<3> euler = quat.toEuler();

//  Serial.print("W: ");
//  Serial.print(quat.w());
//  Serial.print(F(" "));
//
//  Serial.print("x: ");
//  Serial.print(quat.x());
//  Serial.print(F(" "));
//
//  Serial.print("y: ");
//  Serial.print(quat.y());
//  Serial.print(F(" "));
//
//  Serial.print("z: ");
//  Serial.print(quat.z());
//  Serial.print(F(" "));

  Serial.print("Yaw: ");
  Serial.print(euler[0] * DEG);
  Serial.print(F(" "));
  Serial.print("Pitch: ");
  Serial.print(euler[1] * DEG);
  Serial.print(F(" "));
  Serial.print("Roll: ");
  Serial.print(euler[2] * DEG);
  Serial.print(F(" "));
  Serial.println("");
  delay(200);
}


text:
using string to display text on serial monitor
After using int to display text in serial monitor, now i am trying to use string but there is something wrong.
The expected reslut is "Led1 is on" in serial monitor but what i get is "285".
This is the code involving strings.
String(ledPin1="Led1 is on");
Serial.println(ledPin1);

while this is the full code
int numledPin1Blinks=5;
int ledPin1Blinks=2;
int i;
int j;
int waiTtimeoff2=1000;
int waitTimeOn2=1000;
int ledPin2=10;
int ledPin1=13;
int waiTtimeOn1=1000;
int waiTtimeOff1=1000;
void setup()
{pinMode(10,OUTPUT);
pinMode(13,OUTPUT);
Serial.begin(9600);
String(ledPin1="Led1 is on");

}

void loop()
{Serial.println(ledPin1);
for (i=1;i<=3;i=i+1){
Serial.print("   You are on blink
no#:  ");
Serial.println(i);
digitalWrite(ledPin1,HIGH);
delay(waiTtimeOn1);
digitalWrite(ledPin1,LOW);
delay(waiTtimeOff1);}
Serial.println(" ");

Serial.println("Led 2 is on!");
for (j=1;j<=4;j=j+1){
Serial.print(" You are on blink no
#:");
Serial.println(j);
digitalWrite (ledPin2,HIGH);
delay(waitTimeOn2);
digitalWrite (ledPin2,LOW);
delay(waiTtimeoff2);}
Serial.println(" ");

}

What do you think that code is supposed to do?

Display ' led 1 is blinking ' in serial monitor.

Why would it do that? ledPin1 is just a number and can never be anything else. It's an int. All you are doing is assigning the address of a static string to it, turning that number also into a String, and then throwing that string away.

As an aside: don't try and learn how to use String in the first place. It will lead you down a dark and dismal path that will end in unstable code and tears before bedtime. Don't taint your knowledge with them.  Start straight off with C strings (NULL-terminated character arrays).

I am learning aurdino from a website ( toptechboy) . The instructor did the same thing as he introduced the concept of string but I'm unable to perform it

I just perused that site (lesson 5 is it?) There's nothing like that there. The closest is: String redMessage="The Red LED is Blinking"; which is nothing like you have.

Yes I think it's lesson 5. I am not copying his code as I want to learn to code that's why my code seems to be different but it has the same structure as on the website

Please stop answering and use comments instead.

Maybe you should start with his code and modify it instead of trying to run before you can walk.

Sorry for not using comments.

For this case(string) ,  I even copied his code but the problem still persists.

note: your code is very poorly formatted ... that makes it difficult to read and to spot errors .... proper code formatting should be one of the first things that you learn .... it will help you a lot in the future .... note: your code has errors that prevent it from compiling

Your syntax is incorrect. You are assigning the address of a static string literal to an integer, then using the results of that assignment (the address of the string literal, as it "falls through" to the left) to create a new String object. That String object is then being thrown away.
You need to create a new String variable (not re-use one that you actively use for another part of your program) and assign a string literal to it:
String led1Message = "LED 1 is on";

Then you can print that variable instead:
Serial.println(led1Message);

HOWEVER String objects are very very fragile on the Arduino and should be avoided. Forget trying to learn to use them, since you will only have to un-learn them at a later date.  Skip them and start straight away with C-strings (NULL-terminated char arrays).  Also learn about PROGMEM.
For instance, the above could be written as:
const char led1Message[] PROGMEM = "LED 1 is on";

And then use a casting to get println to grab it from flash:
Serial.println((__FlashStringHelper*)led1Message);

This uses pretty much zero RAM, which on an Arduino is very important. Even more important it doesn't cause heap fragmentation which can cause your program to crash randomly.

Thank you very much,  I had no idea about demerits of using strings. I'll just try using const char instead.

Can print/println really differentiate between in memory const char and flash one? The F macro was using reinterpret cast into FlashStringHelper pointer so function overloading can be used.

Actually, I'm not sure: I never actively use Arduino... ;)  You may want to cast it to (__FlashStringHelper*).


text:
Nano V3 values "overwritten" randomly
When I assign a global var to a certain value inside an if-block it has been changed to another value in the next statement. Somehow the address of the var is overwritten by some other process. It also does not stop at 1 value, this happens to the next vars that are assigned another value too. The vars are not defined in a row but should be close.
I already installed a newer version of Arduino IDE, no change.
Example:
menuActive=1;
Serial.print(menuActive);

gives results in the range 40 to 57 as far as I have seen till now. Further actions assign always the SAME value to next vars I assign after this.
Anyone some idea what could cause this? Am I low on memory for local vars?
This is compile message:
Sketch uses 21790 bytes (70%) of program storage space. Maximum is 30720 bytes.
Global variables use 1454 bytes (70%) of dynamic memory, leaving 594 bytes for local variables. Maximum is 2048 bytes.

edit:
As I already said, it is 21k of code. But I show you the part of the code that mishaves:
while ((digitalRead(rotSwPin) == 0) && lpress <= 200) {
    delay(10);
    lpress++;
    if (lpress > 200) {
        menuActive++;
        menuLvl=0;
        menuPos=0;
        subPos=0;
    }
}

Normally I use menuActive=1. Within the braces, it is still 1, out of that it changes. Maybe change from byte to bool.

Sounds like a buffer overflow to me.

Agreed! But where can I find the memory assignment in a file/list to grab an idea which variable does the overwriting?

You can't unless you generate a "map" file, for which you need to modify the compiler options in the IDE configuration files.  Examine your code for any arrays that you use and make sure you don't try and use more than you should. One common misuse is to declare int foo[10] and then try and use foo[10] as a slice.

Given the range of numbers it gives you, chances are it's a char array into which you are printing numbers, maybe with punctuation like brackets.

or show your code and someone spots the problem

Thanks for your suggestions, but I checked those things already carefully. I think of stepping to Eclipse for this Arduino project and find out more by debugging?

As I already said, it is 21k of code. But I show you the part of the code that mishaves:

while ((digitalRead(rotSwPin) == 0) && lpress <= 200) { delay(10);lpress++; if (lpress > 200) {menuActive++;menuLvl=0;menuPos=0;subPos=0;} }

Normally I use menuActive=1.
Within the braces, it is still 1, out of that it changes. Maybe change from byte to bool.

If your program corrupts memory (which seems to be the case here), the part of the code that misbehaves can be quite far from the part that does the memory corruption. There is nothing wrong with the code you are showing here. Your problem lies in some part of the code you are not showing. Nobody will be able to help you without seeing the bug.

I found the problem.
I could see that the false value is the character code of the minute I am displaying. I display hours and minutes and there was a declaration that was 3 characters short for the string I got as a result for hours added to minutes. Yes it was memory corruption.
So be careful to dimension enough places for your strings including 1 extra for 0.

@hoekbrwr You might want to post that as an answer, rather than a comment.

Comments are not recommended for any of the following: Answering a question or providing an alternate solution to an existing answer; instead, post an actual answer (or edit to expand an existing one);. Feel free to post an answer instead. Thanks.

I found the problem. I could see that the false value is the character code of the minute I am displaying. I display hours and minutes and there was a declaration that was 3 characters short for the string I got as a result for hours added to minutes. Yes, it was memory corruption. So be very careful to dimension enough places for your C-strings including 1 extra for 0. If you are not so short on RAM then a few more characters will do no harm, the end of the string will be the character before the 0 in memory.
When strange things happen start looking at this matter!


text:
How can I discover attached motor shields in code?
I'm using the Motor Shield v2 and I'm looking for a way to automatically discover the addresses of attached motor shields.

research how to discover i2c devices

If you configure each I2C device to have a unique address, then it's easy to determine which ones are connected.
This sketch is derived from the I2C Scanner sketch found here: I2cScanner
// This sketch tests the standard 7-bit addresses.
// Devices with higher bit address might not be seen properly.
#include <Wire.h>
byte shieldOneAddress = 0x27;
byte shieldTwoAddress = 0x32;
byte error, address;

void setup(){

  Wire.begin();
  Serial.begin(9600);
  Serial.println("Scanning for shields...");

  for(address = 1; address < 127; address++){

    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if(error == 0){
      if(address == shieldOneAddress){
        Serial.println("Shield One is connected.");
      }
      if(address == shieldTwoAddress){
        Serial.println("Shield Two is connected.");
      }
    }

  }
  Serial.println("Scan complete.\n");
}

void loop(){}

This code detects a device connected at address 112. This is the all call address. It doesn't detect the individual address of a motor shield (0x60 in my case).

So ^that is true when the motor shield library isn't imported, but when the motor shield library is imported it works fine. Maybe they do some setup, not sure.


text:
ESP8266 + HC-05 on same arduino
I'm absolutely new to arduino, so please excuse me if this is a noob question.
I want to use a ESP8266 esp-03 Wifi module with a HC-05 bluetooth module together with my arduino uno.
Unfortunately both use the TX and RX pins on the board.
Is there a way to use both, the wifi and the bluetooth modules?
Or do I have to purchase a wifi board?

You can (just about) use any combination of two of:

Serial to PC,
HC-05
ESP-03

You have, basically, a hardware UART (pins 0/1), and a software UART (any pins of your choice).
Only the hardware UART can be used for communication with the PC, and you can only reliably use one instance of SoftwareSerial.
So, you could:

Use Serial to the PC (0/1) and HC-05 (SoftwareSerial, your choice of pins), or
Use Serial to the PC (0/1) and ESP-03 (SoftwareSerial, your choice of pins), or
Hardware Serial for ESP-03 (0/1) and SoftwareSerial for HC-05 (your choice of pins), or
Hardware Serial for HC-05 (0/1) and SoftwareSerial for ESP-03 (your choice of pins)

If you want anything more complex than that then you need to use a board with more than one hardware Serial port (such as a Mega2560).

Thank you for your reply! So do I understand correctly, that when I use the serial port (e.g. to program the arduino) I cannot use the hardware UART pins at all? I also bought the Mega2560, are the 14TX3, 15RX3, 16TX2, 17RX2, ... pins the hardware serial ports you are talking about?

You can't have anything connected to the UART pins when actually doing the programming. Once programmed you can't use the UART pins and communicate with the PC. I.e., if you want to use the UART pins for a peripheral you will (most likely) have to disconnect it to get the programming to work, and you won't be able to debug your program through serial.  And yes, those are Serial2 and Serial3 etc that you point to there.


text:
What exactly does the Arduino preprocessor do?
Arduino claims to be a "language," not just an "application framework," and Arduino files have their own extension, .ino.  The language is obviously C++, but not quite.  My understanding is that Arduino has some sort of special preprocessor which converts .ino files into C++ files before compiling them.
My question is: What exactly does this preprocessor do?  What exactly are the differences between "Arduino language" and real C++?  The Arduino documentation seems to gloss over this.
In particular, I've had weird things happen when I try to define my own classes in my sketch.  It's hard to figure out what I'm doing wrong when the language doesn't seem to be specified anywhere.

The Arduino ino to cpp converter doesn't touch your cpp and h files. It only converts the ino file to a cpp file as Majenko described in his answer.

I've had weird things happen - can you give an example?

@NickGammon It was a while ago, so I don't remember the exact error message.  But I suspect it was caused by the automatically generated prototypes.  (i. e. a function takes a struct or class as an argument, and the prototype is inserted before the declaration of that struct or class)

It does four things, basically:

It adds #include <Arduino.h> to the top of your file, which gives you access to all the classes, functions and defined variables/macros of the API.
It joins together all the INO files together into a single monolithic file (in the same order as the tabs in the window),
It matches #include entries with libraries and adds the files in those libraries to the list of files to compile, and
It scans through the ino file(s) looking for functions and adds prototypes to them to the top of your file.

It's the latter that can cause problems. Historically it never got the prototypes in the right place, and if you ever passed a structure of your own devising to a function it would break horribly.  It does a better job these days, but it's still not 100% perfect.
It basically means that you don't have to adhere to the "You must define it before you use it" rule of C/C++.  Which of course makes for lazy programmers.

and it concatenates all ino files of the project to one file, starting with the ino file with same name as the project folder a then the rest of ino files in alphabet order (it is the same order as tabs in IDE)

Ah yes, that too.

See my answer: How the IDE organizes things
I'm not sure if link-only answers which refer to a Stack Exchange link are OK. In case they are not, here is the first part of that answer:
This is how the IDE organizes your "sketch":

The main .ino file is the one of the same name as the folder it is in. So, for foobar.ino in foobar folder - the main file is foobar.ino.
Any other .ino files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
This concatenated file becomes a .cpp file (eg. foobar.cpp) - it is placed in a temporary compilation folder.
The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
The main file is scanned for #include <libraryname> directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
Any .c, .cpp or .asm files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
Any .h files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
The compiler adds into the build process standard files (like main.cpp)
The build process then compiles all the above files into object files.
If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you strcpy etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

Thanks!  Where did you learn all of this information?

Observation of what files get copied into the temporary directory, and looking at the commands being executed when "verbose" compiling is turned on.

Where are the temp files located? Can you configure Arduino IDE to keep them to make it easy to look at them?

If you turn on "verbose compiling" you can see where the temporary files are.


text:
LDC paired with Arduino locks up and freezes. Out of SPRAM?
I am making an alarm clock using a 4x20 lcd display, rtc, and Arduino Pro Mini 3.3v. I have implemented a menu system for setting the time/date that blinks the text on the lcd display to indicate that I have it selected, but the blinking randomly stops and the Arduino stops printing to the serial after about ten seconds.
After much head scratching and Googling I came to the conclusion that all my lcd.print() lines were using up all my ram. I tried to create PROGMEM variables to use in the print commands, but I couldn't get it to work so I ended up just adding the F() macro to every print statement (there's a lot). This now prints everything as expected, but the Arduino still freezes up after the same amount of time. Am I using F() wrong or is the problem something else like power???
Visual Studio code says I am using 643/2048 bytes of data/ram and 14960/30720 bytes of flash when I upload the code. (that is with the F() macro implemented)
--------------EDIT----------------
So I've created a small test sketch to use with the same circut, and now I'm really confused. I've been running it for about an hour now and it is still not freezing. The script blinks a full screen of number signs every 200ms. The backlight is on and everything is still powered the same way. This, in theory, rules out both running out of ram and not providing enough power. Any other ideas?
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClibExtended.h>

LiquidCrystal_I2C lcd(0x27,20,4);
RTC_DS3231 clock;

void setup() {
    Serial.begin (9600);
    lcd.init();
    clock.begin();
    clock.adjust (DateTime (__DATE__, __TIME__));
    lcd.backlight();
}

bool on = true;

void loop() {
    lcd.setCursor (0, 0);

    if (on) {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print ("#");
            }
        }
    }
    else {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print (" ");
            }
        }
    }

    on = !on;
    delay (200);
}

add your code to the Question.

A lcd display requires 5v and your Arduino is a 3.3v pro mini board. How did you connect that? Are there long wires to the rtc and the display?

Along with what Jot said, and my own WAG, it sounds like you're trying to pull too much power, potentially overheating the power regulator.  Once you add some code, we can see if that's an alternate possibility.

I have the Arduino powered by the usb from my computer and the rtc and lcd are connected to the vcc pin on the Arduino. I am using the lcd without the backlight, so does it still need 5v? Also, I tried using a 9v battery to power the circuit (connected the Arduino to the battery through the raw pin and connected the lcd and rtc directly into the battery instead of the vcc pin from the Arduino), and the lcd still freezes. Would it be helpful if I posted the circuit diagram? My code is over 1000 lines long, so I'm not sure what the best way to share it with you would be.

create a small test sketch to test if the problem is power or overheating

@Juraj I posted one

Any other ideas? - there is a problem in your longer code which isn't in the smaller code. Hard to say what that is without seeing the longer code.

I found the problem! it was specific to my code and didn't turn out to have anything to do with ram or power. The problem was I hadn't detached the interrupt from the rtc when I woke it up with a button. It would freeze seemingly randomly because the rtc would fire an interrupt signal when the next minute ticked, while the arduino was awake. I guess it causes problems when you try to interrupt arduino's sleep and it's not actually sleeping. All I had to do was detach both interrupts when the button is clicked. Thank you all for your help :)


text:
How to get a feedback that something connected to an Arduino is working?
Assume you have an Arduino Uno board, the board is connected to some sensors, maybe a stepper motor or something, it does not matter.
How to get feedback or diagnostics or something that all the things are working, or if not then get feedback that are not working?

It all depends on what the devices are and how they work. As an example, you could add current shunts to the motor connections and sense the current flowing through the motor.

with sensors you can check if the values are in expected range

moving parts can be checked with optical or electromagnetic sensors

there is nothing special for Arduino. it is common design of a system

OP asked how to provide feedback that there is or isn't a problem, not how to diagnose one. That's pretty straightforward, and I'd be happy to offer an answer if this were re-opened. Voting to do so....

Thank you all for the comments , have a ncie day , i think i got it :D

There is no general mean of error detection in microcontrollers, so also not for an Arduino. Problems can occur at many points, extremely depending on how your project works. Think about a sensor, that is connected over some network bus; the sensor itself may fail, but also the network bus, so that you are not able to connect to the sensor anymore. Also the Arduino has no possibility to report errors to you, that you didn't anticipated in your sketch (like the log files on a PC would do). So there is not one answer for it. Here are some possibilities (some of them already described in previous answers):

Check the output of library functions for error messages. Many (but not all) libraries return status codes from their important functions. For example: The Wire.endTransmission() function will return a status code, with which you can determine, if the transmission succeded and what might have gone wrong.
Check sensors for expected values. If the values go out of range (for example a temperature of -20°C where you would expect room temperature) you can be pretty sure, that something is wrong with the sensor (assuming it worked properly before).
Add sensors to your project, to sense, if it is working as expected, and program the Arduino to do the corresponding actions on failure (for example an alarm)

The first two options are simple, the third can get very complex and expensive and is normally only used, if the project really demands sensing malfunction electronically (like for a robot, that could hurt humans, when moving in the wrong direction).

To expand on Juraj's answers, tackle this question from the user's point of view. What does all things are working mean for them? Does the temperature you read from a sensor have to be within .2C of a reference value? The stepper has to move a thing from defined positions A to B?
Based on the answers to questions like this, which is sort of a black-box testing approach, think about how to obtain reference values, then write tests in your Arduino to check if they are met. You might have to move your system into a defined testing stage first, like move the steppers to a defined starting point, then go test.


text:
Accessing raspberrypi.local from Nodemcu
Currently I am trying to access a rest API from NodeMCU. The API is hosted on my local LAN on a Raspberry pi 3 b. The Raspberry pi is accessible on LAN using the raspberrypi.local domain address.
But the problem is I am unable to access the raspberrypi.local address form NodeMCU.
It is unable to just resolve the address.
Can anyone please help me resolve this issue?

In order to access the API, your NodeMCU needs to know the IP address your Pi has at this time. There are several ways to resolve raspberrypi.local to the actual IP. Assuming the NodeMCU got its IP assigned by your WiFi hotspot, it also received a DNS server IP. This is where the NodeMCU would ask first. However, if this DNS server is hosted by your internet provider, it obviously would not know what to respond when asked for your raspberrypi.local.
Another way, especially for .local domains, is mDNS. NodeMCU has a module to do that.
If you work with this a lot, consider running a local development network with your own DHCP/DNS combo. dnsmasq is a good place to start. Lots of tutorials online. The Pi can host that for you.


text:
Connection from Arduino Uno to Microsoft SQL Server Database
I would like to make a connection from Arduino Uno to Microsoft SQL Server for storing student attendance records into a table from my database.
So, what is the best way to do that? I need a suggestion or useful references and links.
I have written a web application on Visual Studio using C# language. What Arduino does is getting fingerprint through sensor, then I would like to store the attendance records of a student into database. So the attendance records can be retrieved from database to the web application and display to teachers.
This is just for project purpose only and the connectivity between Visual & SQL Server using these two lines below:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS1;Integrated Security=True";

It is highly doubtful you will ever get the Arduino to connect to Microsoft SQL Server.  Create a Web API as a gateway between the Arduino and SQL using a protocol of your choosing (REST is common with plenty of examples around).

@Majenko Hi, Majenko. Do you have any useful references? Cause I'm new to Arduino. Don't know which is the best one to me to establish connection between Arduino Uno & Microsoft SQL

No, I've never done it. You seem to already be au fait with C# and VS, so I'd guess you'd add it to your web app. Just create some URLs (however you'd do that) that accept data in some way and post them to the SQL server. Of course you'd need a network connection (WiFi, Ethernet, whatever).

Using a layer between Arduino and MSSQL might give you the least headache. Would you like to do this on-premise or in the cloud?
For an easy cloud approach, look at AWS Lambda. Write a Lambda function that inserts into your MSSQL database, possibly running on AWS too. Your choice of Java, Node.js, C#, or Python. Hook it up with incoming MQTT messages from your Arduino.
https://stackoverflow.com/questions/33165045/aws-lambda-and-sql-server-integration
 could help.
For a cloud-free approach, you could run your own local MQTT server (broker, to be exact, Mosquitto being the most popular), and have your C# subscribe as an MQTT client. When the Arduino publishes a fingerprint signature, your C# script can do the database work.

Hi Chris. I've been searching for tutorials about Mosquitto. But I didn't find any useful articles how to send data from Arduino to MSSQL using Mosquitto. Do you have any useful links or tutorials for me to do it?

Mosquitto is just a broker. Think of it more like a phone switch board. You write a piece of C# code that subscribes to a topic (think phone number). When your Arduino publishes information on that topic (dials that number), Mosquitto routes that to your C# client, invoking your code (phone rings). There is a nice intro to MQTT at HiveMQ.

Chris, how can I connect the arduino with mqtt broker or subscribe to the mqtt broker?  Without using ethernet shield or wifi shield


text:
Beginner problem with DC motor
I am new to electronics and I'm having a problem when creating my project. I have created a Bluetooth controlled rover using HC-06, Dual H-bridge motor driver and 4 DC motors.
However, only two of the DC Motors are moving and the other two remain still.
Could you please suggest what happened?
Attached is the wiring of the motors and code.
char t;

void setup() {
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()) {
    t = Serial.read();
    Serial.println(t);
  }

  if(t == '1') {
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
  }

  else if(t == '2') {
    digitalWrite(9,LOW);
    digitalWrite(10,HIGH);
    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);
  }

  else if(t == '3') {
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
  }

  else if(t == '4'){
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
    digitalWrite(12,LOW);
  }

  else if(t == '5') {
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
    digitalWrite(12,LOW);
  }

  delay(100);
}

I have seen this question a number of times. What have you done to investigate the problem? Did you test each thing on its own: the arduino board, the driver module and the motors.

Why are you posting a new question, instead of editing your own? Duplicate of https://arduino.stackexchange.com/questions/56995/basic-question-on-dc-motors

To analyze your problem:

Switch two wires between two motors (and repeat this to get all combinations), to find out if the code/wiring until the motors is wrong, or there is a problem with the motors.
Print out the values of pins 9, 10, 11 and 12 and the value of t/input to see if the pins are controlled as you expect.
Remove all but one motors, for all motors one at a time, to see if there is no influence between them.

Below is not an answer to your question, but I can only align the code as answer.
It is better coding style to use the following form:
void loop() {
  if(Serial.available()){
    t = Serial.read();
    Serial.println(t);
  }

  if ((t >= '1') && (t <= '5'))
  {
    int input = (int) t - (int)'0';

    digitalWrite( 9, (input == 1) || (input == 4) ? HIGH : LOW);
    digitalWrite(10, (input == 2)                 ? HIGH : LOW);
    digitalWrite(11, (input == 1) || (input == 3) ? HIGH : LOW);
    digitalWrite(12, (input == 2)                 ? HIGH : LOW);
  }

  delay(100);
}

Note: ? : is a ternary operator which means : a ? b : c => if a then b else c.
Instead of using 9, 10, 11, 12 define pin numbers (e.g. PIN_MOTOR_X), and for 1, 2, 3, 4, 5 input numbers define LEFT, RIGHT, UP/FORWARD, DOWN/BACKWARD, STOP.

I don't know if I agree that code is better coding style, but it is definitely much more compact.  I slightly disagree with it being "better", because it's less obvious as to what the code does.  Part of good code style is making things readable.  This isn't bad code, just not obvious.  I definitely agree that naming the motors will make things a lot better.

@computercarguy Actually it would maybe be better to write a separate digitalWrite that has a parameter in for the 'boolean' so the ternary operator would not be needed (four times). (assuming the ternary operator is what bothers you, which I can understand).

Yes, there's a lot of different ways to write this.  The way you did it just isn't one I'd be comfortable supporting, and that's only because of the mental load to figure out what's going on.  I tend to write things more plainly/simply, so I don't have to really think about it when I have to read it later.  Abstracting the digitalWrite would probably be one of the better ways to simplify this.  And yes, when there's more than one ternary in a block of code, I kind of get the cold sweats.  :-)  I know how easy it is to abuse them.


text:
How to do I2C on Arduino with SDA and SCL pin already used
i have a Arduino screwshield from sparkfun that I purchased: https://www.sparkfun.com/products/9729 which I used to put between my arduino uno and my 2.8" TFT LCD touch shield so that I am able to use the unused pins. I have to make an I2C connection between 2 Arduino Unos which I understand will require the A4 and A5 pins however the TFT currently uses both pins. also, my tft screen is from here: https://www.sgbotic.com/index.php?dispatch=products.view&product_id=2756
The schematics of my tft are: http://www.sgbotic.com/products/datasheets/development/02756-schematic.jpg .
I am wondering if I can just use the A4 and A5 pins using the screw shield anyway since according to the schematics, the A4 pin is connected to the LCD_RST or is the pin necessary for displaying images taken from the SD card?
If that isn't the way, how should I go about doing it, does anyone know?

Please add a link to this in your question: https://www.sgbotic.com/index.php?dispatch=products.view&product_id=2756 The memory of the arduino uno will be filled before you can do something useful with it. I suggest to use the arduino mega or use a nextion screen instead. This example confirms that the reset is connected to a4: https://github.com/SGBotic/LCD-GUI-Library/blob/066d3c71cd00760af6da987e81b904bd36dbe29c/examples/display_text/display_text.ino

Even better, the chipKIT Lenny (like a Leonardo but far more powerful) with 2 I2C buses, plenty of RAM, and a professional TFT library (DisplayCore).

@Jot i see! thank you so much for pointing out that the uno memory may be filled else i would be wasting a lot of time. i've added the link to my question!

@Majenko, as in chipKIT Majenko-Lenny?

@Jot As in I designed it, yes ;) The chipKIT™ name isn't mine though - that's Microchip's property - I just license it from them.

No, you can't just use it. While I2C itself may work, the screen will keep resetting itself all the time and will be useless.
You may be able to get some luck with a software bit-banged I2C  on other pins. However I would personally choose to modify the TFT screen's PCB and cut the LCD_RST signal from the A4 pin and connect a 10kΩ resistor to +5V, or re-route it to another pin. That way you can then use I2C.

Second the Software I2C library (kudos felias-fogg, excellent work!). I have worked a lot with it and it performed really well. Had lots of trouble with the hardware Wire lib that went away with the software lib. Pick your own pins.

i see! thank you so much. as mentioned by @jot im afraid my uno will run out of memory so i will be switching over to the mega instead to save myself the trouble. thank you for your help!

If the LCD is using A4/A5 for something besides I2C, than no you cannot.

As I have very little knowledge about Prototype connection.But to avoid the soldering problems,
You May use I2C adapters as well as I2C cable joiners will be much useful and are specially designed for expansion of more than 1 I2C modules at the same time.
Hope These Sheilds and Adapters will be helpful for you.


text:
Why isn't the stack pointer changing in this simple sketch?
I'm playing around with context switching, and my first idea is to play with SP and see how it changes.  However, Sp doesn't do what I expect.  The sketch is below. I'm using an Uno R3.  What I expect to see is that SP should first print out some value, then it should be 4 integers further along (4x2 bytes?) when printed the second time.  But that doesn't happen, and both times I see the exact same value for SP.  What could the problem be?
    void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.print("X = ");
  Serial.println(SP,HEX);
}
void loop() {
  // put your main code here, to run repeatedly:
Serial.print("BEFORE: ");
Serial.println(SP,HEX);
int y = 15;
int z = y;
int g = z + y;
int dsf = z-y;
  Serial.println(dsf+g); //this should make these variables DO something...
  Serial.print(" After = ");
  Serial.println(SP,HEX);
  delay(1000);
}

Why do you assume that the stack will change? The AVR core has 32 registers. Plenty to store little temporary variables like those. Add to that the fact that the compiler optimizes lots of things out that it doesn't need, and you end up with almost nothing.

Valid point.  However, a similar sketch that actually called a function, whose sole role it was to print out SP, still had the SP not changing.  If I understand the function calls (perhaps I don't) then at least the return address should be on the stack at that point, shouldn't it?

You should examine the compiled assembly code to see what it's actually doing.

You should also read this: https://gcc.gnu.org/wiki/avr-gcc - especially the calling convention and frame layout sections

Thanks, will do.  If you summarize the comments as an answer I'll accept

You can use setjmp/longjmp for context switching. Please see https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/src/Scheduler.cpp#L124 as an example.

@MikaelPatel: I've set/jumped a bunch in previous code.  However, I want to do it on my own to see how it's done.  Otherwise I'd just download FreeRTOS or something

@MichaelStachowsky That is the spirit! Here is a link that might provide some insight. https://github.com/vancegroup-mirrors/avr-libc/blob/master/avr-libc/libc/stdlib/setjmp.S Writing that in C/C++ would provide an extra challenge :)

It's impossible to second-guess the compiler like that. There's a couple of things you need to realise:

The compiler will optimize out any variables that just get assigned to other variables as part of calculations and have no further use
The AVR CPU has 32 registers. More than enough to not need to use RAM to store values for a simple sketch like that.

Making the variables volatile will certainly help, since that forces the compiler to place them in memory. However you really should examine the assembly code the compiler produces to know exactly what it's doing.

Another way the compiler can optimize is to compile small or single-use functions inline. What you expected would get wrapped inside a call and return sequence, may not.
Inserting __attribute__ ((noinline)) ahead of the function definition can suppress that optimization:
__attribute__ ((noinline)) void foo(int bar)
{
   // do something
}

suppresses the inlining for function foo(). Inlining has frustrated my investigations more than once, so I created this easier to remember macro. (The keyword is just __NOINLINE; the #else-clause is there so that, umm, "someone", doesn't unwittingly try to use the "__attribute..." declarator with another compiler that doesn't recognize it).
// Don't compile this function inline
//   '__NOINLINE void foo(void){ ... }'
#ifdef __GNUC__
#define __NOINLINE  __attribute__ ((noinline))
#else
#define NOINLINE error 'NOINLINE' not defined for this compiler
#endif

Even small multi-use functions might be inlined.

I noticed that gcc is way more prone to inlining since the Arduino IDE started giving it the -flto compiler option. Before that point, it would not inline any non-trivial non-static function.


text:
DF Robot W5200 Ethernet Shield for an Arduino Uno not working?
I've been working on using an ethernet shield for my Arduino Uno for a couple weeks now. I've been going through the problems one by one and now realise that there seems to be nothing transmitting. Running code similar to DHCPAddressPrinter results in nothing, and any web server I set up does not work at all. Can anyone please help? Running the code below results in an output of "Baud rate set!" and nothing else. One thing to note is that the MAC address I am using is from going into the command prompt and using the MAC address listed from ipconfig /all, as there is no sticker on the ethernet shield itself.
    /*
    DHCP-based IP printer

     This sketch uses the DHCP extensions to the Ethernet library
     to get an IP address via DHCP and print the address obtained.
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13

     created 12 April 2011
     modified 9 Apr 2012
     by Tom Igoe

     */

    #include <SPI.h>
    #include <EthernetV2_0.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on         the shield
    byte mac[] = {
      /*MAC Address here*/ };

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
      Serial.println("Baud rate set!");

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for(;;)
        Serial.println("FAIL");
          ;
      }
      // print your local IP address:
      Serial.print("My IP address: ");
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
      }
      Serial.println();
      Serial.println("Loop");
    }

    void loop() {

    }

run the WebClient example sketch

Don't use the MAC address of your computer read from ipconfig output. It creates a conflict on LAN. Use the MAC address from examples.
To troubleshoot Ethernet shield, use the Ethernet library newest version 2.00. It supports W5100, W5200 and W5500 and has better diagnostic in examples.
And to troubleshoot, always connect the LAN cable to router or switch, not to computer, because direct connection to computer requires manual setup of addresses (no DHCP).


text:
How to read data directly from lcd display
Referring to post: LCD data read and show on computer
It was not clear what the final code is. Could you post the code and schema again, and if possible, an explanation of how it works?
My problem:
I need to read the information of a lcd 20x4 display, which is controlled by a PLC (which has the protected hex code), and send the data through the serial port.
For this I am using an arduino one to do the reading. I connected the arduino in parallel with the display data bus, to try to read the bits and convert later.
This is the schematic I'm using:

Note: I have placed 1k resistors to make the pulldown on each pin, to avoid reading errors.
With this code:

The problem is that I'm having these results in reading:

No matter what appears on the screen, they are always invalid characters.
If someone identifies where my problem is, I'll be very grateful.

No final code was posted as far as I can see, just pseudo-code that could be adapted to suit.

Stack Exchange is not a forum, and your "question" is not answerable.

I edited my question, I think it became clearer.

The display shown in your picture is 16x2 display LM016L. Why do you think that your "a 20x4 display" has the same control method as the LM016L display?

Serial.print() will be too slow for this.  Also your 1K resistors are potentially too stiff, if you want a keeper for undriven lines try 10K or larger.   Ultimately, you need to either write code informed by actual understanding of the operations described in the LCD data sheet (including details of clock-data timing), or if you just want to do a general capture to analyze, you should instead use a cheap USB-based logic analyzer ala sigrok/pulseview which has a chance of having sufficient sampling rate to capture the operations asynchronously.

I would recommend ditching the the digitalRead in this case - it is performed sequentially, and is rather slow.
As you only need to read 8 input lines, consider using Port register: The Arduino Uno comes with a total of three Ports which "hold" all of the I/O pins.
Those are

PORTB = Digital Pins 8 through 13 plus the crystal pins
PORTC = Analog Input 0 through 5, reset pin
PORTD = Digital Pin 0 through 7

Since you need the RX and TX lines (Digital pin 0 and 1) for your serial communication, you will have to split the signal onto two registers.
I would recommend connecting D0 through D3 to Digital Pins 8 through 11 for the first four bits (meaning they'll go to bits 3 to 0 of Port B), and D4 through D7 to Analog Pins 0 To 3 (meaning they'll go to bits 3 to 0 of Port C).
RW goes to Pin 7, RS to Pin 6, E to Pin 5.
The code you would then use to read the data would be this:
    uint8_t byte_displaydata = 0x00;
    uint8_t RW = 7;
    uint8_t RS = 6;
    uint8_t E = 5;
void setup() {
  Serial.begin(1200); //perhaps increase this a bit
  pinMode(RW, INPUT); //some speed is lost compared to register manipulation, but that is likely insignificant
  pinMode(RS, INPUT);
  pinMode(E,INPUT);
  DDRB &= ~((1 << DDRB0) | (1 << DDRB1) | (1 << DDRB2) | (1 << DDRB3)); //technical not necessary since they're initialized with 0
  DDRC &= ~((1 << DDRC0) | (1 << DDRC1) | (1 << DDRC2) | (1 << DDRC3));
  PORTB &= ~((1 << PORTB0) | (1 << PORTB1) | (1 << PORTB2) | (1 << PORTB3)); //disable internal pullups
  PORTC &= ~((1 << PORTC0) | (1 << PORTC1) | (1 << PORTC2) | (1 << PORTC3));

}

void loop() {
  if(digitalRead(RS) == HIGH && digitalRead(E) == HIGH){
    byte_displaydata = 0x00; //reset byte_displaydata
    byte_displaydata = PINB << 4; //push PINB bits 3 to 0 to bits 7 to 4
    byte_displaydata |= (PINC & 0x0F); //filter PINC bits 3 to 0 and OR them into result bits 3 to 0
    Serial.println(byte_displaydata,BIN);
  }
}

Please note that I have not tested this, and only recently have gotten started in AVR / Arduino.
If anyone can look this over, I'd greatly appreciate it.
Source: Microchip ATmega328P datasheet, Arduino pin mapping

It is probably too late for the OP but there is a protocol sniffer for such LCD screens which use the HD44780 series LCD driver as, for example, the common LCD1602 does.
The code is published here:
https://forum.arduino.cc/t/lcd-1602-and-similar-databus-sniffer/675769/11
The data rate would be too fast for Serial.print() to print each character received in real time so a queue is used to consolidate the data.


text:
Using Arduino UNO for uploading a sketch to the Espresso Lite v2
I am trying to use my Arduino UNO as a programming interface to load sketches on the Espresso Lite v2.
I followed the instructions to setup the Wifi network (long press gpio13 and the AP thing), but now I want to run code on it.
I uploaded this sketch to the UNO, in order to allow for serial communication(i chose method 3):

void setup(){
  pinMode(0,INPUT);
  pinMode(1,INPUT);
}
void loop(){
}

Afterwards I configured the Arduino IDE with the necessary libraries and device manager plugins for the Espresso, so I selected "Espresso Lite 2.0" as the target board and for programmer "Arduino as ISP".
This is what my tools menu looks like:

I connected the 3.3V, GND, TX (to TX) and RX (to RX) and RESET (to RST) headers from the Arduino UNO to the Espresso Lite holes. If I open the Serial Monitor I can see serial output so I think the connections are correct.
I tried to upload an empty sketch and i got these errors (verbose upload):

Sketch uses 246096 bytes (23%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27588 bytes (33%) of dynamic memory, leaving 54332 bytes for local variables. Maximum is 81920 bytes.
C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.13/esptool.exe -vv -cd ck -cb 115200 -cp COM3 -ca 0x0 -cz 0x400000 -ca 0x00000 -cf C:\Users\ADMINI~1\AppData\Local\Temp\arduino_build_89/sketch_oct08a.ino.bin
esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    setting erase size to 0x00400000
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
An error occurred while uploading the sketch
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 0D instead of C0
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 45 instead of C0
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 0D instead of C0
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 74 instead of C0
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 0D instead of C0
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 45 instead of C0
warning: espcomm_sync failed
error: espcomm_open failed

This is the serial output after i tried to upload:

What am I doing wrong?

@gre_gor this is different: I am trying to troubleshoot the "sketch upload" function on a specific board

You can't use "Arduino as ISP" to program an ESP8266.

@gre_gor What should I select in this case? Is the fact that I can see serial output irrelevant?

Don't connect reset pins together.  Selecting "Arduino as ISP" is irrelevant in many ways.
Put the esp8266 into flashing mode by resetting it with io 0 LOW at reboot (hold button GPIO0 and click the RESET button). And then Upload from IDE. The esptool can't reset the board to flashing mode because you don't have RTS and DTS line from Uno.
Picture from manufacturers page:

This solved my issue!


text:
ATTINY85 with RGB LED
I'm trying to DIY about a dozen BlinkSticks (discontinued, Adafruit) pictured here

I'm thinking to use a Digispark ATTINY85 to control a single RGB LED to show the status of some program running under Linux. Here is the proto board I have my eye on:

I could either use a single individually addressable RGB LED with a built-in WS281X controller

or a plain RGB LED with each color pin connected to a GPIO pin on the TINY85.

This is my first Arduino project, so I'm not familiar with the best way to approach this project. I'm trying to keep the part count low as well so the serial data approach is appealing too. Has anyone done this before and can explain their setup?

Prior work I've found for the simple control approach:

The blinkstick schematics are available: https://www.blinkstick.com/help/schematics

A plain rgb led needs resistors and with the same resistors one color is brighter than an other color. So you have to tune the resistors or the pwm in the code. A rgb led with built-in controller is easier to get a certain color, and the controller has often more than 8 bits so very dim values are no problem. However, you need a library which uses flash and ram which is very limited for a attiny85. The best option is a atmega328p with a rgb led with built-in controller. Everything else is looking for trouble.

The newest blinkstick uses an addressable led, while the Adafruit kit appears to use a regular 4 pin RGB led. These are easier to get.
The digispark and the blinkstick are almost identical, but they use different pins for the USB connection. So to use the firmware for the blinkstick on the digispark, you need to change the pin numbers in usbconfig.h
#define USB_CFG_DMINUS_BIT      3
#define USB_CFG_DPLUS_BIT       2

PS. the pin numbers in usbconfig.h don't seem to match the schematic, so I'm not sure what's going on

This is a good observation. Thanks for taking the time. I'll assemble the project with the ATTINY85 board I've found and the WS2812 LED plus the capacitor, then adjust the firmware as you indicated and report back how it works. Thanks again.

I don't think you need the capacitor. Best of luck.


text:
Leonardo Problem
I have boiled this down to a very simple piece of code:
int testKey;

void setup() {

Serial.begin(9600);

}

void loop() {

Serial.println("Input Source ID "); //Ask me the number

while (Serial.available()==0){ } //Wait for me to answer

testKey = Serial.parseInt();  //Store my answer in this variable

Serial.print("Parsed Input is ");  //Print the results on serial monitor

Serial.println(testKey);

}

When I run the code on my Leonardo, or Uno, I expect to have Input Source ID to be printed on the serial monitor. It remains blank (it is set to 9600 baud). If I go ahead and enter a 1, then the serial monitor starts working. However, from this point on, it seems to ask me for the ID again, and print a 0 to the serial monitor:
Parsed Input is 1
Input Source ID
Parsed Input is 0
Input Source ID
It then is waiting for me to enter a new Source ID. If I then enter a 2, this is what I get, in addition to what was already there.
Parsed Input is 1
Input Source ID
Parsed Input is 0
Input Source ID
Parsed Input is 2
Input Source ID
Parsed Input is 0
Input Source ID
My question is, why doesn't the void loop start automatically and immediately prompt me for input? Secondly, after I give it a number, it seems to run it twice, inserting a 0 into the variable. Why? This seems so straightforward, but it has me stumped. I tried some delay statements here and there, to no avail. Thanks in advance.

You can set the line ending in the serial monitor to all combinations with carriage return and linefeed. Try all the possibilities and you see. No one of use uses the Serial.parse... functions, they are inconvenient.

Ok, thanks to both of you! I have implemented your suggestions, and I am able to get the expected results. Kudos to you!

My question is, why doesn't the void loop start automatically and immediately prompt me for input?

It does. However your serial monitor isn't open at that time and can't receive it.  Unlike the Uno the Leonardo does not reset when you open the serial port.
A common workaround, to make it look more like an Uno, is to add:
while (!Serial);

in setup() after Serial.begin(...), so that it does nothing until you open the serial terminal.

Secondly, after I give it a number, it seems to run it twice, inserting a 0 into the variable. Why?

Simple: you're parsing the number as a number. You're then parsing a blank line as the number.
If you have the serial monitor set to send CR + LF as the line ending you get the integer terminated by CR, followed by no integer (represented by 0) followed by LF.

This line:
while (Serial.available()==0){ } //Wait for me to answer

Doesn't wait for you to answer, it only waits until the first character is typed. This while loop happens about a million times a second on an Uno. You can't possibly type more than one character in that microsecond. Once you type it, the clock starts ticking, because parseInt() uses a timeout value, so if no valid digit character is entered by the timeout, it exits. The default timeout is 1000ms (1 second).

the entered value is sent from serial monitor after Send button or Enter key. Even at 9600 baud the gap between characters is far less then a second

True; I forgot about serial monitor.

and you plan to leave it here?

Sure. If it's a poor answer, it will get downvoted, as it ought to be.