Unclear GET request mixed values In my Uno code, I access to a page in my server and retrieve that value and make decision upon that value.

I get this kind of response,

Connected to server
on
on
off
off
on
off
[WiFiEsp] TIMEOUT: 116

Disconnecting from server.

Which should just be on or off.

This is my code for testing :

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2,3); // RX, TX
#endif

char ssid[] = "RPi";            // your network SSID (name)
char pass[] = "raspberry";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "192.168.50.1";

// Initialize the Ethernet client object
WiFiEspClient client;

int c =0;
int testLED = 12;

void setup()
{
  pinMode(testLED, OUTPUT);
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  printWifiStatus();

  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("GET /simple.txt HTTP/1.1");
    client.println("Host: localhost");
    client.println("Connection: close");
    client.println();
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
  if (client.available()) {
     c = client.read();

     switch(c){
          case '0':
                 Serial.println("off");
                 digitalWrite(testLED, LOW);
                 delay(2500);
                 break;

          case '1':
                 Serial.println("on");
                 digitalWrite(testLED, HIGH);
                 delay(2500);
                 break;
      }
        }

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();

    // do nothing forevermore
    while (true);
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

My simple.txt file just has 1.

Why this code outputs a gibberish value? Is it a problem with the way I retrive data?
Raspberry pi is working as my network server.

Thanks in advance.

When you send a GET request in HTTP you get a HTTP response back, not just the contents of the file you requested.

For instance, your request may result in a response of:

HTTP/1.1 200 OK
Date: Thu, 28 Dec 2017 11:02:21 GMT
Server: Apache/2.4.25 (Ubuntu)
Last-Modified: Wed, 05 Apr 2017 09:40:30 GMT
ETag: "2c39-54c682ee19688"
Accept-Ranges: bytes
Content-Length: 3
Vary: Accept-Encoding
Connection: close
Content-Type: text/plain

1

As you can see there's plenty of occurrences of 0 and 1 in there to trigger your LED.

You need to parse the incoming data better. Read it line by line and only start reacting to the content after the blank line that indicates the division between header and body.


Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using 'localhost:1.0' as the value of the DISPLAY variable I have tried everything on this url
https://stackoverflow.com/questions/10165761/java-cant-connect-to-x11-window-server-using-localhost10-0-as-the-value-of-t
session output:
root@whale:/home/kermit# echo $DISPLAY
localhost:1.0
root@whale:/home/kermit# cd dev/sht30/
root@whale:/home/kermit/dev/sht30# arduino --upload sht30v1.ino --port /dev/ttyUSB0
Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using 'localhost:1.0' as the value of the DISPLAY variable.
        at java.desktop/sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
        at java.desktop/sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:102)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.desktop/sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:61)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:315)
        at java.desktop/java.awt.GraphicsEnvironment$LocalGE.createGE(GraphicsEnvironment.java:101)
        at java.desktop/java.awt.GraphicsEnvironment$LocalGE.<clinit>(GraphicsEnvironment.java:83)
        at java.desktop/java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:129)
        at java.desktop/sun.awt.X11.XToolkit.<clinit>(XToolkit.java:231)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:315)
        at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:588)
        at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:583)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.desktop/java.awt.Toolkit.getDefaultToolkit(Toolkit.java:582)
        at processing.core.PApplet.<clinit>(Unknown Source)
        at processing.app.Preferences.save(Preferences.java:735)
        at processing.app.Preferences.init(Preferences.java:249)
        at processing.app.Base.main(Base.java:117)

How do you run arduino in headless mode on a raspberry pi?

It is probably a non-existant or stale auth cookie in your .Xauthority file.  This sort of thing happens when you're running your X session with one user but trying to run your X application as different user.  Doing sudo or su root (or really any other user) is a common way to get in that situation.  Running the IDE as root usually mean something else has already gone sideways.  The typical reason for that is you're running as root instead of fixing your permissions to the Arduino serial device file.

That said, if you want to run headless builds and uploads of Arduino projects, what you're looking for is arduino-cli.
cd /path/to/directory/containing/sht30v1.ino
arduino-cli -b arduino:avr:nano compile
arduino-cli -b arduino:avr:nano upload --port /dev/ttyUSB0


srd-05vdc-sl-c and coil operating time I'm using Arduino UNO to control an imatic relay board with 16 relays model srd-05vdc-sl-c.
I use all the relays to control some linear actuators and everything is working fine.

My only question is: are the coils used for these relays for continuous use? I mean, can I continue to give power to some coils for more than 30 minutes? Or will they be destroyed?
Should I write a specific Arduino routine to power off all the coils when not used, or can I leave them powered for 30 or more minutes?

I checked the relays and they do not overheat.

You can leave them energized for more than 30 minutes. My 16 year old car with 250,000 km still has the original fuel pump relay. I can't imagine how many hours of continuous use it received over this period of time. The relay in my car is not the same make / model as the relays you are using, so you should check with the manufacture to see if there is a "service lifetime" specification.


How to make two small micros communicate with my Arduino over BLE? I want to do a project with an Arduino Uno and two other BLE (or regular bluetooth) capable modules. I want the Bluetooth modules to be hooked up to buttons (one button for each Bluetooth module). I then want the Bluetooth-capable modules to send the state of their buttons to a central Arduino board.

Is this possible? Can I have two different BLE boards connected to one Arduino?

I have a RedBear BLE (Bluetooth low energy) shield for my Arduino. What micro-controllers should I get for the peripheral modules? And where can I learn about pairing Bluetooth modules? Everything I read seems to be about pairing Bluetooth boards to a phone.

Can I do this all with BLE or am I going to need to get a new shield for my Arduino to talk with the two peripheral boards?

Thanks.

You can use SoftwareSerial to communicate with two modules from an uno. But You will have to wire 'em up separately, not through your shield. (making the total number of bluetooth modules 4.

You could also use your existing sheild and poll between the two remotes. I.e. disconnecting from one and connecting to the other at a regular interval.

For the micros and bluetooth for your button, you could use a HM10 with an ATtiny like in this instructable. He uses two HM10 modules to talk to each other. HM-10 is a popular BLE module. If you want regular bluetooth(2.0), you can use HC-05.


Getting stable measurements with the BNO055 IMU I bought the BNO055 "smart" IMU from Adafruit, thinking it would be a simple way to get orientation data for a small mobile robot project, but I've found the thing to be very difficult to use and nearly worthless.

It's advertised as being able to auto-calibrate, and although it does attempt to do this, I've found that the calibration doesn't hold. It continuously re-calibrates itself, and either gets stuck in an error state or find a successful calibration...but then loses it after a few seconds.

Is there anything I can do to improve its stability? Does it need to be mounted inside a special grounded housing? Is there a special incantation I should utter before powering it on?

I'm reading it from an Arduino Uno via I2C, and though the wiring and programming is relatively simple, getting it calibrated and staying calibrated I've found to be nearly impossible.

Even after the "system" flag says its fully calibrated, and I have the IMU just sitting on a table, not moving, after a minute, it loses its "system" calibration. The accelerometer, gryoscope, and magnetometer usually remain calibrated, but how can I trust them if the on-board fusion algorithm is reporting it's not ready?

If the BNO055 is a lost cause, is there anything better? I've tried several MPU-**** chips from InvenSense, but they're even worse.

Try a permanent calibration. From the Adafruit forums:

  You'd basically need to read and write data registers 55-6A. In both cases, you have to set the sensor in CONFIG_MODE. There's more information on page 48 of the datasheet.

The magnetometer is influenced by surrounding magnetic sources like motors. You might be able to tell the extent of the effect using the following method:

  The System Calibration Status will start out at 0 and will go to 3
  when the sensor is calibrated. For example, the mag calibration status
  will go to 3 if you do some figure 8s. If you put a piece of metal
  near the sensor, the calibration status will drop to 0. But when the
  metal is moved away, it will go back to 3. You may be able to use this
  value as an indicator that calibration is lost. I have found that once
  it's calibrated, it seems to hold calibration well.

For getting solid readings out of the gyroscope, this might be helpful advice:

  I don't worry about scaling the gyro output on a per-sample basis. I simply sum the output into a 32 bit (or larger) integer register. I do subtract-out a null value at each sample, which I will talk about later. But essentially, if you sample your gyro at 1kHz, and sum the output into an accumulator, you will see that the value of that accum at any time will be directly proportional the angle of rotation. If your rate is set for 250 deg/sec, then a rotation of 180 deg will result in approximately 23330000 in the accumulator. I call that the GYRO_CAL number. So, at any given time the angle, in degrees, is deg = accum / GYRO_CAL * 180.

  Since the gyro output is linear, the accumulator is insensitive to
  whether the rotation is fast or slow (as long as the max deg/sec isn't
  exceeded).

  Here is my basic routine for each gyro reading:

void read_FIFO(){
       sample = read_value_from_FIFO();   //read the latest z-axis sample. I use the fifo, but that isn't necessary
       accum += sample - null;           //add the sample to the sum and subtract the null
       if((accum > GYRO_CAL) -= GYRO_CAL*2;  //roll the accumulator at +180 deg.
       if((accum < -GYRO_CAL) += GYRO_CAL*2; // roll the accumulator at -180 deg.
       angle = accum/GYRO_CAL * 180;   // convert to degrees
}

  I calculate the null at the beginning of each run. I sum 1000 readings
  and take the average. The gyro has to sit still for 3 or 4 seconds for
  this. The GYRO_CAL value can be calculated by summing the output while
  you rotate the gyro by 180 deg. Or you can sum over many turns, and
  divide by the number of 180 deg turns for a more accurate value.

  You could probably use a 64-bit FP for the accumulator, but since
  arduino only supports 32 bit FP, I found it absolutely necessary to
  use a 32 bit integer to avoid roundoff and other errors.

  If you follow that general outline, I promise you will get rock solid
  performance out of the gyro. There are a few other small optimizations
  that I make, which I can discuss later.


Interfacing Digital clock with Uno I want to take input from a clock for a specific time and respond to it.

I am taking alarm as input because it will send some signal to a buzzer and I want to decode it through Arduino.

I am using Arduino Uno.

The program I used is as follows:

int b = 0;

void setup() {
    pinMode(8, INPUT);
    Serial.begin(9600);
}

void loop() {
    b=digitalRead(8);
    Serial.println(b);
    if(digitalRead(8) != 0)
    {
        Serial.println("input in 8");
    }
    else
        Serial.println("not");

    delay(500);
}

I have removed the buzzer from the clock and connected the terminals to Arduino pin 8 and GND.

But the output is always random (i.e. 0 & 1), no matter if my alarm is on or off.

I cannot find if my program has a flaw or if my approach is just wrong.

It is likely that the alarm clock does not provide any voltage level (I mean GND) to the  buzzer when it does not have to ring, the circuit is just left "open" then; it will provide a voltage level (depending on your clock power supply) only when the alarm has to ring.

On the other side, your Arduino pin 8 must have a voltage level that can be mapped to a 0 (anything between GND and 5V/3) or a 1 (anything between 2x5V/3 and 5V).

However, in the absence of alarm, the input is left "dangling" (no voltage level at all). In CMOS technology, leaving an input pin dangling will make it randomly take 0 and 1 levels as you described.

Fortunately, the solution to this problem should be easy: you just have to force a 0 level to pin 8, by connecting it to GND through a resistor. I generally use 10K or 15K for that resistor. This is called a "pulldown" resistor:

when the alarm does not provide any voltage, the input pin level will be "pulled down" to GND, ie 0.
when the alarm provides a 5V (see important remark below) to the input pin, then it will be seen as 1.

IMPORTANT: you have to make sure that your alarm clock, when ringing, provides a voltage that is not higher than 5V (it would grill your UNO, or more precisely the ATmega328 of your UNO) and is at least ~3V to be "recognized" as 1.

NOTE: it is likely that solving this first issue will not be enough to make your complete program work, because your alarm clock probably does not send a continuous voltage to your buzzer but and alternate one to make it ring, hence you will get successive 1 and 0 at high speed (between 100Hz and 100Hz I would say) in your program. If that is the case please open another question as the solution for that specific issue is disconnected from the current one (random 1 and 0).


Issue with incrementing PWM over time First post here. So I have an issue, which I have identified, but I'm not quite sure how to fix it.
I'd really appreciate some input and suggestions.
I realize that my "pwmDelta" is the problem, but I am not sure what to do to fix it.

I am trying to write a program that will increment the value of the pin 3 a set amount of time, in a somewhat linear fashion, starting at my low point, and finishing at my high point.

The issue is that my equation is incorrect and I can't output a partial bit value. Huge oversight on my part. If you read the data from the serial monitor with the code written as I have it, you'll see that it isn't coming even close to reaching my max value.

I need suggestions on how I can have the program figure out the delta in a way that I can send an integer value to the PWM output pin, yet still keep a somewhat linear increase over time. Would this even be possible?

int motor1 = 3;         //pin for PWM output to motor
float t = 0;            //Variable to keep Track of time
int tLim = 30;          //Time Limit for Ramp
float lowLim = 21;      //Low Limit, in Duty Cycle %
float highLim = 65;     //High Limit, in Duty Cycle %
float motorPWM = 53.55; //Starting Value of PWM, in Bits
float pwmDelta = ((255/100)*(highLim-lowLim))/(tLim); //Delta equation, to calculate how much to change PWM value each time it is incremented
float motorDelta;       //Variable to write value to Motor Output

void setup() {
  pinMode(motor1, OUTPUT);
  analogWrite(motor1, 53.55); //run motor at initial value for 20 seconds before beginnning ramp
  delay(20000);
  Serial.begin(9600);
}

void loop() {
  motorDelta = motorPWM + pwmDelta; //incrementing output value based on Delta Equation
  motorPWM = motorDelta; //Setting new incremented value equal to old value, so incrementing can continue

  if (t <= tLim) {  //Check if time is <= time limit
    analogWrite(motor1, (motorDelta)); //write incremented value to output pin
    delay(1000);  //wait 1 second, increment t, to keep track of time
    t++;
  }
  else {
    analogWrite(motor1, motorPWM = 165.75); //set pin to high value for 60 seconds, then set to 0
    delay(60000);
    analogWrite(motor1, motorPWM = 0);
  }
  Serial.print(motorDelta);
  Serial.println();
  Serial.print(t);
  Serial.println();
}

float pwmDelta=((255/100)*(highLim-lowLim))/(tLim);

That line should be:

float pwmDelta=((255.0/100)*(highLim-lowLim))/(tLim);

Adding the .0 tells the compiler to do that math using floats and you get 2.55.  Without it the math is done with int and the result is 1 which isn't what you want.

analogWrite(motor1, 53.55);

Just write 54.  analogWrite only accepts integer values.

analogWrite(motor1, motorPWM=165.75);

You should really do that as two lines, an assgnment and then an analogWrite.  This way leads to confusing code.  Also, analogWrite only accepts integer values so your decimals are useless there as well.


MQ135 Gas Sensor Calibration I have bought a MQ135 gas sensor. I have read online from multiple sources that a calibration/warm-up period of between 12-24hrs is required for the sensor to give its most accurate readings. I currently have it attached to one of my UNO's just spitting out Analog readings to the Serial monitor and seems (just after an hour!) to have settled at a reading of 50 which it has stayed at now for a period of around 20 minutes. My questions surrounding this process really are:

What is the point in doing this process if when a project that uses this sensor is powered off for some number of hours? Will you have to let it warm-up/calibrate again before having faith in the readings?
How do I actually identify PPM for a gas such as C02? Is there some form of constant that I should be comparing the reading obtained to or something similar?

By my opinion, it is impossible to calibrate these solid electrolyte based sensors. I achieved best results when I measured the CO2 level in 5 minute intervals, by heating the sensor for 100 seconds. I cant remember these times precisely, but by heating and allowing it to cool down I was able to get quite reliable results. But then I realized that the sensor is getting some offset. If you want to do a two-point calibration, you can put it to fresh air, it should read about 0.04%, or you can breathe directly to the sensor for a short while and it shoud read 4%. But I highly recommend using NDIR CO2 sensor, those are used in home air monitoring devices.


Joysitck with servo, LED array and buzzer Does anybody know of a sketch that can turn a single servo 180 degrees clockwise/counterclockwise with the x axis of a joystick, light a bar graph LED with the Y axis, and sound a buzzer when the joystick button is depressed.

You have a distinct set of requirements that you could turn into a sketch yourself.  I'm guessing you have never written a program before, in which case the problem really is you don't know how to do what you want to.

So, break the problem down into small chunks.  The less complex a problem the more likely you are to find a generic solution on the web that you can 'borrow'.

How do you turn a servo?
How do you read the position of a joystick?
How do you light a LED bar graph?
How do you sound a buzzer?

I'm pretty certain that you can find pages that tells you how to do each of those in separate sketches.  Once you have each of those working you need to merge the setup functions, making sure they don't over write each other and then tackle the loop functions (which will be more difficult).  BUT I know there are posts on here about how to merge two sketches into one.

I'm 99% certain you will not find a sketch that does what you want.  I'm 99% certain you will be able to coble together a solution that will do what you want if you break it down.

If you get stuck, post the code you have and explain your problem and people will help.

Good luck.


Combining code for multiple sensors in one program I need to operate 2 different sensors (gas and temp) simultaneously.
I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.

Here are the sketches:

Thermistor code:

void setup() {
  //This function gets called when the Arduino starts
  Serial.begin(9600);
  //This code sets up the Serial port at 9600 baud rate
}

void loop() {
  //This function loops while the arduino is powered
  int val; //Create an integer variable
  val=analogRead(0);
  //Read the analog port 0 and store the value in val
  Serial.println(val);
  //Print the value to the serial port
  delay(1000);
  //Wait one second before we do it again
}

This is the gas detector code:

/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int sensorPin = A0;
// select the input pin for the potentiometer
int DOPin = 2;
// select the pin for the LED
int sensorValue = 0;
// variable to store the value coming from the sensor
int ledPin =13;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(DOPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  Serial.print("Analog Output = ");
  Serial.println(sensorValue);
  // turn the ledPin on if triggered
  if (digitalRead(DOPin) ==HIGH) {
    digitalWrite(ledPin, LOW);
    Serial.println("Digital Output = OFF");
  } else {
    digitalWrite(ledPin, HIGH);
    Serial.println("Digital Output = ON");
  }
  delay(1000);
}

You just need to assign the sensors different pins.

/* GAS Sensor MQ-2
This sensor detects flammable gasses
the board has four pins
connect AO to Arduino pin A0
connect DO to Arduino pin 2
connect Gnd to Arduino Gnd
connect Vcc to Arduino 5 volts
*/

int gasSensorPin= A0; // GAS sensor pin
int DOpin= 2; // select the pin for the LED
int gasSensorValue= 0; // variable to store the value coming from the sensor
int ledPin = 13;

int tempSensorPin = A1;  //Temperature sensor pin
int tempSensorValue;

void setup() {
 // declare the ledPin as an OUTPUT:
 pinMode(DOPin, INPUT);
 pinMode(ledPin, OUTPUT);
 Serial.begin(9600);
 }

void loop() {
 // read the value from the sensor:
 gasSensorValue= analogRead(gasSensorPin);
 Serial.print("Analog Output = ");
 Serial.println(gasSensorValue);
 // turn the ledPin on if triggered
 //
 if (digitalRead(DOpin) == HIGH){
 digitalWrite(ledPin, LOW);
 Serial.println("Digital Output = OFF");
 }
   else {
     digitalWrite(ledPin, HIGH);
     Serial.println("Digital Output = ON");
  }

Serial.print("Temperture: ");
tempSensorValue = analogRead(tempSensorPin));
Serial.println(tempSensorPin);  //Print the value of pin A4

delay(1000);
}

This is your combined sketch.


I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery? I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?

No, you need to use a (roughly) 6V battery. They are 6V motors, so they need a 6V battery.

However, you do need to sum the currents not the voltages. The battery must be able to provide at least the current required by both motors together.


Splitting a Serial.readString into string array I am working on a project where I need to split incoming data from serial (time to be exact, so aa:bb:cc) and need to split it into aa then bb and cc, ideally into  an array. I know I could use readStringUntil and make 3 separate variables, but I would prefer it is in arrays. Here is the code that supposed to do this. It works with predefined string (eg. 00:00:00), but with reading serial it says that the initializer fails to determine size of "input".
Thank you in advance for helpful suggestions.

Here is the code:

void setup() {
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  Serial.begin(9600);
  while(!Serial.available()){} //wait until Serial data received
  String vst = Serial.readString();
  char buf[vst.length()+1];
  vst.toCharArray(buf, vst.length());
  char input[] = vst;
  char delic[] = ":";
  char* sub = strtok(input, delic);
  while(sub != NULL){
   Serial.println(ptr);
    sub = strtok(NULL, delic);
  }

}

Your main problem is this:

char buf[vst.length()+1];

You can't initialize an array with the return value of a function.

Instead you would need to use alloca to perform the same function:

char *buf = alloca(vst.length()+1);

However, the way you're doing it is wasteful. You don't need buf at all.  You can directly access and manipulate the internal char buffer inside the string using vst.c_str();.

For convenience you can point buf at it:

char *buf = vst.c_str();

To complete the picture here's a routine that takes the string and gives you three integers. Since we expect a specific format with only 3 sections to it we don't really need a loop.

// Use readStringUntil to avoid the 1 second delay.
String vst = Serial.readStringUntil('\n');
char *buf = vst.c_str();

char *hourString = strtok(buf, ":");
char *minuteString = strtok(NULL, ":");
char *secondString = strtok(NULL, ":");

if (secondString != NULL) { // Will only be true if we have two colons
    int hours = atoi(hourString);
    int minutes = atoi(minuteString);
    int seconds = atoi(secondString);

    Serial.print("It is ");
    Serial.print(minutes);
    Serial.print(" and ");
    Serial.print(seconds);
    Serial.print(" seconds past ");
    Serial.println(hours);
} else {
    Serial.println("Invalid time format");
}


Accessing struct's variable parametrically on ESP8266 I have 2 instances of a struct. One has def values stored and second stores values read from a file on SPIFFS.
I'm trying to use a for loop over all struct's variables - if file was read OK and key was found, store its value in final_par else get value from def_par.
For that, I've created keys array - but I can't find a way to iterate, in a for loop
as final_par.keys[i] = def_par.keys[i] - but this is not possible.
How can it be done ?
struct parameters
{
  bool ext_inputs;
  bool auto_relay_off;
  bool useSerial;
  bool useWDT;
  bool useOTA;
  bool useResetKeeper;
  bool useFailNTP;
  bool useDebugLog;
  char deviceTopic[20];
  char groupTopic[20];
  char prefixTopic[20];
  int inputUpPin;
  int inputDownPin;
  int outputUpPin;
  int outputDownPin;
  int inputUpExtPin;
  int inputDownExtPin;
  int auto_relay_off_timeout;
};
char *keys[] = {"ext_inputs", "auto_relay_off", "useSerial", "useWDT", "useOTA", "useResetKeeper",
                "useFailNTP", "useDebugLog", "deviceTopic", "groupTopic", "prefixTopic", "inputUpPin",
                "inputDownPin", "outputUpPin", "outputDownPin", "inputUpExtPin", "inputDownExtPin",
                "auto_relay_off_timeout"};

parameters def_par{false, false, false, true, true, false, true, "devTopic", "noGroup", "myHome", 2, 1, 14, 12, 0, 2, 60};

parameters final_par;

You can do it but it can be awkward. You'll need an array of structs, each member of which describes one member of your 'struct parameters' - essentially, an expansion of your present 'keys[]'.
Then you can consult this array randomly or in order to find the name, data-type, and memory offset of a given parameter (indexed by parameter order), or search it, to access the same information by parameter name.
Here's your parameter struct with some (incomplete but runnable) code to list the descriptor array, and incidentally, show how to build and use the array. Note that the code compiles but with a warning that a member of your 'parameters' was not initialized. I chose not to fix that; it isn't used here and doesn't prevent compilation.
struct parameters
{
  bool ext_inputs;
  bool auto_relay_off;
  bool useSerial;
  bool useWDT;
  bool useOTA;
  bool useResetKeeper;
  bool useFailNTP;
  bool useDebugLog;
  char deviceTopic[20];
  char groupTopic[20];
  char prefixTopic[20];
  int inputUpPin;
  int inputDownPin;
  int outputUpPin;
  int outputDownPin;
  int inputUpExtPin;
  int inputDownExtPin;
  int auto_relay_off_timeout;
};
//char *keys[] = {"ext_inputs", "auto_relay_off", "useSerial", "useWDT", "useOTA", "useResetKeeper",
//                "useFailNTP", "useDebugLog", "deviceTopic", "groupTopic", "prefixTopic", "inputUpPin",
//                "inputDownPin", "outputUpPin", "outputDownPin", "inputUpExtPin", "inputDownExtPin",
//                "auto_relay_off_timeout"};

parameters def_par{false, false, false, true, true, false, true, "devTopic", "noGroup", "myHome", 2, 1, 14, 12, 0, 2, 60};

parameters final_par;

// A couple of functions to extract data from an array or struct:
#define countof(a) (sizeof(a)/sizeof(a[0]))                             // ret # of array elements (not bytes)
#define offsetof(struc, member) ((int)(&(((struc*)(0))->member)))   // ret byte-offset from start of struct to the given member

// Enumerate possible parameter types
typedef enum {
   t_bool,
   t_char,
   t_int
} parType;

// Descriptor table - contains name, type, and offset of each parameter
// Could go in flash to save a bunch of RAM
struct descriptor {
   const char *name;
   parType pType;
   uint8_t offset;
} Descriptors[] = {
   { "ext_inputs", t_bool, offsetof(parameters, ext_inputs) },
   { "auto_relay_off", t_bool, offsetof(parameters, auto_relay_off) },
   // ...
   { "inputUpPin", t_int, offsetof(parameters, inputUpPin) },
   // ...
   { "auto_relay_off_timeout", t_int, offsetof(parameters, auto_relay_off_timeout) }
};

void setup() {
    Serial.begin(115200);
    Serial.println("parameter        type          offset\n");
    // List the parameters' names, types, and offsets within 'struct parameters'
    for( uint8_t i = 0;  i < countof(Descriptors);  ++i ){
        Serial.print(Descriptors[i].name);    Serial.print(", ");
        Serial.print(Descriptors[i].pType);   Serial.print(", ");
        Serial.println(Descriptors[i].offset);
    }
}

void loop(){
    ;
}


Controlling multiple 12v solenoids with 5v relay modules (Arduino Reset Issue) I have 4 12V(1A) solenoids running on a 12V(4.16A) power supply.
Each solenoid circuit is controlled by a 5V relay module connected to the Arduino Uno (powered by USB).

The solenoids actuate properly but eventually the Arduino resets, typically when multiple solenoids are turned on/off in fast succession. This is accompanied by random character artifacts on the LCD display (connected to the Uno) during operation but before the reset.

From what I've gathered there are back EMF surges occurring when the solenoids lose their charge. Here are some possible remedies I've found:

Add a flyback diode (IN4004) to each solenoid circuit. (Redirect the surge)
Add a capacitor (4700 - 10,000 uF) to the 5v supply (from the Uno) for the relays. (Filter the surge)
Provide a separate 5v power source to the relay modules instead of using power from the Uno. (Isolate the surge)

Any input on which solution(s) should be applied or other possible causes for the Uno reset and LCD distortion is appreciated.

Some of those 5V "digital" relays can be wired using a separate power supply for the relays and the Arudino. You have to move a jumper to use separate power supplies.

My guess is that you're powering both your Arudino and your relay coils from the same 5V supply, and when you energize all 4 relays at the same time you draw too much current and the Arduino doesn't get enough voltage and resets.

Read up on your relay modules, and either re-wire them using 2 different 5V supplies, or switch your 5V supply to a higher current supply. (and possibly adding a filtering capacitor to the Arduino to smooth out the power fluctuations as the relays energize and de-engergize)

I used a 4-channel relay unit in a project of mine that has optical isolation of the relay control lines, and can be wired to use separate power supplies for the Arudino and the relay power. When wired with separate power supplies, the relay's control lines just draw CMOS logic levels to control the different relay channels, and get the power for the coils independently from the microcontroller's power.


Passive buzzer works with analogWrite(), but not with digitalWrite(). It also has constant static noise I have a YL-44/MH-FMD passive piezo buzzer hooked up to an ESP8266/NodeMCU.

It's connected like this: Buzzer ---> NodeMCU
- GND ---> G
- VCC ---> 3V
- I/O ---> D2

This code makes a clear beep.

void loop() {
  analogWrite(BUZZER, 255);
  delay(100);
  analogWrite(BUZZER, 0);
}

This code makes a weird low clicking sound, no beep.

void loop() {
  digitalWrite(BUZZER, HIGH);
  delay(100);
  digitalWrite(BUZZER, LOW);
}

I have no idea why the second one doesn't work, as all the tutorials reference that one.

Also, why does the buzzer have a weird constant static noise and gets hot?

Am I doing something wrong in the wiring? I use no resistors, as the tutorials don't show that.

To sound a passive buzzer, use Arduino tone() function. If you set the pin HIGH the piezo surfaces are pulled together (or pulled away). It is what makes one click but nothing more. To make a tone the input must oscillate at right frequency. PWM is one way how to do a beep. Use tone() function to generate tones of desired frequency.

Your analogWrite(255) is PWM at 1/4 of full on, because max analogWrite value on esp8266 is at default 1023. So it makes a nice beep with 255.

If you use a speaker or passive piezo with esp8266 you can expect noise generated by WiFi operations. I set the pin as INPUT after tone() to eliminate the noise.


Why can't my .cpp file have a class of the same name? I made a new Arduino IDE project ABC, and am given ABC.ino. Then I create a XYZ.h and XYZ.cpp.

ABC.ino:

#include "XYZ.h"

void setup() {}
void loop() {}

XYZ.h:

#ifndef XYZ
#define XYZ

#include "Arduino.h"

class XYZ { };

#endif

XYZ.cpp:

#include "Arduino.h"
#include "XYZ.h"

When I try to compile this, I get some error:

In file included from sketch/XYZ.cpp:2:0:
XYZ:8: error: abstract declarator '<anonymous class>' used as declaration
 };
 ^
exit status 1
abstract declarator '<anonymous class>' used as declaration

However, when I rename my class to something other than the file name, like XYZa, the compilation succeeds.

Why can't I have the same name class as the file?

I've done C++ projects (independent of Arduino) via Xcode and nano, and this has never been a problem.

#define XYZ

class XYZ { };

The first line tells the "C preprocessor" (called before C and C++ compilers) to replace XYZ with nothing everywhere it happens, hence after preprocessing, and before compiling, that code becomes:

#define XYZ

class  { };

This is where C++ compiler complains. It has nothing to do with your file name.

Among C and C++ programmers, it is commonly admitted that header files should be protected by macros named after the file name including the extension:

#ifndef XYZ_H
#define XYZ_H

If you use this practice, you won't have this problem anymore.


Cannot disable interrupts I am new to arduino.

Why does this not work the way it's supposed to?
Shouldn't it block all interrupts for 3secs after it received one from digi pin 2?

How would I accomplish this:
Running a method whenever the value on this pin changes, execute it and then listen for more interrupts from that pin?

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

int i = 0;

void loop(){}

void test(){
  noInterrupts();
  Serial.println("Interrupt registered - waiting " + i);
  delay(3000);
  Serial.println("done waiting!" + i);
  i++;
  interrupts();
}

You could achieve that by this simple rewrite:

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

volatile bool changed = false;
int i = 0;

void loop() {
  if (!changed) return;
  Serial.print(F("Interrupt registered - waiting "));
  Serial.println(i);
  delay(3000);
  Serial.print(F("done waiting "));
  Serial.println(i);
  i += 1;
  changed = false;
  clearInterrupt(digitalPinToInterrupt(2));
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void test() {
  changed = true;
  detachInterrupt(digitalPinToInterrupt(2));
}

The interrupt service routine (ISR), test(), is really short and does not call functions that actually need interrupts to work (e.g. delay(), Serial). Please see Nick Gammon's comment below on clearInterrupt(), i.e. EIFR = bit (INTF0);

An alternative rewrite is to use the BlinkWithDelay-pattern and a somewhat more complex state-machine:

volatile bool changed = false;
bool waiting = false;

const unsigned long waitIntervalMillis = 3000UL;
unsigned long waitStartMillis = 0L;

int i = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
}

void loop() {

  // Check for change
  if (!changed) return;

  // Check for change before wait interval
  if (!waiting) {
    Serial.print(F("Interrupt registered - waiting "));
    Serial.println(i);
    waiting = true;
    waitStartMillis = millis();
  }

  // Check if wait interval has expired
  else {
    unsigned long currentMillis = millis();
    if ((currentMillis - waitStartMillis) >= waitIntervalMillis) {
      Serial.print(F("done waiting "));
      Serial.println(i);
      i += 1;
      changed = false;
      waiting = false;
    }
  }
}

void test() {
  changed = true;
}

A third rewrite is possible. Assuming that the pin is connected to a push button, the interrupt handler can be replaced by simply reading the pin with a low frequency (for debouncing).

Cheers!


Sending data over two independently powered arduinos I have multiple arduinos that are each powered by a 12v battery through a 5v regulator.  All arduinos share a common ground.  Can I simply connect the digital output from one arduino into the digital input of another?  I'm worried the (small) voltage differences between each regulator could cause a problem.

It's ok if the distance between the two devices are not too big. (couple meters)

Since the valid logic level (voltage) ranges are pretty wide a small difference won't affect the operation of the devices. Arduino uses TTL (5V) logic so let's see the level diagrams:

If you see the output level ranges (on the right) are more strict than on the input side (on left) so the logic value remains valid even if a small voltage drop or noise occurs on the wire.

Make sure you won't connect two outputs directly since it can damage the microcontrollers. Connecting two inputs are totally safe.

EDIT: If you want to cover longer distances you need to use a balanced line  e.g. differential I/O-s, RS-485 or CAN. These are not default Arduino features so you'll need additional electronic to use them.


Do I have a faulty arduino uno, or have I found an Arduino bug? Lately, we got an old arduino uno donated from a friend and have been trying to get it to work with servos. We have been having very perplexing results. We have tried many different "stock" code and servo combinations with our servos, but here is the behavior:

180 Servos automatically move to right max as soon as power is applied.
Sail Winch servo moves a tiny amount and then stops. If power wire is removed and then reapplied, the servo moves another tiny amount.

The code is very simple. First we call the servo.attach(pin), and confirm the pin. We have also tried doing the manual uSec definition: servo.attach(pin, 600, 2400). In our loop() we have tried servo.write(*value from 0-180*) and servo.writeMicroseconds(*value in PWM range*)

Power is being supplied by a 9v battery, the sensor (yellow) is directly in digital pwm pin, while red (power) is in + and black (ground) is in -.

I'm trying to decide whether I should invest in another arduino system.

servos:

180 servos

Sail Winch servo

If the Arduino "fails" the moment you apply power to a motor, you can bet that it is a power issue.

Or possibly you are exceeding the output rating of the output pin. You should not draw more than 20 mA from each output pin continuously.

  I'm trying to decide whether I should invest in another arduino system.

Power the motor independently of the Arduino. This is normal advice for all but very small motors. Also make sure that you have a suitable driving transistor / MOSFET if the motor draws more than 20 mA. Take into account any surge startup current.

See Driving motors, lights, etc. from an Arduino output pin for some design ideas.

For example:


Arduino Nano (3.0) Use an USB Bluetooth stick I was thinking to build a very small USB Audio Streaming device with aux output for an amp (I know they already exist, but I like the self invention). So I bought an Arduino Nano and a USB Bluetooth device with was originally for a computer. But I thought I might use it on the Arduino. After I removed the housing and soldered four wires onto the USB plug:

https://www.dropbox.com/s/ye5vveb98sfz1zq/IMG_20161030_132648_01.jpg?dl=0

I needed to know how to wire them:

https://www.moddiy.com/product_images/uploaded_images/patillaje-conector-usb.jpg

So I connected:

"1" to 5V+ on arduino
"2" and "3" need to be connected to txd and rxd on the arduino (but I don't know whitch way around)...
I read that I need to have 3.3v on "3" or the "+" wire but I have 5V Output on the digital Pins on the arduino (so I need some resistors, but I'm not familiar with calculating them).
"4" to gnd

Can someone confirm and / or provide some information for me to get this thing running (Bluetooth device enabled and functioning)?

Further steps would be:

coding the arduino to Use the Bluetooth module for audio streaming - preferrably three Channel.
configure the arduino to give the stream to an amp.

I know my knowledge of electronics is not very good and I need some education. If you can provide some good learning websites - feel free to suggest.

Interfacing an Arduino with USB is already VERY hard. USB does not use the same Serial as protocol so don't connect it to Tx and Rx. The only way to interface an Arduino and an USB device is trough a USB shield, which is quite complex already.

Just for you information. USB uses 5V so no voltage divider is needed to reduce it to 3.3V. A voltage divider is pretty much 2 resistors in series where the original voltage goes in one end, the output voltages is between the 2 resistors and the other end is connected to ground. Read more about them here.

Now, communicating with Bluetooth is also complicated, but mix USB + Bluetooth and you get something ALMOST impossible (I hope the ALMOST is clear enough for any hatters). It is possible, but seeing you level of knowlage, simply don't risk having a severe depression trying to fingure it out!

In the end of the day, your plan of using that Bluetooth USB module is just going to be crazy complicated and big.

A more effective solution would be to use a module such as the HC-05 Bluetooth module. It is quite cheap if you get it from sites such as Amazon. Link here for this product on Amazon.com. It is designed with the Arduino in mind thus making programming easier. You project could also be a little smaller, because this module pretty much has the size of your Arduino Nano.

Hope it was helpful!


Arduino IDE does not display examples folder from my custom library I have created a custom library for local usage. I call is ABC_node for ESP32 and the structure is as follows:

.
|-- examples
|   |-- bnoCalibStorage
|   |   `-- bnoCalibStorage.ino
|   |-- influxHTTP_write
|   |   `-- influxHTTP_write.ino
|   |-- influxPing
|   |   `-- influxPing.ino
|   |-- influxUDP_write
|   |   `-- influxUDP_write.ino
|   `-- rtcTimestamp
|       `-- rtcTimestamp.ino
|-- keywords.txt
|-- library.properties
|-- README.md
|-- ABC_Node.cpp
`-- ABC_Node.h

I tried following the Adafruit GitHub Repository structure where each example is placed inside a folder named after the sketch.

I am hosting this repository on a private GitLab Server. I used git tag v1.0.0 to create a tag and from GitLab I could download the .zip file for the stable v1.0.0 library.

I manually extracted the files to my <user>\Documents\Arduino\libraries folder and renamed the folder to ABC_Node (since my gitlab repo is named something else)

I restarted my IDE but I could not find the library ABC_Node in

Sketch\Include Library\

library.properties

name=ABC_Node
version=1.0.0
author=Shan Desai
maintainer=Shan Desai
sentence=Firmware to create InfluxDB measurements and send them via HTTP/UDP to Core
paragraph=ABC_Node provides `String` based InfluxDB measurements which can then be sent via HTTP/UDP to a central InfluxDB instance.
category=Data Processing, DAQ
architecture=ESP32
repository=https://[gitlab-address]/node-repo.git

I followed the Libraries Guide from Arduino on local Installation

System

Windows 10

Arduino IDE 1.8.5

Your library.properties is lacking a line.  Emulating your library with blank files and copying in your library.properties content, and running on Linux from the command line, it reports to me:

Invalid library found in /home/matt/Arduino/libraries/ABC_Node: Missing 'url' from library

So you lack the line:

url=https://whatever.website.you.want.to/point.to

(Or use something like http://example.com if you don't want one...)

I put that line in, and magically the library appears in the list.


Why is the GSM shield so expensive? I've been doing some Googling for GSM shields and their prices and frankly I don't understand why they are so expensive on average.

The official one sold by Arduino is 71 euros for me (I live in Europe), and third party ones have similar prices.

A cheap dumb-phone is usually 30 euros and those phones have become really impressive these days, they have even a camera. When they are locked with the carrier the price can go as low as 20 euros. How is it even possible that a single part of what is supposed to make up a phone is more expensive than the phone itself? :(

Thanks in advance!

If you are ready to wait a month for delivery and also giving up flexibility by restricting yourself to just sending and receiving SMS, then you can go as low as €2 for a DIY kit on AliExpress.

By adding more money, you also get more features. Just sarch for "gsm arduino" or "SIM800", "SIM900".


How to set sampling rate for digital pin input? I have an ADC that have sampling rate up to 40 MSPS, but i use 8 MHz clock so it will be 8 MSPS. The board used is arduino nano. The problem is i have to sampling it just 2 MHz (because the capacity of array variable in arduino Nano, which is around 10.000 elements in array variable). I know that using direct port reading will increase the speed of the digital read, but how can i set the direct port reading to just read every 0.5 us? Micros function cannot do the job of course

Thank you

You need:

A timer
A board that is capable of running fast enough to do what you want.

The Nano fits the first criteria, but not the second.

At 16MHz you get a clock period of 63ns.  That means you get a mere 8 clock ticks (actually gives you 504ns) per interruption from the timer. That's at most 8 assembly instructions that can be executed within that time.

Since an interrupt service routine's preamble is longer than 7 instructions you can see there would be a slight problem there.  No time for actually reading a digital IO port - and if you are using a serial protocol to communicate with your ADC you can multiply the reading time by the double the number of bits you need to read. That's a long time compared to 500ns.

So no. Think again. Use a more suitable board. Maybe an ARM based board (like the Teensy 3.x) would be a better fit.


SIM900 + GPS Module making http rest calls I am wondering if its possible to program a board that is developed using SIM900 and GPS module to make http rest calls.

I found this library. My question is, will I need a microcontroller for this ?

My question is, will I need a microcontroller for this ?

Yes. There are certain things that you need a "man in the middle" to control. Without a microcontroller, how will you tell it what site to visit? How often to send the HTTP request? How to format the HTTP request? Is there any other thing you need this to do?

People often hope that they can hook up two complex devices that are almost setup to be slaves (like shields, sensors, and outputs) to a microprocessor. Unless the two were specifically designed to work together (or they use a standard, very specific protocol), your chances of building this without a microchip is like trying to build a skyscraper with popsicle sticks. It's possible, but there are cheaper and much easier/more efficient ways to doing that.

Well, they're both SPI/I2C/UART/USB/Serial! Why not? Well, although we're all humans and we use verbal communication as a protocol, do we all understand each other? Not really... For those protocols, they're designed to have a "master" and a "slave." A master would be powerful and have control over all the slaves. Hooking a GSM and GPS shield together is like hooking two slave devices together. It's not going to work out (unless you're aiming for blue smoke...)

tl;dr: you trying to mix two things that don't mix. Buy an Arduino Nano clone for $8 and have your circuit actually work.


Adafruit RTC begin() not returning false I am programming my arduino with the capability to keep time with the DS3231 from Adafruit. I do not have the module yet, but am trying to figure out the rest of the build without it.

However, it seems like the way to determine RTC is working does not work, as it returns true, even without the module.

Example code from the Adafruit RTC library for using this module:

// Date and time functions using a DS3231 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(9600);

  delay(3000); // wait for console opening

  if (! rtc.begin()) { // part that fails. begin() returns true when should return false
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}
....

If you look at the library source code it will be clear why begin() returns true.

From https://github.com/adafruit/RTClib/blob/1.2.0/RTClib.cpp#L434-L437:

boolean RTC_DS3231::begin(void) {
  Wire.begin();
  return true;
}

I suppose they plan to eventually make the return value of begin() mean something but for now it does not.


What is corrrect the way to find roll, pitch, yaw? I have an MPU9250. I have calculated accelerometer, gyroscope, magnetometer. But I want to know how to caclulate roll yaw pitch. I have searched on Google. I found many answer

roll  =  (atan2(-Accel_Y, Accel_Z)*180.0)/M_PI;
pitch =  (atan2(Accel_X sqrt(Accel_Y*Accel_Y + Accel_Y*Accel_Y))*180.0)/M_PI;

source: https://theccontinuum.com/2012/09/24/arduino-imu-pitch-roll-from-accelerometer/

   accelerationX = (signed int)(((signed int)rawData_X) * 3.9);
   accelerationY = (signed int)(((signed int)rawData_Y) * 3.9);
   accelerationZ = (signed int)(((signed int)rawData_Z) * 3.9);
   pitch = 180 * atan (accelerationX/sqrt(accelerationY*accelerationY + accelerationZ*accelerationZ))/M_PI;
   roll = 180 * atan (accelerationY/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;
   yaw = 180 * atan (accelerationZ/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;

source:  https://engineering.stackexchange.com/questions/3348/calculating-pitch-yaw-and-roll-from-mag-acc-and-gyro-data

  Accroll = atan2( accy / (accy^2 + accz^2) )
  Accpitch = atan2( accx / (accx^2 + accz^2) )

source: http://franciscoraulortega.com/pubs/Algo3DFusionsMems.pdf

 Accroll = atan2(accy, accz)
 Accpitch = atan2( -accx, sqrt(accy^2 + accz^2) )

source:https://www.nxp.com/docs/en/application-note/AN3461.pdf

What is the correct way to find roll yaw pitch?

For a stationary accelerometer sensing the acceleration of gravity, I see "dead zones" when the Pitch, Yaw or Roll axes are parallel or close to parallel to the gravity vector.

Likely this is why accelerometers are used in conjunction with gyroscopes.

Refer to this NXP (aka Motorola, Freescale & Qualcomm) document for an in depth discussion regarding the necessary math.  Note the section regarding "Regions of Instability".

Also, refer to this class and this class from rutgers.edu which work students through a project using an Arduino and an accelerometer in the 1st class then adds a gyroscope in the 2nd class to improve the response.

(Added Later)

The rutgers.edu links don't appear to work anymore and this link has been suggested as an alternative.


How to change the default name of ESP8266-12E module Is there any way to change the default name (ESP_xxxxx) that the module generates?

This line of code should hopefully do a difference.

wifi_station_set_hostname(myHostname);

For more information :

https://www.reddit.com/r/esp8266/comments/3zl3pi/change_esp8266_network_name/


Arduino IDE Display Code Line Numbers In the Arduino IDE: How can I get the line numbers shown in a sidebar of the editor?

It is hard to find which line my errors are referring to without them...

I am using Arduino IDE on a form of Windows.

Go to File > Preferences. Under the Settings tab, click the checkbox for Display line numbers.

Keep in mind that this option is available in the latest version of the Arduino Integrated Development Environment (v1.6.6). In case you are using GNU/Linux distribution is recomended to use the one that is NOT in the distribution's repositories but the one that is offered in https://www.arduino.cc/en/Main/Software

If you are using a Linux OS this solution may not work. Look at the 'preferences.txt' where you can edit your preferences in a file without a GUI.It will display all possible options available for your current version of Arduino IDE on your OS. It is usually in the '.arduino' folder which may be in your 'home' folder.


ESP8266 Programming using ESP-01 to USB converter I am new to ESP8266. To ease out the task of programming esp8266, I bought this:  ESP-01 ESP8266 Programmer CH340G Chip USB WiFi Wireless UART GPIO0 Adapter.

Configured Arduino Interface to run AT commands in the serial monitor.
I flashed ESP8266 with the basic blink LED example. It worked fine for some time and later on gave this error.

warning: espcomm_sync failed

When i tried to flash another program on to ESP8266, I am getting the following error.

Sketch uses 221,995 bytes (51%) of program storage space. Maximum is 434,160 bytes.
Global variables use 31,568 bytes (38%) of dynamic memory, leaving 50,352 bytes for local variables. Maximum is 81,920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I could only find one article regarding this adapter.
There he made a custom bridge soldering GPIO 0 to GND for ESP8266 Flashing.

So should i make a removable bridge for the same, to upload a new program.
Is there any other way to simplify this task?

Finally I made a breadboard connection joining ESP8266's GPIO 0 and GND to Programmer's GND for flashing the chip

For more info

Additional Reference:
Programming ESP8266


Marlin g-codes applicable for a Melzi Sanguino board How/where do I find a complete listing of "acceptable" Marlin g-codes applicable to a Melzi Sanguino board on a 3D printer (Zonestar). It appears that not all printer boards accept all available Marlin codes.

Then I was thinking incorrectly. I had assumed that not all g-codes (from a Marlin build) were, in fact, “implemented” the same way on all boards, and some would not even be recognized or interpreted. But I still don’t understand why that is.

As already written in the comments the software defines what G-Codes are taken by a (printer) boardBUT Even if the software has the same name (eg Marlin) it might behave different on different boards because of:

different release versions for different hardware
different release repositories being ahead or behind the master repo
hardware specific features a G-code triggers (most unlikely)

The clever way is to go from features I need to software supporting thosefeatures to boards supported AND useable for my hardware to controll (3d-printer/CNC-router/laser-cutter aso)
  -


Any problems taking arduino(esque) devices through airport security? I'm flying out for vacation, and I want to take some of my half-done arduino projects with me to work on.  I'm concerned that aiprort security might mistake my devices for something sinister or at bare minimum 'suspicious' and be confiscated.

Has anyone ever had any negative experiences taking arduino-esque wiring projects through airport security?

It will depend on your particular country of course. Check the rules on cabin baggage.

In Australia, Arduino boards should pose no problem. It is best to not take any batteries or tools with edges (screwdrivers) or heavy tools (wrenches). In case they do want to have a look, place the boards at the top of your bag for easy access.

I have traveled to Europe from Australia with half a suitcase full of large PCBs with no problem. The only time my bag was opened was when I was carrying a tea pot stand, which was in the shape of a tea pot. Apparently it looked like a gun.


Connecting TFT Display MI0283QT-9A to ESP32 I have purchased a MI0283QT-9A TFT display (https://download.mikroe.com/documents/add-on-boards/other/display/tft-proto/tft-proto-manual-v200.pdf) which is
driven by the ILI9341 display controller.

I've managed to find the following board specification: http://pub.ucpros.com/download/tft_320_240_mi0283qt_9a_v1_3_spec.pdf

First of all, the pins are named differently from all the examples I can find for connecting it to my ESP32 microcontroller. For example, the TFT specs describe:

33 SDO Serial Output Signal
34 SDI Serial Input Signal
35 RD Read execution control pin
36 WRX(D/CX) Write execution control pin ; Serial Register select s Signal
37 D/CX(SCL) Register select signal; Serial Interface Clock
38 CSX Chip Select Signal
39 TE Tearing effect out pin synchronize MPU to frame writng

But this Adafruit ILI9341 example (https://github.com/adafruit/Adafruit_ILI9341/blob/master/examples/graphicstest/graphicstest.ino) talks about CS, DC, MOSI, CLK, RST, and MISO.

I think these map as follows, can anyone confirm that?

ESP32 = TFT
--------------
DC    = RS
CLK   = WR, although maybe it should connect to DC???
CS    = CSX
MOSI  = SDI
RST   = RST
MISO  = SDO

I'm really unsure about the first two!

Second, in the PDF it refers to note 1 on page 11:

So as far as I can tell, I need to set the voltage high/low on the four IM* pins, depending upon the interface I want to use. So the second question is which interface does the Adafruit ILI9341 library use?

It sounds like you want a 4-wire 8-bit serial SPI compatible interface.  To get that you have to set the IMx pins to the right state to enable that interface.  That means:

IM0 = LOW
IM1 = HIGH
IM2 = HIGH
IM3 = HIGH

You can hard-wire those to GND for LOW and +3.3V for HIGH.

That will then configure it to work in the right mode for you, where it gives you access to the following pins:

| Display  | ESP32   | Function                    |
|----------|---------|-----------------------------|
| SCL (RS) | SCK     | Serial clock                |
| SDI      | MOSI    | Serial data Master -> Slave |
| SDO      | MISO    | Serial data Slave -> Master |
| D/CX (WR)| DC      | Data / Command register sel |
| CSX      | CS      | Chip Select (Active Low)    |
| RST      | RST     | Reset                       |


Arduino Mega 2560 RFID Serial Communication I have an RFID reader: http://img.tradeindia.com/fp/1/641/264.jpg

Something like above along with ITEAD TFT shield & GSM Modem. The RFID reader has an RS-232 port as well as GND, TX and 5V pins. I am using an Arduino Mega 2560 board. I have connected the TX, GND of RFID reader to RX3 pin 15 / GND (pin) of Arduino. Note I am supplying 12 V to RFID via an adapter.

Note the ITEAD TFT shield consumes the TX0, RX0 pins—so I cannot make use of the RX0 and TX0 pins. Though I have not written the code for GSM modem.

Now while running the program below, I am getting junk output both in my TFT display as well as the serial monitor:

#define __AVR__
#include <UTFT.h>

// Declare which fonts we will be using
extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];
UTFT myGLCD(ITDB24,59,58,57,56);
String myString = "";

void setup() {
   Serial3.begin(9600);
   myGLCD.InitLCD();
   myGLCD.clrScr();
}

void loop() {
  myGLCD.setFont(BigFont);
  if (Serial3.available()) {
    int inByte = Serial3.read();
     myString += String(inByte);
    }
    if(myString.length() == 10)
      myGLCD.print(myString, CENTER, 0);
}

TFT Screen output:

1310494848

Serial Monitor Output: non printable junk character.

The value is incorrect, I am pretty sure, what am I doing wrong?

I found that the ITEAD shield is sending or rather using RX0/TX0 pins very frequently—some data is going through.

BTW what is the functionality of http://arduino.cc/en/Tutorial/SoftwareSerialExample?

How can I use 3 different Serial I/Os individually at the same time without disturbing any other I/O?

First of all, try testing 1 functionality at a time to isolate the issue.
Now you do not know if the LCD is not working correctly, or if the serial communication with the RFID module is not working correctly. Connect it to a computer and test both independently.

When getting gibberish from a serial line, usually it means the baudrate doesn't match. Both devices have to send the same amount of bits per seconds in order to communicate with each other.

This is the Arduino example to test 2 serial lines (for Arduino Mega) at the same time: http://arduino.cc/en/Tutorial/MultiSerialMega


Using ps2 mouse (PAW3402 / PAW3412) as a distance sensor for arduino I am working on a project where I need to calculate distance traveled by a robot. The mouse is connected to the arduino uno processor and I received some sample code from the arduino website to get started.

The problem is that the mouse gives difference distances depending on how fast or slow the it moves. (The same way you can move your pc mouse from side to side, fast and slow, and watch it cover different distances across the screen). Is there anyway to get get around this mouse setting? If not,  is there a more accurate sensor that can be used to accomplish the task? I'm having a hard time finding one.

Here is a link to the datasheet: http://www.alldatasheet.com/datasheet-pdf/pdf/333273/PIXART/PAW3402.html

Assuming under normal conditions a relative pointing device such as a optical mouse always reports relative position changes with out regard to speed.  If true, then consider that the speed of the robot is faster than the mouse can process.  Also, consider that the mouse's optics is out of focus with respect to the surface it is supposedly taking its positioning cues from.  Lastly, consider the surface may not be ideal for an optical mouse.  Attempt the same experiment using a sheet of paper or a "not-shiny" wood surface.

All surfaces have to be flat.  For example, a ceramic tile floor will likely not work as the surface will come in and out of focus during travel.  Make sure the elevation of the robot with respect to the surface is constant.  Inspect the wheels to make sure they are perfectly round and rotating around their center point.

Check and make sure you are not suffering from a integer calculation or type size problem.  Examine your code and make sure you are handling all cases including the expected maximum and minimum values properly.  And that your variables are large enough to handle these expected values.


Problems with green TWI (I2C) port on Arduino Braccio Shield Summary: The green TWI/I2C port on my Braccio shield I2C port hasn't worked for me so far. Looking for advice or information please.
Detail:
I'm using the Arduino (Tinkerkit) Braccio robot arm for self education. It comes with a Uno based Braccio Shield. Tinkerkit no longer seems to be in business and documentation is a bit scarce. The shield uses KF2510 style connectors for servos (orange), inputs (white), serial (yellow) and importantly for my question a TWI/I2C port (green).

The green four pin TWI/I2C connector provides GND, +5V, SDA (A4), SCL (A5). However the SDA and SCL connections are reported to not be direct, but that "a very tiny chip (located next to the I4 connector) buffers between the green connector and the Arduino pins SDA and SCL" . A photo of the chip described is below.

Contrary to the reports of a "buffer" studying the schematic shows a level shifter PCA9306TI and two sets of 10K pullup resistors (R7,R8 and R11,R12) on the bus on both sides of the chip. VREF2 on the outboard side of the chip has a R9 220K resistor to +5V.

The other side of my I2C connection was an Arduino Pro-mini 5V. I was never able to get it working using the green port described, but it works fine directly hooked into SCL and SDA bypassing the level shifter.
My questions (sorry for the long lead up) are:

Has the green TWI port been level shifted to expect ~3V? (Only really came to this conclusion writing this all up clearly).
If I want to change the green TWI port to 5V I2C can I replace R9 220K with a zero ohm jumper?
The 10K pullups (R7,R8 and R11,R12) seem larger than anticipated (I had anticipated about 4.7K for 5v or about 2.4 for 3V)? Can they be removed and left open if I have a single set of pullups elsewhere on the bus? Or better suggestions?

Thanks!
Update 2021/01/30
Well my I2C debugging skills are improving researching this! As a test bed I set up a clean working I2C bus with two MCU's running the Arduino Example Master/Writer Slave/Receiver sketches by Nicholas Zambetti. I tested the I2C signal on the oscilloscope to make sure it was clean. All good. To that test bed I connected the Braccio shield (5V, GND, SCL, SDA). Connecting the Braccio shield changes the I2C signal in interesting ways, with partial strength (runt) pulses, and round shoulder slow rises. Connecting via the green TWI port seems to accentuate the runt pulse aspect. Also interesting the oscillscope was still able to decode the signal. Still working on figuring this out.
Pic 1. First test - SCA and SCL connected via pin headers in top left of shield picture above.

Pic 2. Second test - SCA and SCL connected via green TWI port

Pic 3. Clean Signal (no Braccio Shield connection)

I fear we have a colloring issue. Your green is my blue ;-).
I have looked into the data sheet of the level shifter IC and TI only describes scenarios with a higher voltage on the right side and a lower voltage on the left side. Also the allowed voltage translations do not contain 5V to 5V. So I would say in equal voltage scenario the Level shifter may not work.
Answers

Q1: The TWI port is always used with 5V (not ~3V). The Arduino that is supposed to use the shield might be a 3.6V version (like a DUE or M0). Perhaps the TWI port is only intended for this use case: A low voltage arduino with a 5V device. I admit: This should be noted in the documentation. So perhaps Braccio shields work outside the specification and may works under normal circumstances. But meanwhile I begin to understand why they are out of busines ;-).

Supplement: the SCL and SCL signals are routed to two pairs of header pins as they are connected to different pins on different Arduinos. On a UNO you can not use A4 and A5 for analog as they are used for I2C for example. Do you use A4 A5 in any way? Or did you connect the second I2C pin pair in the power header when you had used the TWI connector? (rhetoric question ;-) of cause I will change the answer if you give me more information ;-) )

Q2: The 220k resistor is necessary as it limits the current through the chip if VRef1 is lower than VRef2. Removing it with 0 Ohms would be a bad idea. As long as 5V is used on both sides, nothing would happen. But if Vref1 is 3.6Volts, you would waste energy and perhaps the chip would take part at a grill fest.

Q3: Most I2C devices breakout boards already use their own pullup resistors. So lowering the pullups is not the best idea. -> too high current with LOW signals as the devices pull ups and the braccio pull ups are set in parallel.
-- There is a chance, that the resistors are too large for devices that don't use their own pull ups, but at a 100kHz bus speed I don't think, this could cause an issue.

BTW: You do not need to exchange the pull ups, if you insist to try out different values. Just use parallel resistors to lower the resistance (10K || 10K -> 5K) [|| means connected in parallel] (R || Rp -> (R*Rp) / (R+Rp))


Sending AT commands to Reyax RYLR890 LoRa modules via additional serial port not working I am setting up a LoRa module (transmitter) with nodemcu (ESP8266). The module (Reyax RYLR896) accepts AT commands over serial interface. I created an additional serial port using pins D7 and D8 on the nodemcu using SoftwareSerial.h in Arduino IDE to try and set up the transmitter following this example.
I coded up the sketch below to read an AT command from native serial interface, pass it on to the LoRa module via the additional serial port, read the response and print it in serial monitor. The LoRa module should respond with "+OK" to an AT command like "AT" or with data for a command like "AT+ADDRESS". However, I get no response. So far, I have tried:

Experimenting with different baud rates (9600 and 115200)
Hard-coding AT command(s)
Using read/write and readString/print.

The string sent via serial monitor is read correctly but the second if block is never entered.
#include <SoftwareSerial.h>

#define Rx D7
#define Tx D8

SoftwareSerial LoRaSerial(Rx, Tx);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) {
    ; // Wait until native serial interface is ready.
  }
  Serial.println("Native serial interface ready!");

  LoRaSerial.begin(9600); // Also tried 115200
  LoRaSerial.println("LoRa serial interface ready!");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()) {
    String serial_command = Serial.readString();
    Serial.print(serial_command);
    LoRaSerial.print("AT\r\n"); // hard-coded to test
  }
  delay(200);
  if (LoRaSerial.available()) {
    String LoRa_response = LoRaSerial.readString();
    Serial.print("Done!");
    Serial.print(LoRa_response);
  }
}

The module is brand new and I have tried with two different ones. Any help is appreciated!
Connections are as follows:
Node
mcu <> RYLR896

GND <> GND
D7 (Rx) <> TX
D8 (Tx) <> RX
3V3 <> VDD

The RST on RYLR896 is not wired.

In order to test AT commands for Reyax Rylr 896 module, you need to connect rxd of lora module with rx(D7) of nodemcu and txd of lora module with tx(D8) of nodemcu.


Low Power Pin Change Detection (ATtiny) I want to use an ATtiny as data logger for the opening and closing of a door/window. For that I am using a reed-switch. Since I want to run it from a 3V coin battery, long term power consumption is crucial. Therefore the ATtiny (currently 13A) is in system down mode most time and is only listening to Pin-Change-Interrupts. Depending on the state of the reed-switch the power consumption differs in an order of magnitude.

switch open:    0.1µA
switch closed: 74.5µA
my Multimeter has a tolerance of ±0.1µA

This is a difference of an order of magnitude. But it is plausible as the datasheet of the ATtiny13A states in chapter 10 that a GPIO pin can only be pulled up and is otherwise dangling. The pull-up resistor is somewhere between 20k and 50k as stated in chapter 18.2.

So in my setup the pin is pulled up and the reed-switch is grounded.

How can I reduce the power consumption in the case where the switch is closed?

Alternatively: Can I somehow revert the state of the switch, as windows and doors are closed most of the time?

The MCU is running with the 128kHz internal Clock with CKDIV8 so practically running @ 16kHz.

The minimum viable code:

/*
  3V0               SW0
   |     |     |     |
 -----------------------
 |                     |
 |                     |
 |      ATtiny13A      |
 |                     |
 |                     |
 -----------------------
   |     |     |     |
               TX   GND
 */

#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <iso646.h>
#include <stdbool.h>
#include <util/delay.h>

#define BIT_SET( PORT, BIT_FIELD ) PORT |=  BIT_FIELD
#define BIT_CLR( PORT, BIT_FIELD ) PORT &= ~BIT_FIELD

#define TX_PIN          PB4
#define SW0_PIN         PB0
#define INT0_MASK       PCINT0

// MARK: - POWER

static void power_down(void) {
    BIT_SET(GIFR, _BV(PCIF));       // Clear interrupt signal
    BIT_SET(GIMSK, _BV(PCIE));      // Pin Change Interrupt Enabled
    sleep_enable();
    sleep_cpu();                    // Enter sleep mode
    sleep_disable();
    BIT_CLR(GIMSK, _BV(PCIE));      // Pin Change Interrupt Disabled
}

ISR(PCINT0_vect) {}

// MARK: - Setup

static void setup(void) {
    cli();

    // Set up output pins
    DDRB = _BV(TX_PIN);
    BIT_CLR(PORTB, _BV(TX_PIN));

    BIT_SET(PORTB, _BV(SW0_PIN));        // pull up interrupt pins
    BIT_SET(PCMSK, _BV(INT0_MASK));   // set PCINT0 to trigger interrupt
    BIT_SET(GIFR, _BV(PCIF));       // Clear interrupt signal
    BIT_SET(GIMSK, _BV(PCIE));      // Pin Change Interrupt Enabled
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);

    sei();
}

static void loop() {
    BIT_SET(PORTB, _BV(TX_PIN));
    _delay_ms(1);
    BIT_CLR(PORTB, _BV(TX_PIN));

    power_down();
}

int main(void) {
    setup();

    while (true) {
        loop();
    }
}

The additional 80uA drain is almost certainly coming from the pull-up resistor being shunted to ground though the reed switch.

https://www.wolframalpha.com/input/?i=(3+volts)+%2F(50k+ohm)+in+uA

As suggested by @Edgar Bonet, one way to greatly reduce this drain is to disable the pull-up immediately when you wake from the pin going low. At this point it is possible for the pin to stay low even if the switch is no longer grounding the pin, so you need to periodically check it using a watchdog.

Wake from pin going low pin change interrupt
Disable pull-up (stops current flowing though resistor)
Do your logging operation.
Enable a watchdog wake up
Go back to sleep.

At this point you can wake either from (1) a watchdog or (2) pin change if the pin goes high again.

If you wake from a pin change...

re-enable the pull-up
disable the watchdog
go back to sleep

If you wake from the watchdog...

re-enable the pull-up.
if the pin is high now, disable the watchdog and go back to sleep.
if the pin is low, disable the pull-up and leave the watchdog running and go back to sleep.

The watchdog timer on this part should only use single digits of uA while running, and it should only need to be running while the switch is grounding the pin. You can set the watchdog timeout to be quite long- on the order of seconds even, to reduce the frequency you  wake to check with the pull-up (and therefore the net power used, at the cost of latency for detecting pin changes). The main downside to this strategy is that you can miss activations that happen inbetween your watchdog wake-ups, so for example if the pin goes low and then you set the watchdog for 8 seconds, and then the pin changes high and then low again during the next 8 seconds, it is possible (but not assured) that you could miss the second event, so set the watchdog timeout to be short enough that you will not miss consecutive events that you care about (you might not care if the door is opened twice in the same minute anyway).

Also, as noted by the famous @nick gammon, you might be able to get lower than 5uA when sleeping without the watchdog. Check to make sure you are disabling everything in the power register and that all unused pins are in input mode (these will be disabled when sleeping as long as there is not a pin change interrupt on them).  There are lots of googleable articles on minimizing ATTINY power during sleep.

You also mentioned that your dominant case is that the switch is closed rather than opened. Since this is the higher-power case with the current switch consider using a normally open switch rather than normally closed one if possible.

Finally, if you just want simplicity and you only care about events of a minimum duration (saym then door much be open for at least 1/2 second to be noticed), then you can skip the pin change interrupt completely and only use an always-running watchdog to wake periodically and very quickly enable the pull-up and check for the desired pin state, and then disable the pull-up and go back to sleep. You should be able to do this in less than a dozen cycles so the net power usage should be almost as low as the watchdog timer drain by itself.


Arduino Serial.write sending more than 64 bytes I am using an Arduino Due to collect a large amount of data from an encoder (about 1kb). Afterwards I need to send the collected data to a C# application I wrote over the serial port. I serialized my tx data into a byte buffer and simply used this code to transmit:

void sendEncoderData()
{
  byte buffer[1024];

  /*** some code that populates buffer ***/

  int bytesToSend = 1024;
  Serial.write(buffer, bytesToSend);
}

When I run the code, nothing seems to get received by the C# application. In fact, I never see the Tx LED light up. However, if I change bytesToSend to a value smaller than 64 bytes everything works. Is this a limitation of Serial.write() or is it something else? What are ways I can work around this limitation?

More information： sendEncoderData() is called by an interrupt service routine. However prior to the call, I made sure to 'detachInterrupt()` on all pins including the pin associated with said ISR.

Here's the problem:

  sendEncoderData() is called by an interrupt service routine.

There is an internal 64 byte serial transmit buffer that is filled by Serial.write().  That buffer is empted by sending the data a byte at a time using an interrupt.

If you are in an interrupt (at a higher priority than the serial interrupt) then the interrupt that sends the data can never happen, so the buffer just fills up and stops when it gets to 64 bytes.  It will hang until there is room for more bytes in the buffer, and that will never happen because you're not allowing the data to be sent.

The answer (as I and others have said many times in the past): Never use Serial in an interrupt.


ESP01 connected to Arduino can't read from UART while connected from external power source I have an Arduino Uno connected to a NodeMCU ESP01 module, communicating via serial pins. The NodeMCU is powered from the Arduino's 3.3V pin. My idea is that the ESP01 receives MQTT messages, sends them to the Arduino via serial and wait for the Arduino to reply and then publish MQTT messages back.

If I power the Arduino from my computer's USB, everything works fine.

If I use an external power supply 12V/1A, the ESP01 can publish and receive "standard" MQTT messages (meaning, it does not send messages to the Arduino and does not expect a reply). It just receives and directly replies (no Arduino involved).

The problem occurs if the ESP needs to query the Arduino for a result.

The Arduino is able to read and write (I see the correct text in the console) to the serial port, but the NodeMCU ESP01 has problems publishing MQTT messages. Sometimes it does not publish anything (the ESP probably is unable to read what Arduino sends over serial), sometimes it publishes destroyed characters (random text).

It looks like the current needed by the ESP module is not high enough, but it does not make sense for me, since the external power supply should be able to provide more current than USB. Any ideas?

This is my schematic:

Code:

In my ESP01 I have the following MQTT onMessage listener, If the topic is a query for the Arduino (topic is validated by the handleQuery function), then the topic is sent by UART to the Arduino, which listens for specific strings in the loop function. When the Arduino receives a string, it does some logic and writes a reply back to the ESP via UART (Serial.print()).

After the ESP sends a message to the Arduino, it sets listeners for strings, that end with character %. If the reply from the Arduino is received, then it publishes an MQTT message with the result.

function onMessage(client, topic, message)
    if handleQuery(topic.."+"..message) then
        uart.write(0,topic.."+"..message)

        uart.on("data","%", function(data)
            if data=="quit%" then
                uart.on("data") -- unregister event
            end

            if data ~= "quit%" then
                client:publish(topic.."/response","REPLY:"..data,0,0)
            end
        end,0)
    else
        client:publish(topic.."/response","REPLY: Invalid query",0,0)
    end
end

The reply from the Arduino has the following message format:

 REPLY:<value>%
 quit%

This solution works if the Arduino is connected to my desktop computer's USB. It does not work if it is powered from an external power supply. It seems like the ESP is not able to read what the Arduino wrote to UART with Serial.println() if powered from an external power source.

I have no idea why, because power supply should be able to deliver more current.

Edit:

I use the following Arduino clone: eBay link

I tried to connect the ESP01 to the Arduino's 5V output with a voltage regulator (5V should deliver more current), and again, if the USB is connected, the ESP reads UART messages with no problem. If the Arduino is powered from an external power source, the ESP reads damaged characters. The only difference is that those damaged characters seems to be always the same. So perhaps some coding problems(?) or something like that.

So far it looks like a low current value is not a problem.

Edit 2

I removed from my code print() statement from the ESP/LUA code that I used for "debbuging". It printed to serial some messages for me. It seems that it cleaned traffic on Serial line a little bit.

Now I get most of the time correct characters, but the first character is missing, so instead of:

LOW% I get OW%
HIGH% I get IGH%
29.53% I get 9.53%

And from time to time I get String =]�quit%.

Perhaps some input buffer has a problem(?).

Can I just check when you plug your 3.3V ESP into a 12V power supply it stops working?  Is there a burning smell when you do this?  Are you using anything to drop the voltage to 3.3V?

You also say you are connecting the ESP to the Arduino's 5V supply.  Normally that's not a good idea either.

Also have you tied the ground of the Arduino to the ESP/12V PSU?  If the two devices don't share a common ground then they won't agree what 0V and so won't be able to talk to each other over serial.  Just run a wire from the Gnd on the Arduino to the Gnd on the ESP and they will jump into life.


Arduino button-controlled LED with AVR Assembly I am trying to make a simple button-controlled LED, but I cannot seem to get any input from the button that would change the state of the LED. In other words, the program keeps branching to lighton, keeping the LED always on, regardless of the button state. I am using an Elegoo Uno R3.

Schematic:

Code:

.text
.global setup
.global loop

setup:
  ser r16
  sts DDRB, r16
  ldi r16, 0b00000000
  sts DDRD, r16
  ldi r16, 0b00100000
  sts PORTB, r16
  clr r16
  sts PORTD, r16

loop:
  lds r20, PORTD
  cpi r20, 0x00 ; PORTD always equal to 0x00 ?
  breq lighton
  clr r16
  sts PORTB, r16
  rjmp loop
lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  rjmp loop

Edit: I also implemented the method in https://stackoverflow.com/questions/39361410/creating-a-toggle-switch-in-avr-assembly to create a short delay with r18 instead of del, but it didn't help; see revised loop method below:

loop:
  cpi r18, 0
  brne dec_jmp
  lds r20, PORTD
  cpi r20, 0x00 ; PORTD always equal to 0x00 ?
  breq lighton
  clr r16
  sts PORTB, r16
  ldi r18, 250
  rjmp loop
lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  ldi r18, 250
  rjmp loop

dec_jmp:
  dec r18
  rjmp loop

With delay:

lighton:
  ldi r16, 0b00100000
  sts PORTB, r16
  call delay150
  ldi r16, 0b00000000
  sts PORTB, r16
  call delay150
  rjmp loop

Fixed it with the below code for the loop:

loop:
  sbic PIND, 2
  call nopressb
  ; button pressed
  ldi r16, 0b00100000
  out PORTB, r16
  rjmp loop
nopressb:
  ldi r16, 0b00000000
  out PORTB, r16
  rjmp loop


Reliably measuring the energy consumption of arduino running sketch I would like to know if there is a programmatic way of measuring the energy consumption of a sketch or at least if this is possible via external devices.

My aim is to compare the energy consumption of two devices, connected to usb, running slightly modified versions of the same sketch e.g., one using crypto and one without using crypto.

programmatic way of measuring t

Not sure what you meant by that but typically you can use a high side current sense amplifier to get a measurement of the current. Then adv a known voltage to get vcc. That known voltage could be the internal reference, if available

In some cases a resistor on vcc can be used to measure current, together with two dividers.


Timer Interrupt Collision I am working with a MEGA2560 trying to implement velocity ramps for three steppers at the same time. The goal is to move to different positions applying accelerations and decelerations while finishing all of them at the same time.
In order to do so, from the distances to move of each of the motors, I calculate the amount of steps to do and the velocities for each of those steps in order to ensure that all the motors finish at the same time. For so, I use timers 3, 4 and 5 in compare mode. This way, at each interruption, I make the motors do one step and, after that, I set the new compare value for the timer in order to reach the new velocity to move at.
My problem is that, at some point, my interruptions crash and one of the motors stops working. This only happens under one condition: when motor 1 has to do 18 steps and motor 2, 34. In this case, both motors 1 and 3 finish but motor 2 gets stuck and does not move any more. Although, if its motor 1 who has to do 34 steps and motor 2, 18, everything works. Motor 1 is related to timer 3 and motor 2 to timer 4. This makes me think this must be related to the priorities of the interruptions.
In the following code you can see my interruptions:
ISR(TIMER3_COMPA_vect) {
    m1_step();
    m1_steps_done++;
    m1_configure_vel();
}
ISR(TIMER4_COMPA_vect) {
    m2_step();
    m2_steps_done++;
    m2_configure_vel();
}
ISR(TIMER5_COMPA_vect) {
    m3_step();
    m3_steps_done++;
    m3_configure_vel();
}

While, in the velocity configuration I have:

void m1_configure_vel() {

  if (m1_steps_done < m1_acceleration_steps) {
    m1_temp_vel = m1_temp_vel + acceleration;
  }
  else if (m1_steps_done <= (m1_steps - m1_acceleration_steps)) {
    m1_temp_vel = m1_temp_vel;
  }
  else if (m1_steps_done < m1_steps) {
    m1_temp_vel = m1_temp_vel - acceleration;
  }
  else {
    m1_temp_vel = 0;
    m1_finished = true;
  }
  if (m1_temp_vel <=0){
    m1_temp_vel = 0;
  }

  OCR3A = frequency_to_compare_value(m1_temp_vel);
}

As you can see, all I do here is, depending on the steps done by the motor and the amount of steps to do, I increase, maintain or decrease the motor's velocity and set the compare value for the timer.
The whole thing is that this code works fine, the ramps are calculated properly and motors move correctly. The problem is that, under the condition I explained before, interruptions may collide due to their priorities and one of them just stops to happen.
I was wondering if anyone had any idea or have faced something like this before.

I think the problem is being caused by the size of your ISR's.
When using ISR's, it's important to make the code as short as possible and you should certainly avoid using any functions!
I would change each of your ISRs to:
ISR(TIMER3_COMPA_vect) {
    m1_steps_done++;
}
ISR(TIMER4_COMPA_vect) {
    m2_steps_done++;
}
ISR(TIMER5_COMPA_vect) {
    m3_steps_done++;
}

then, in the main loop of your code, you can change it so that if m1_steps_done, or m2_steps_done or m3_steps_done has increased, execute the step and configure functions


Arduino Power - DC adapter I have a 12V 2.5 ampere Dc adapter.Can i use it to power arduino uno board?
It says on the arduino website that i can use 9-12V and upto 1 ampere. I am concerned with current limit here..

Don't worry about the current limit. The board will only draw what it needs. The spec is telling you that the board can draw as much as 1 amp, so in general the power supply should be able to supply that – more is no problem, but less could be if you have a lot of devices attached to the board that are drawing power as well.

As is pointed out in the comment above the higher the input voltage the more power the on-board regulator will need to dissipate (as heat). If you are using the barrel jack (which you should if you aren't providing power through an external regulator or other stable source) there is a diode (D1 in the reference design) in the input path and the MC33269D-5.0 regulator is spec'd with a max dropout voltage of 1.25 V so you will need an input voltage of at least 6.95 V (assuming a 0.7 V drop across the diode).


Can't display text on LCD 1602 Today I tried to display some text with my Arduino UNO and a LCD 1602A screen. I did find some schemas online, but I cannot get any character or "black boxes" on the display.

I connect wires like that :
Pin 1 : GND
Pin 2 : +5V
Pin 3 : 50K Pot.
Pin 4 : Pin 7 from Arduino
Pin 5 : GND
Pin 6 : Pin 6 from Arduino
Pin 11 : Pin 5 from Arduino
Pin 12 : Pin 4 from Arduino
Pin 13 : Pin 3 from Arduino
Pin 14 : Pin 2 from Arduino
Pin 15 : +5V
Pin 16 : GND

You can see my setup here : http://imgur.com/a/QkI4z

The LCD screen is lighten up, but nothing else appears. Pot. is working (increase or decrease light). I tried to change the LCD with another, but both are not working. I tested some many code, here an example :

/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Do you have an idea ? Thanks !

I realize that your question is based around using multiple connections to the arduino, however if you wish to simplify the setup/operation have a good look into I2C interface, this only uses 2 pins SDA and SCL to operate, you can get an interface board on Ebay for $1.00....just a thought.


AI A7 Thinker connection with Arduino I am trying to connect my A7 to my Arduino Uno but I can't find a way to communicate with it. I searched a lot on the internet to find some schemes but not one of them worked. Here is my actual setup:

ARDUINO              A7

PIN 6      <=>       URXD
PIN 7      <=>       UTXD
GND        <=>       GND
5V         <=>       5V

Here is my code:

#include<SoftwareSerial.h>
SoftwareSerial myserial(6,7);//RX,TX

void setup() {
  Serial.begin(9600);
  myserial.begin(115200);
  Serial.println("Starting...");
}

void loop() {
   delay(1000);
   myserial.println("AT");
   Serial.println(myserial.read());
}

I tried by connecting USB instead of 5V, both of them, connecting the POWER pin, or interchange 6 and 7, pressing the power button, with different delays, different baud rates, but I always get the same output on my computer:

Starting...
-1
-1
-1
-1
...

Sometimes it goes 0 when I plug the USB and press the power button. The LED on the A7 is responding when I press the button and sometimes it powers up the circuit.

I also tried this solution with really simple code:

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

void loop() {
}

Again with different bauds rates but the compiler outputs an error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
...

So I don't know what is wrong. Maybe the board is not working but it's most certainly my mistake, so I am asking for your help to solve this puzzle.

Thank you!

I'm dealing with the exact same thing right now trying to get mine to work. The only help I can give so far is that that avrdude error was solved for me when i stopped trying to upload code to the uno with the a7 powered. think it has to do with the programmer using the same RX/TX ports.