text:
Using LM70 temperature sensor with Arduino
I am trying to sense the temperature using the LM70 temperature sensor with an Arduino Mega. As you can see in the Datasheet, it uses the SPI protocol. I have made the following connections (VSSOP-8 Package):

SI/O pin --> Pin 50 Arduino Mega.
SC pin --> Pin 52 Arduino Mega.
CS pin --> Pin 53 Arduino Mega.
V+ pin --> 3.3V Arduino Mega.
GND pin --> GND Arduino Mega.

My code does not work (it does not print the right temperature), and I think it can be for two reasons:

I am not reading correctly the information from the sensor. It sends 16 bits, from which the 11 first bits store the data for the temperature.
I am not calculating the temperature in the right way.

This is my code:
// the sensor communicates using SPI, so include the library:
#include <SPI.h>

void setup() {
  pinMode(51,OUTPUT); //MOSI
  pinMode(50,INPUT); //MISO
  pinMode(52,OUTPUT); //CLOCK PIN
  digitalWrite(53,HIGH); //slave select stays high. When we set this to low, the sensor will start to send data.
  SPI.begin();
  Serial.begin(9600);

  //time to set up
  delay(500);
}

void loop() {
    //enable Slave
    digitalWrite(A0,LOW); //Enable communication with slave
    delay(500); //wait for conversion

    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;
    Serial.println(temperature); //display temperature on serial monitor

    //disable Slave
    digitalWrite(53,HIGH); //set to High again
}

Please, if you see something wrong in my code, let me know.
Thank you in advance.

digitalWrite(A0,LOW) -- Are you sure about that one?

You are right, it should be digitalWrite(53, LOW). Thank you!!!
However, the code still does not work. Any ideas?

There are several things that are not doing correctly. This is not a complete answer but to provide you some directions on how to get it right.

A0 is pin 54, it is not SS which is pin 53;

On how to use the SPI library properly, I would suggest that you read my blog on SPI, it will also help you to get the data out of data sheet that you need for SPI programming. Based on the timing diagram on the data sheet, you will need to configure the SPI as SPI_MODE2;

LM70 SI/O pin is used as both MOSI and MISO, you will need to connect MOSI to SI/O via a 10k resistor, and connect SI/O direct to MISO, this information is available in the data sheet;

LM70's temperature data is in Two's complement format, To convert it, it needs a little bit work. It is then need to shift down/right using bitshift operator by 5 bits to get ride of the first 5-bits, before finally multiply by 0.25C as per data sheet.

int value = 0x4b1f;  //value from SPI, temp = 125 degree C
int mask = 0x8000;   // mask for MSB
int temp = (-(value & mask) + (value & ~mask)) >> 5;
Serial.print("Temp");
Serial.println(temp*.25);

Read all links that I provided to understand the subjects and give it a try. Good luck!

Your problem lies here:
    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;

And it's a twofold problem.
First:
int val = SPI.transfer(0x00);

That only reads the first 8 bits of the data. To get all 16 bits you have to do two transfers and then combine them together with bitshifting:
int bh = SPI.transfer(0x00);
int bl = SPI.transfer(0x00);
int val = (bh << 8) | bl;

That then gives you a value that is right-aligned. you then need to shift it to the left the right number of bits and "sign extend" it to keep it negative if needed.  If you're not interested in the fractional part then it's as simple as:
val >>= 7;
if (val & 0x0100) {
    val |= 0xFE00;
}

Now... what does that all mean?  Well, assume it's currently 25°C. From the datasheet we can see that would give us a reading of 0000 1100 1001 1111 (note there is a typo in the datasheet saying that is 0b9f in hex when in fact it's 0c9f).
Let's do those operations - first the bit shift:
Dec   Hex   Bin
3231  0C9F  0000110010011111 >> 7
25    0019  0000000000011001

Then we look to see if bit 8 is set or not (bit 8 was the most significant bit). If it is then we OR it with bits 9-15 also set. This "sign extends" it.
Let's take a look at -25°C from the datasheet:
Dec   Hex  Bin
-3169 f39f 1111001110011111 >> 7      Shift right 7 bits
487   01e7 0000000111100111 & 0x0100  And with 8th bit
256   0100 0000000100000000           Result is not 0 so is true

"Or" the shifted value with 0xFE00:

487   01e7 0000000111100111 or
65024 fe00 1111111000000000 =
-25   ffe7 1111111111100111


text:
Infrared sending not working slight misconfiguration?
Edit: Took some advice from below but it still doesn't work. I think it probably blocking code but please tell me how I could fix it to send a the valid infrared signal, NOTE: I wouldn't actually code it like this I am just trying to learn and understand how to do it and then make it better after:
uint8_t Status;
uint8_t Counter;
const uint32_t Code[] = {4507,4507,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,1694,573,1694,573,1694,573,1694,573,1694,573,1694,573,46560};

void setup() {
  pinMode(4, OUTPUT);
}

void loop() {
  while(Counter<70) {
    if (Status=1) {
        digitalWrite(4, HIGH);
        Status=3;
        while(Status=3) {
          delayMicroseconds(26);
          digitalWrite(4, HIGH);
          delayMicroseconds(26);
          digitalWrite(4, LOW);
        }
        delayMicroseconds(Code[Counter]);
        Status=2;
        Counter++;
    } else {
      if (Status=2) {
        digitalWrite(4, LOW);
        Status=0;
        while(Status=0) {
          delayMicroseconds(26);
          digitalWrite(4, HIGH);
          delayMicroseconds(26);
          digitalWrite(4, LOW);
        }
        delayMicroseconds(Code[Counter]);
        Status=1;
        Counter++;
      }
    }
  }
}

It is unclear, what exactly is the problem. Maybe you have some basic misconceptions. Like, that infrared remotes (and also most libraries) use a fixed modulation for the pulses (for example at 38kHz) to get better noise resistance. How are you receiving the IR signal? You need to send an IR signal, that the receiver understands.

Raw infrared timings do not need to specify hz I believe. if you flash a led constantly at 1Hz you would be flashing 1 time per second. 2Hz 2 times per second. The actual infrared timings in the Buf variable do not need to specifcy a frequency since they are RAW. So the code above It starts with the first 4507 and that would be the delay. the (timing). I believe that's how it works after reading alot about infrared. But the problem im having is that I don't know how to implement it i guess? do I flash delay for 4507 and then keep it off for 4507? I know how it works but need help debuging this

No, I'm very sure, that you don't just send raw on and off cycles with the LED, though that depends on what you use to receive the signal. You didn't answer that question. So how are you receiving the signal?

Im not looking at the recieving side.

soooo, how are you checking if it works or not? Sounds like testing the light switch, but without looking at the actual light, if it really lights up.

If the TV turns on then it works :/

if (Status=1) is an assignement, this will not work like you think it does. It should be a comparison: if (Status==1). Likewise for while (Status=2) and other if() and while() statements in your code. Furthermore there is no way your while() { } loops will ever exit because the value of  Status never changes inside the loop.

If the TV turns on then it works ... they are not all same ... what is the brand name and model of TV?

There are two basic things wrong here - one with your understanding of the timings, and the other with your understanding of how IR communication works.
First the timings - those are both ON and OFF timings. You don't just turn on for a defined length of time - you turn on for a defined length of time and then turn off for another defined length of time.
So for the timings in your code 4507,4507,573,1694,573,...etc... you would:

Turn on
Wait 4507us
Turn off
Wait 4507us
Turn on
Wait 573us
Turn off
Wait 1694us
Turn on
Wait 573us
... etc ...

You have no "off" time in your code, only ever on times.
Secondly is your understanding of IR communications. It does not involve turning an LED on or off for defined times. It's not as simple as that. Instead you are controlling the modulation of an LED.  When the LED of an IR remote control is "on" it's not just turned on - it's rapidly turning on and off. The receiver looks for the presence or absence of this rapid turning on and off light. This is the "carrier frequency" of the signal and must match what the receiver is looking for.
Typically this is between 30kHz and 50kHz depending on the receiver.
So you need some way of generating that rapid on-off signal. Normally this is done using PWM by the IR libraries and switching between 0% and 50% duty cycle for the off and on periods of the signal you want to send.
So it's far simpler to just use a library that does all this underlying work for you.

Thanks I will try this out and see if it works <3

I have edited my question because yours should work but it doesn't.

You have covered the first problem, but done nothing at all about the second problem.

delayMicroseconds(26) is 38khz :/

This I can 100% verify I know since it has been mentioned in all of the stuff I have read

Except for some problems: 1. digitalWrite and while take time so your 38kHz would end up more like 10kHz if you're lucky. 2. You have no way of ever leaving your while loop. 3. You are doing an assignment and not a comparison, which will always be true.

can you provide me some basic simplified code on wat i need to do? :>

if (Status==2) is an comparison, if (Status=2) is an assignment.

Yes: use a library. You are trying to perform something very very complex and you don't even understand the basic syntax of the library.

I mean I can use the library. I just want to understand how it works and I want to make my own simplified version. Satisfaction of doing it urself and just more flexible since its small and I can read it better and not only that improve its performance even if its at a fraction.

Start with doing something simpler. IR requires precise timing and an intimate knowledge of the MCUs internals.

oki :~ thanks :>

source: Stack Exchange

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

sort: votes


text:
Building RS485 serial to USB adapter with digispark
Is it possible to build an serial-adapter with digispark board?
Like: Embedded System with 2-wire RS-485 Port connect to my digispark board. Digispark Board is connected via USB to my Computer (running Linux tty or Windows COM Putty Interface)
I also own a Raspberry Pi. I'm very new at this thing, so maybe there is a way to convert the RS485 signals to monitoring my devices with my computer?

Yes. However; you state that you are 'very new at this thing', you may want to start with blinking LED's and/or find a tutorial for what project you're thinking off; so you can follow along easily.

I just started with coding digispark, like with these blink led or some other things, but ich dont know where to find the right keyword or tutorial with this serial COM connectors.

There are some good books available to help. There is the Raspberry Pi cookbook and the Arduino cookbook. These will take you from the very beginning to the point where you can make your own designs and they will work.

I would steer you away from using something that has a chip with neither a USART nor USB hardware for the purposes of making something like that. The ATTiny85 that's on the Digispark has USI (Universal Serial Interface), which is really more of a USART construction kit. The USB support it has is bitbanged and somewhat unreliable.
If you do go in this direction and want a small Arduino type board like Digispark, the "Beetle" ATMega32u4 based boards are a better choice.  It has a native USB interface, and a proper USART to hook to an RS-485 driver.
The chip also has a bootloader section; it is difficult to corrupt your own sketch.  It also has more memory, not that you necessarily need it.

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


text:
What wireless protocols can be used with arduino?
Before you close this saying it's not related to programming. It is related to programming since i'm using it and asking about libraries.
What are the common types of communication protocols and their libraries? Theres WiFi which uses esp8266 etc. Zigbee which can be used with XBee, Bluetooth which can be used with esp32 and others.
What are a list of wireless protocols and chips and libraries for those wireless communications? (This list will be compiled by multiple people hopefully so its okay if you don't know the library or chip but protocol is good) thank you and hopefully no take down <3

Any and all protocols can be used if you can find/build/program the interface to them.

I'm asking what protocols exist. Link a list?

https://en.wikipedia.org/wiki/Comparison_of_wireless_data_standards

this question is not arduino specific

Arduino can use all wireless protocols both in existence today and which yet will be invented in the future. There is no limit to wireless protocols which may be used with Arduino. The correct answer is: all of the protocols.

Arduino allows you to connect external peripherals (via I2C, SPI, UART, I/O) and shields.
It'll be impossible to list them all, as you can even make your own; but here an overview of the most common I can think off:

WiFi
Bluetooth
LoRa
Zigbee
Z-wave
RF (433mhz)
InfraRed
GSM/LTE

It'll be a trade-off between signal range, power usage, delay and bandwidth.
Do note that your question in this way is quite broad. If you want to use this to start your own wireless proejct, you can follow these steps (, but do note that we expect one to do some research/tests himself before posting a question):

Find a tranmission layer applicable for your project based on requirements.
Find Arduino compatible hardware (if none found; make your own or find another transmission layer / adjust requirements)
Find libraries/examples of this hardware being used with Arduino.
Buy the hardware (this is not step 1!)
Use the found sources and make your project reality.


text:
Clocking issues while programming ATMEGA32U4-AU via USB bootloader
Hi,
I'm designing a custom board with the ATMEGA32U4, with a GPS receiver and LoRa radio and it is powered from a LiPo battery. Since I'll need to make hundreds of this board later on, I'd like to program them over USB. I started out from the Arduino Pro Micro schematic and I use an 8MHz crystal. I'm able to make use of the factory default USB bootloader and upload Arduino sketches using the dfu-programmer in Linux. My first problem was that the blink example didn't really blink at 0.5Hz rate(delay(1000) wasn't 1sec), but much-much slower. No worries, reduce the delay a little bit. However, when I want to communicate with the GPS, the from the transmitted signal, I can see that the baud rate is not correct. I suspect that the clock settings are not correct. I read that these can be changed with the help of fuses, but as far as I know, they cannot be modified using only USB , I need a programmer for that, which I'd like to avoid.
(Correct me if I'm wrong here)
So my question is, how do I set up the MCU correctly, so that it runs from the 8MHz external or 8MHz internal clock using only USB? Is it even possible?

Off topic: You can measure Vbatt by using it as AREF and measure internal bandgap voltage reference (= switch to the correct adc channel and measure it)

BTW, have you selected correct speed for pro micro board? (eg. 3V3/8MHz?). Also by default there is CKDIV8 fuse set, so if you didn't changed anytning in fuses, it'll be even slower than just half speed

Thanks for the tip regarding the battery voltage!
Yes, I switched to 3v3/8MHz.
In the meantime, I found this: https://www.avrfreaks.net/forum/clock-select-register-instead-fuse-bits
I was able to switch the clock source back to 8MHz and the UART baudrate seems okay now.

Yes, it's possible to change prescaler, but you have to configure it in each program you create.

I'd still try to set the fuses. Using software to select the correct clock source and prescaler seems to me like a workaround, instead of proper solution. Though I can't give a good reason why. It just feels wrong.

The problem is that I do not have a programmer, so I could only set fuses through USB.
Right now I'm able to send and receive data via Serial, but not SoftwareSerial. On SW Serial I can send, but not receive.

I made some more progress. Turns out, I was using SoftwareSerial with the dedicated UART pins, which is wrong. So basically all my problems have been solved. Thank you for your contributions!


text:
ESP32 HTTP Server request interrupts Telnet session
I have an ESP32 application that uses a web server as a user interface. For auditing and debugging during development I use Serial; however, that is impractical in the installed system. So, I decided to use Telnet (TCP/IP) to monitor what is happening when Serial is impractical.
The issue is that once a TCP/IP session has been established, when a HTTP request is received, the TCP/IP session is aborted.
I have reproduced the issue in a minimal sketch here:
#include "Arduino.h"
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

WiFiClient telnetClient;
WebServer server(80);
WiFiServer telnetServer(23);

void telnetPrint(const char* text)
{
  if (telnetClient)
  {
    telnetClient.print(text);
  }
}

void telnetPrintln(const char *text)
{
  telnetPrint(text);
  telnetPrint("\r\n");
}

void _print(const char* text)
{
  Serial.print(text);
  telnetPrint(text);
}

void _println(const char* text)
{
  Serial.println(text);
  telnetPrintln(text);
}

void _println(IPAddress myIP)
{
  char rgIPTxt[32];
  sprintf(rgIPTxt,"%u.%u.%u.%u",myIP[0],myIP[1],myIP[2],myIP[3]);
  _println(rgIPTxt);
}

const char *rootFmt="\
\
  \
    <title>Test</title>\
  \
  \

Test
\

\

Heap size=%d

\

\
  \
\
";

char rootMessage[1024];

void updateRootMessage()
{
  _println("updateRoot");
  snprintf(rootMessage, sizeof(rootMessage), rootFmt,
           heap_caps_get_free_size(MALLOC_CAP_8BIT)
           );
}

void handleRoot()
{
  _println("Entered handleRoot");
  updateRootMessage();
  server.send(200, "text/html", rootMessage);
  _println("Leaving handleRoot");
}

void wifiSTASetup(const char*ssid, const char*password)
{
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);
  telnetServer.begin();
  telnetClient=telnetServer.available();
  _println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    _print(".");
  }
  _println("");
  _print("Connected to ");
  _println(ssid);
  _print("IP address: ");
  _println(WiFi.localIP());
  server.on("/", handleRoot);
  server.begin();
}

#define BAND    915E6

void setup()
{
  Serial.begin(115200);
  wifiSTASetup("your ssid", "your password");
}

void loop()
{
  server.handleClient();
  if (!telnetClient)
  {
    telnetClient=telnetServer.available();
    if (telnetClient)
    {
      _println("telnetClient obtained");
    }
  }

}

create an issue https://github.com/espressif/arduino-esp32/issues

https://github.com/espressif/arduino-esp32/issues/4399


text:
Arduino binary LED 10 bit display
I'm working on a simple ADC project, the goal is to adjust the on/off of the LEDs according to the binary reading (1-on,0-off). I've tried this with 8 bit, and it works as intended. But on 10 bit, two of the LEDs with representation of 2^8 and 2^9 won't turn on even though the reading on the serial monitor is 1023 (should be 1111111111 -all LEDs on). I wonder if there's anything wrong with my code or circuit?
(I'm totally new to arduino, sorry for the noobness)
-I'm using Arduino UNO R3, the details are shown in the image
void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin(9600);
}

void loop(){
  int sensorValue = analogRead(A0);
  Serial.print("Decimal=");
  Serial.print(sensorValue);
  Serial.print("\tBinary=");
  Serial.println(sensorValue,BIN);

  if(sensorValue>=0&&sensorValue<=1023){
    digitalWrite(4,(sensorValue&1));
    digitalWrite(5,(sensorValue&2));
    digitalWrite(6,(sensorValue&4));
    digitalWrite(7,(sensorValue&8));
    digitalWrite(8,(sensorValue&16));
    digitalWrite(9,(sensorValue&32));
    digitalWrite(10,(sensorValue&64));
    digitalWrite(11,(sensorValue&128));
    digitalWrite(12,(sensorValue&256));
    digitalWrite(13,(sensorValue&512));
  }
  delay(20);
}

write a debug sketch ... turn on all of the LEDs ... does that work?

According to the official documentation, the second parameter of
digitalWrite() should be either HIGH or LOW. Thus, in order to be
compliant with the published API, you are supposed to write:
digitalWrite(12, sensorValue&256 ? HIGH : LOW);

In practice, digitalWrite() interprets any non-zero value as HIGH.
However, its prototype is:
void digitalWrite(uint8_t pin, uint8_t val);

Both parameters have the type uint8_t, which means “8-bit unsigned
integer”. If you provide a value that doesn't fit in 8 bits, the
implicit cast to uint8_t will reduce it modulo 28. Thus,
both 256 and 512 become zero through the implicit cast.

Your trinary operator trick would fix the 8 bit truncation problem AND send the documented values to the function. Personally, I'd write a function that took bit index and a value and returned HIGH or LOW, and call that. D.R.Y.

I know OP is new, but fancy not writing to ports for ganged output.

Seems, digitalWrite does not take any int != 0 as HIGH
Rather consider supplying a boolean (one byte value)
   digitalWrite(12,(sensorValue&256)==256);
   digitalWrite(12,(sensorValue>>8)&1);

or similar


text:
Need PPM out of MQ4 sensor
I'm using this working library to extract H2 & Alcohol in PPM from sensors.
UPDATE
I read the readme file and used the example shown.
But this gives me an error.
This is the code:
  //Include the library
#include <MQUnifiedsensor.h>
/************************Hardware Related Macros************************************/
#define         Board                   ("Arduino UNO")
#define         Pin                     (A4)  //Analog input 4 of your arduino
/***********************Software Related Macros************************************/
#define         Type                    ("MQ-4") //MQ4
#define         Voltage_Resolution      (5)
#define         ADC_Bit_Resolution      (10) // For arduino UNO/MEGA/NANO
#define         RatioMQ4CleanAir        (4.4) //RS / R0 = 60 ppm
/*****************************Globals***********************************************/
//Declare Sensor
MQUnifiedsensor MQ4(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);
// Setup
MQ4.setRegressionMethod("Exponential"); //_PPM =  a*ratio^b
MQ4.setA(1012.7); MQ4.setB(-2.786); // Configurate the ecuation values to get CH4 concentration
MQ4.setR0(3.86018237); // Value getted on calibration
// Loop
MQ4.init();
MQ4.update();
float ppmCH4 = MQ4.readSensor();

And the error:
Arduino: 1.8.13 (Mac OS X), Board: "WeMos D1 R1, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 921600"
MQ4:17:1: error: 'MQ4' does not name a type
MQ4.setRegressionMethod("Exponential"); //_PPM =  a*ratio^b
^
MQ4:18:1: error: 'MQ4' does not name a type
MQ4.setA(1012.7); MQ4.setB(-2.786); // Configurate the ecuation values to get CH4 concentration
^
MQ4:18:19: error: 'MQ4' does not name a type
MQ4.setA(1012.7); MQ4.setB(-2.786); // Configurate the ecuation values to get CH4 concentration
^
MQ4:19:1: error: 'MQ4' does not name a type
MQ4.setR0(3.86018237); // Value getted on calibration
^
MQ4:21:1: error: 'MQ4' does not name a type
MQ4.init();
^
MQ4:22:1: error: 'MQ4' does not name a type
MQ4.update();
^
exit status 1
'MQ4' does not name a type

please describe the I tried several things

You understand that if the library doesn't do what you need, you can make your own copy of it and modify it, right?

The function serialDebug() is only for debug, as the name says. When you need a specific value, the  library also provides functions for that. Have you ever tried looking at the readme of the library. There you can find the line float ppmCH4 = MQ4.readSensor(). Seems to be what you want

@chrisl I looked and used the example from the readme but it gives me the error I wrote in the updated question.

You need to write a real code with the functions setup() and loop(). It isn't enough to write a comment with these names. You cannot execute any functions at global scope (outside of any other function).

@chrisl thanks for the help. But I figured out what the origin of the problem was. There where library issues reinstall of all did the trick! Thanks for the help though! :)


text:
Getting some strange data from an MPU-6050
I'm trying to create an IMU unit using MPU-6050 unit.
I've got 100k data records, and this is the result:

It seems to me that's a kind of offset in gx. Why?

Why I'm getting this kind of drifting in acz?
This is the setup code:
void setup_mpu_6050_registers(){

  //Activate the MPU-6050

  //Start communicating with the MPU-6050
  Wire.beginTransmission(0x68);
  //Send the requested starting register
  Wire.write(0x6B);
  //Set the requested starting register
  Wire.write(0x00);
  //End the transmission
  Wire.endTransmission();

  //Configure the accelerometer (+/-8g)

  //Start communicating with the MPU-6050
  Wire.beginTransmission(0x68);
  //Send the requested starting register
  Wire.write(0x1C);
  //Set the requested starting register
  Wire.write(0x10);
  //End the transmission
  Wire.endTransmission();

  //Configure the gyro (500dps full scale)

  //Start communicating with the MPU-6050
  Wire.beginTransmission(0x68);
  //Send the requested starting register
  Wire.write(0x1B);
  //Set the requested starting register
  Wire.write(0x08);
  //End the transmission
  Wire.endTransmission();

}

And this is the reading code:
void read_mpu_6050_data(){

  //Read the raw gyro and accelerometer data

  //Start communicating with the MPU-6050
  Wire.beginTransmission(0x68);
  //Send the requested starting register
  Wire.write(0x3B);
  //End the transmission
  Wire.endTransmission();
  //Request 14 bytes from the MPU-6050
  Wire.requestFrom(0x68,14);
  //Wait until all the bytes are received
  while(Wire.available() < 14);

  //Following statements left shift 8 bits, then bitwise OR.
  //Turns two 8-bit values into one 16-bit value
  myData.msecs = millis();
  myData.acc_x = Wire.read()<<8|Wire.read();
  myData.acc_y = Wire.read()<<8|Wire.read();
  myData.acc_z = Wire.read()<<8|Wire.read();
  myData.temp = Wire.read()<<8|Wire.read();
  myData.gyro_x = Wire.read()<<8|Wire.read();
  myData.gyro_y = Wire.read()<<8|Wire.read();
  myData.gyro_z = Wire.read()<<8|Wire.read();
}

The structure that stores data is:
struct datastore {
   long msecs;
   int acc_x, acc_y, acc_z;
   int temp;
   int gyro_x, gyro_y, gyro_z;
};

Then I save data in the card:
logFile.write((const uint8_t *)&myData, sizeof(myData));

where do the graphs come from? ... how is the data in the graphs selected? ... maybe you are graphing an incorrect parameter

The graphs were made based on data saved on a CSV file in a SD card connected to arduino.

I changed the question including the data structure that's is used to store data and the code that save it.

The graphs show values much larger than can be stored in an int. Could you show a line from your CSV file?


text:
Photoresistor help
I'm a newcomer to Arduino, trying to read analog values from a circuit with a photoresistor. I believe I am using a 1-ohm resistor
The problem I am having is that my photoresistor does not seem to be working, or my circuit is wrong. When I run the below code on my Nano, my Serial monitor constantly prints 1023. When I cover the photoresistor completely with my finger, the value dips down to 900-950, but then jumps back up to 1023. It dips down to 900-950 again, and jumps back to 1023. This happens continuously.
Here is my code:
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  int value = analogRead(A0);
  Serial.println(value);
  delay(20);
}

Here is an image of the circuit I am using. In my case, I am using a Nano instead of Uno.

I ran the above code on the virtual circuit above, and it works as expected. However, on my physical device, the phenomenon I explained above occurs.
Is there something wrong with my circuit? Could it be an issue with my photoresistor?

the photoresistor is shorted ... please investigate how a breadboard is constructed

Thanks for the reply. What does it mean for a photoresistor to be shorted?

Also, try a 10 kΩ resistor.

Shorted means there is a flow from VCC (voltage, like +5V for Arduino) with no resistance to GND. This means a lot of current will flow, which might damage or at least make components not working the way they should. Check first how a breadboard works.

shorted means that there is a conductor, such as a wire or breadboard bus, connected from one pin of the sensor to the other pin of the sensor ... this effectively removes the sensor from the circuit, because all of the current in the circuit will flow through the short, bypassing the sensor

Use your ohm meter and check it dark and light that will tell you it is working. Also the resistance (probably 10 or 100K) needs to be relative close to your resistor. Do not expect a lot of voltage swing.

If you pealed the backing off the bread board you will find that you have plugged in your green, red and photo resistor wires into one piece of metal.  This means they are shorted together and as such do not work as you might expect.

Also, be aware that photo resistor or cadmium sulfide cells are slow to react to changes in light.  Sometimes taking about a second to fully change to a new resistance.  If you need a faster response consider using a photo diode or photo transistor.


text:
My code is not uploading to Arduino Uno, Please help!
I am very new to arduino, so new that it is my first board. I keep running into this error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00

I have searched the internet for hours, tried solutions from almost every StackExchange question related to this topic, and even Reddit posts but none of those have been able to help me. All my settings are as they are supposed to be. Both the correct board and serial port are selected but it still keeps giving me this error:
System wide configuration file is "/home/rahat/Desktop/Arduino/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf"
User configuration file is "/home/rahat/.avrduderc"
User configuration file does not exist or is not a regular file, skipping
   ` Using Port                    : /dev/ttyS4
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200`

 avrdude: stk500_recv(): programmer is not responding  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
Also my operating system is Ubuntu 20.04 LTS

You have the wrong port selected. It should be /dev/ttyACM0 or /dev/ttyUSB0

There are no ports /dev/ttyACM0 or /dev/ttyUSB0 available to me

@Majenko the only port available to me is /dev/ttyS4

Then you either have no acess rights or hardware issue.
Try lsusb. and post us an output. If it finds the hardware stating something like 'QinHeng Electronics HL-340...' (there are others).  We will try to trace access issue.
If lsusb doesnt see it then its most likely a cable, but other options are we will trace when it comes to it...

in some cases you may have to use sudo lsusb

Did you do the proper permissions? https://www.arduino.cc/en/Guide/Troubleshooting#upload (Drivers - Linux)

First of all find out on which port the Arduino is connected by running the command : dmesg | grep tty. You should get [82893.921017] usb 1-1: cp210x converter now attached to ttyXXX with the ttyXXX COM port.
Then check if the port is visible Tools->Port. If the port is not visible then you have a permission issue.


text:
How to use a non-adafruit BMP280 sensor for continuous data outflow
please I need help with the arduino BMP280 breakout board I got from  AliExpress. I’m pretty new to the arduino world, I need it for my rocket datalogger, I downloaded the adafruit BMP280 library but I don’t know how or where to change the data rate and what does the “default standby time” mean in the library sensor code? I want to get at least 10-20points of data per second as the rocket will be traveling very fast. Can someone please help me with a solution, or if there’s another library that solves my problem. I’m really stuck. Also, I don’t want my code to stop while waiting for temp, pressure and altitude values and also get the altitude before launch so that I can now the approximate height of the rocket above see level. Any help would be appreciated.
Details
Connection type: 12c
Application : Water rocket altimeter/datalogger and flightcomputer.
Brand: Unknown
Microcontroller: Arduino Nano

you said nothing about what you have ... you only described what you want to use it for ... please provide a link to the datasheet for the device

Show what you've done so far in getting the altitude from the pressure reading, and what stop you from reading it multiple times?

Take a look at the source code of Adafruit library

With a single instantaneous pressure reading you can't get sea-level and elevation. You need to know sea-level to get elevation. You need to know elevation to get sea-level. You can get a "flight level" by setting the sea-level pressure to 1013.25hPa but that's only a true elevation on a very small number of days in the year (if any). So you need to work out how you're going to set the MSL value for your altimeter before flight. You really need to post the code that you've tried so far.


text:
Sequencing air pistons proble - Help please?
I am a beginner trying to activate 2 sets of 3 air pistons sequentially by going through the YouTube Tutorials... Help, please, pretty please?? :-)
There are 3 sets of 2 pistons, each set working in opposition.
So I have P1/P2, P3/P4, and P5/P6, each set working in opposition to squeeze at the center sequentially -
Initial state at turn-on/Reset must be:
// Step 1 Run Once:
P1 Down/P2 Up  // Move simultaneously (joining at the center) and HOLD in position -
P2 Up/P3 Down  // Move simultaneously and HOLD -
P5 Up/P6 Down  // Move simultaneously and HOLD -
// Wait for Start button -

I need to start/stop the sequencing with a toggle push-button -
I have reed-switch sensors that will give me a set of two TRANSIENT contact closure for each piston moving to the Up and Down positions -
Once started, the sequence needs to be as follows:
// Loop until Reset button is pushed -
// STEP 2: -
P1 Down/P2 Up (HOLD) // Old Initial State, unchanged -
P3 Down/P4 Up (MOVE) // Piston 3 moves Down/Piston 4 moves Up and HOLDS -
P5 Up/P6 Down (HOLD) // Still Old Initial State, unchanged -

// PROBLEM:  P3 Down AND P4 Sensors only give me a TRANSIENT closure:  These two transients MUST occur to initiate Step 3, but  they are not always exactly synched together, so my initial try by putting them in series fails... -
// I need to use that set of contact closures to trigger the next command: -
// Step 3: -
// The transient closures of P3 Down/P4 Up Sensors is the trigger needed for -
P5 Down/P6 Up (MOVE) // P5 moves Down/P6 moves Up and HOLD -
P1 Up/P2 Down (MOVE) // P1 moves Up/P2 moves Down and HOLD -
P3 Down/P4 Up (HOLD)  // P3/P4 HOLD -

// Back to Step 2 until the Reset button is pushed -

I can send you my attempt at coding for this, but it does not work unless the two sensors close simultaneously, which only happens in simulation...  ARGH..  :-(
Can someone send me a piece of code that will work for this, please?
I would really, really appreciate that...  Very frustrated right now!
You can email me at XXXXXXX.XXXX@XXXXX.XXX or text/call at (XXX)XXX-XXXX
Thanks either way.
Sincerely,
Michael
PS:  I tried to wire for a separate toggle switching for each sensor, but I run out of pins on my Arduino UNO R3... Looking into it via YouTube https://www.youtube.com/watch?v=cAT07gy4DII "Increase the digital outputs on an Arduino (PART 1 & 2)" but that is way more complex...  Trying to wade my way through that now...

do not expect two sensors to close simultaneously ... that does not happen in real life ... also, please review step 1 ... it does not make sense

When you say simultaneously, what does that means in precision? down to microsecond? or millisecond? Without code and diagram it is hard to comment on how to improve it or solve your problem. All I could think of right now is that 1) you need to have a state machine to manage all the states and transitions, 2) to make sure all actuators acts together, you probably need to directly access the registers of the MCU for activating each pin than using Arduino commands like digitalWrite().

why do you have separate signals for opposing pistons?

Writing your email address and phone number in clear text into an online site begs for receiving tons of spam and robot calls. When using this site, please also use this site for the communication. Simple Q&A

Please include your code into the question.

it does not work unless the two sensors close simultaneously

If I understand correctly, the problem is that when your Arduino detects
the second transient signal, the first one is not active anymore, and
your program doesn't remember it has already seen that first signal.
Your Arduino has memory. Thousands of bits of memory! So it can remember
quite a few things. The solution to your problem is to simply make use
of that memory. When you detect a signal that should be useful for a
future decision, take note, store it in a variable. In order for the
variable to be remembered across calls of the function where you set it,
it has to be global. Or, better yet, static local.
Here is how that could look like in code:
// A `static' variable is a variable that remembers its state across
// calls of the function. A global variable would do the same, but
// code is usually clearer when variables are defined close to where
// they are used. A `bool' (for "boolean") is a variable that can only
// be either `true' or `false'.
static bool P5_is_up, P6_is_down;

// If the sensor tells us that the P5 piston went all the way up, take
// note of the fact and remember it.
if (digitalRead(P5_up_sensor) == LOW)
    P5_is_up = true;

// Same for P6 going down.
if (digitalRead(P6_down_sensor) == LOW)
    P6_is_down = true;

// If both pistons finished their travel, we can move to the next
// step. `&&' means "and".
if (P5_is_up && P6_is_down)
    goto_step_3();

You will need to reset those variables to false at the appropriate
time. The example code above doesn't show that as it only deals with the
logic for deciding when it is time to start step 3.
You will probably end up with many of these variables, and lots of
repetitive code. So you will need to structure your program in order to
avoid excessive repetition. But that is not your immediate problem. For
now, try to make the logic work for a single step transition. Once you
get the logic right, you can worry about generalizing the logic to any
transition.


text:
Help in personal alarm clock project, cant write time on seven segment display

I'm trying to make a type of Arduino alarm clock, which when the time I inputed is equals to the current time, a servo will turn on my lights. It basically consists of a Keypad, an RTC DS1307 and a TM1637 seven segment display. The basic idea is that the RTC module would print time to the display until I decide to write something on the keypad, which would clear the time on the display to let me write the alarm. My problem is that the display manages to both show time on the display and write to the display but this only works on separate code, not together.
The keypad has a '*' and '#' character, when i decide to write the time i want the lights to turn on, after writing it i press the '*' character to save that time and then the idea would be to compare the time written and the present time, if i press '#', then all would be canceled and the RTC module would continue to show the time on the display. (i have not manage to advance that much due to my error on not being able to clear the display when i want to write on the keypad)
#include "Arduino.h"

// KEYPAD
#include "Keypad.h"

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

char customKey;

byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

// DISPLAY
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"

const byte PIN_CLK = 4;   // define CLK pin (any digital pin)
const byte PIN_DIO = 5;   // define DIO pin (any digital pin)
SevenSegmentExtended      display(PIN_CLK, PIN_DIO);

// RTC

#include <Wire.h>
#include <TimeLib.h>
#include <DS1307RTC.h>

void setup(){
    Serial.begin(9600);         // initializes the Serial connection @ 9600 baud
    display.init();
    display.setBacklight(100);  // set the brightness to 10 %
    display.print("ON");      // display INIT on the display
    delay(1000);                // wait 1000 ms
    display.clear();
}

// OTROS

#define digit 4

byte data_count = 0;
char Data[digit];

void loop(){

    tmElements_t tm; // CLOCK

    display.setColonOn(true);
    customKey = customKeypad.getKey();

    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }

    if (customKey) { // ACTIVATE KEYPAD

        display.clear();

        if (customKey == '*') { // IF *
            display.blink();

            if (Data[data_count] < 3) {
                error();
            }

        } else if (customKey == '#') { // IF #
            display.blink();
            display.setColonOn(false);
            display.clear();
            clearData();
        } else { // WRITE ON DISPLAY

            Data[data_count] = customKey;
            display.setCursor(0,data_count);
            display.print(Data[data_count]);

            if (data_count < 4) {
                data_count++;
            } else {
                error();
            }
        } // END DISPLAY WRITE

    } // END KEYPAD IF

} // END LOOP

void error() { // DISPLAY ERROR AND DELETE DATA
    display.clear();
    display.setColonOn(false);
    display.print("ERR");
    delay(1000);
    display.clear();
    clearData();
}

void clearData() { // CLEAR DATA
    while (data_count != 0) {
        Data[data_count--] = 0;
    }
}

This are the libraries i'm using if it helps:
https://github.com/bremme/arduino-tm1637,
https://github.com/PaulStoffregen/DS1307RTC and the
Keypad library from Arduino library manager
Hope I made myself clear with my problem, english is not my first language, if you want more clarification then let me know!
That is basically what i've got, i'm sorry if the post is too long, i have been struggling with this problem for two days and i don't know how to proceed. Hope you all can help. Thanks!

I think your problem is here:

if (RTC.read(tm)) {
    display.printTime(tm.Hour, tm.Minute, true);
}

This code displays the current time, and it runs on every single loop
iteration. This is visibly not what you want. Your project should have
at least two distinct operational modes: “display the current time” and
“allow the user to input data”. You need a variable to remember which is
the current mode, e.g.
enum { MODE_DISPLAY_TIME, MODE_DATA_INPUT } mode;

You need to precisely define the events that make your program switch
modes, and code specific behaviors for each mode. For example:
if (mode == MODE_DISPLAY_TIME) {
    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }
} else if (mode == MODE_DATA_INPUT) {
    // Handle user input.
}

This general approach is called a “finite state machine”. You can read
more about it in this blog article by Majenko.


text:
Smallest microcontroller?
I am looking for a microcontroller that is small (like a attiny10) which is the smallest one I could find.
Requirements I need: analogRead on 1 pin, 7 pins for analogWrite to micro leds so in total 10 pins (ground, power, analogRead, analogWrite). It's circuitry has to be basic no adding extra things like a crystal oscillator etc.. This will allow me to send a certain code to the recieving pin and then the microcontroller decide which led to turn on.

10 pins already rules out the smallest microcontrollers. Also I'm sure you have other requirements, like the minimum amount of (flash/ram) memory it has, does it have to be through-hole or surface mount. Since you're posting this on an Arduino site, does it need to be compatible with the Arduino IDE? Does it need to be an AVR processor? There are other ways to control individual LEDs that don't need an output pin per LED. Have you looked into those?

The physical size of a microcontoller is mainly dictated by its pins. The distance between each pin is set by the package type. The typical hobbyist microcontrollers use the DIP package with 0.1" pin pitch. But when you have chosen a fitting microcontroller, which fits all your requirements, you can choose a different package, which is small enough for you. Though that will be difficult to solder, if you don't have the right tools

PSoC 4000 are truly small (even tinier than an ATtiny10): about 1.5 x 1.5mm in a WLCSP package (16 "pins"/balls). They're still quite powerful: 32-bit Cortex M0@16MHz with 16KB of flash and 2KB of RAM. They don't have enough PWM outputs though...

PSOC doesn't match my requirements. I'll study more of the specifics and get back to you. thanks <3

For LED driving you don't need hardware PWM - software generated PWM is more than adequate. A little bit of jitter really doesn't matter for LEDs.

So ur saying that you can make 2 leds turn off on etc seperatly with only software and no giant libraries that would fill a attiny10?

Yes. I once made an electronic candle with an rgb led and a pic10 - only had about 300 bytes of flash and 16 bytes of ram.

can you tell me how i would do that?

It depends on what you want to do. On the PIC10 I had a tight loop with a counter and three (R, G and B) duty cycle variables. Plus a crude PRNG routine. All written in assembly language. You would probably be fine using a timer or something like that if you want to make it more concurrent.

check out this EEVBLOG video ... multiple microcontrollers may be the way to go ... https://m.youtube.com/watch?v=VYhAGnsnO7w

EEVBLOG helped me find some microcontrollers.

You can drive 12 LEDs out of 4 digital pins using Charlieplexing.

"doesn't match my requirements", "changed my plans" - So only you know what you want to do and can decide what you need to do it. While it is interesting to contemplate, this question is under-specified, seems to be a moving target, and doesn't appear to be about Arduino hardware or software. [Voting put on hold pending OP update].

I don't know whether it's really the smallest you can find but... The
ATtiny84 has an ADC, more digital pins than you need, and is
available in 3 mm packages (UFBGA and VQFN). There is also an
Arduino-compatible core available for it.

The Attiny84 is huge compared to what I need sadly. I need something like the attiny10 but with more pins. preferabily avr

More pins = more size - unless you want to go BGA or chipscale, which is normally outside the abilities of hobbyists.

@Macaroni, 3mm x 3mm is huge?

@Majenko I changed my plans but I still need alot of pins so I might use BGA. I found 2 microcontrollers but I'll have to watch a video to learn about how to solder them because they are WACK. Which one is compantibe with arduino ide and which one should I choose etc.. I need alottt of pins its a big project. Like a mini computer is what im working to.

https://lcsc.com/product-detail/ATMEL-AVR_MICROCHIP_AT91SAM9G45C-CU_AT91SAM9G45C-CU_C111548.html
15 X 15mm 324 pin
https://lcsc.com/product-detail/NXP-MCU_NXP-Semicon-MCIMX6U5EVM10AC_C394782.html
11 X 11mm 624 pin

JLCpcb seems to have a smt service. Don't know if they would do bga so :/

You said you needed 10 pins. Is that a "lot"?

"I changed my plans"

I made a Arduino develop board with ATtiny3217, it has a 24-pin VQFN form factor, but as powerful as ATmega328p, with no external crystal and capable running at 20MHz.
If this is not suitable for you, look into the new tinyAVR family, they are the new generation of ATtiny with more functionalities than the older ATtiny family with the smaller footprint.


text:
TPIC6B595 Output Unable to Allow Supplied Power to 7-segment Display
We have an Arduino Nano connected to 4 small (0.5") common-anode 7-segment displays and 2 large (3") common-anode 7-segment displays. We are trying to multiplex the displays. The larger one requires more power than the smaller one (9V) which the shift register cannot supply.
Therefore, we have supplied 9V to the open drain outputs of the shift register that are connected to the larger displays with a pull-up resistor (390ohm). However, more power (7.5V) goes to the resistor than the display (1.5V).
They are connected like in the ShiftDisplay library's schematic, with a pull-up resistor added according to this link on open drain.
How do we use the open drain outputs logic to supply power to the display?
The data sheet of the big 7-segment display can be found here. Each display requires 160mA of continuous current.

you should post a wiring diagram, your description is not sufficient. use the open drain outputs logic to supply power - you don't typically use pullup resistors to supply power to sth., maybe you confused that with urrent-limiting resistor?

You are getting confused. The pullup resistor is only needed on open drain when you are using it to generate logic levels. It turns the OD output into an RTL output.
You don't want that.
Instead you want your open drain outputs to act like a low-side switch transistor - which is infact what they are.
You can do that by simply placing your LEDs in series with your "pullup" resistor, thus:

simulate this circuit – Schematic created using CircuitLab
I have only shown two elements there (everything inside the dashed box is inside the shift register), but you can see now how when an output is "on" the transistor conducts, and the current flows through the LED, through the resistor, through the transistor, and down to ground.
Your resistor value is then calculated as simply
    9 - Vfled
R = ---------
      Iled

For 20mA and a 2V forward voltage that comes out as 350Ω - so your 390Ω resistors are perfectly fine.

Hi, I don't think this works for our specific 2-digit display (10 pin variant), your answer would require me to have one IC per display. Am trying to see how to use the open drain output on the anode side like in the miguelpynto GitHub.

It sounds like you have a multiplexed display. You don't want to use a shift register with one of those. You either need a multiplexing driver chip or to wire the display direct to the Arduino.

Can you use different resistors for each display group? If so that will solve your problem along with what Majenko said.


text:
FIFO overflow with DMP on MPU6050 and OLED
I am using the DMP example code to get yaw pitch roll values, mainly I am interested in pitch value for building a self balancing robot. I am trying to display the pitch values on an OLED screen but I am getting FIFO overflow error which is resulting in delayed sampling and sometimes erratic values.
I tried adding a mpu.resetFIFO() after updating the OLED, but its causing a very slow sampling of the sensor.
I am keen on changing the Arduino Uno for a Teensy board(prolly teensy LC). My main concerns are will changing the processor help? Teensy LC runs @48Mhz compared to Arduino Uno which runs @16Mhz.
Also I went through this link which I found as a probable solution but wasn't able to do it
https://www.i2cdevlib.com/forums/topic/27-fifo-overflow/#comment-99
would be great if someone could guide me as to how do I do this?

I wasnt able to change the bit as instructed, but after some more reading I was able to, I think the OLED updating is causing a delay, which in turn is causing FIFO overrflow(as it might be slow). For now I am not adding  an OLED.
I tested my code on the bot seems like when the bot freaks out after couple of seconds trying to balance itself the values from MPU are erratic and the program freezes, have tried adding decoupling caps on my motors but it doesnt solve the issue. Really confused as to what is happening

if you can, please post your code ... or post a minimal code that still exhibits the problem ... maybe it can be optimized ... my thinking is to
handle MPU-6050 comm fully at every iteration of loop() and handle OLED comm in chunks


text:
TinyGPS++ Question about gps.encode(ss.read())
I am trying to make an oled gps display, however when looking at multiple examples and other people's code, I am seeing that people are using different methods. I see some code that has gps.encode(ss.read()); and other people use if gps.encode(ss.read()). I am confused on why this is. Also, people either use .isUpdated, or .isValid, when checking for location/speed, etc. On the TinyGPS++ page it talks about these, but does not say what should be used for certain applications.

it's not really about what should be used for certain application ... it is about what does it do? ... the library takes serial input data and assembles it into a GPS data structure ... certain "flags" are set as the GPS data is assembled, if data has changed ... if a certain function is useful in your program, then use it ... there is no specific use for any of the functions ... so your best start is to learn what ss.read() does, then what gps.encode() does, and so on.

From http://arduiniana.org/libraries/tinygpsplus/
Validity, Update status, and Age
You can examine an object’s value at any time, but unless TinyGPS++ has recently been fed from the GPS, it should not be considered valid and up-to-date. The isValid() method will tell you whether the object contains any valid data and is safe to query.
Similarly, isUpdated() indicates whether the object’s value has been updated (not necessarily changed) since the last time you queried it.
Lastly, if you want to know how stale an object’s data is, call its age() method, which returns the number of milliseconds since its last update. If this returns a value greater than 1500 or so, it may be a sign of a problem like a lost fix.


text:
How to use correctly a microstepping driver with a lower voltage stepper motor
I want to use a microstepping driver like Haitronic's HS2215 with a NEMA 17 stepper motor with rated voltage of 4.2V and rated current 1.5A.
The input voltage range of the microstepping driver is 9-40VDC.
From what I understand,  I can use the switches to set the maximum current. In this particular case I would use SW4=On, SW5=On, SW6=Off.

TB6600 current settings
You can adjust the current that goes to the motor when it is running by setting the dip switches S4, S5, and S6 on or off.

I've found this Maker's Guide which describes the settings for use with an arduino.
However, I am not certain what voltage (VCC) should I supply to the mircrostepping driver? Should I provide, the minimum of 9VDC, should I provide less? Is this irrelevant?

Look at https://electronics.stackexchange.com/questions/200324/how-to-interpret-the-stepper-motor-voltage-requirement . My guess it that the stepper driver itself requires at least 9V to run, so it wouldn't even work (properly) with only 4.2V. PS I'd probably go with a bit lower current setting, as to not push the motor to it's max. Unless you really need the torque.

what does this do? SW4=On, SW5=On, SW6=Off

I think it set the maximum current to 1.5A and peak 1.7A, based on what I see on the label on the product.

if the driver has current limiting, then the driver should automatically limit the output voltage, to keep the output current below a set threshold ... if the difference between the supply voltage and the output voltage is large, then the driver may generate extra heat, depending on design

That doesn't matter at all.
The voltage stepper motors are rated for is the voltage that, if applied to the motor coils, would create its rated current.
Stepper motor drivers monitor the current, and always use the full voltage available to them (9 - 40V in your case) to drive the stepper motor - using PWM.
The stepper motors coils inductance slows down the change in current, allowing the driver to reach its set current.
Higher drive voltages simply mean that it's easier to overcome that inductance, allowing for faster stepper motor movements.
You'll want to set your driver at 1.0 or 1.5 A, and supply it with as much voltage (up to the rated 40 V) as you can.

So, if I read your answer correctly, in stepper motor drivers (like the one I'm posting) the VCC voltage has to do with required voltage for the driver, and not the motor?

Yes, basically. Only the rated current matters if you're using a stepper motor driver.

Do most modern stepper drivers work in this fashion (I mean using PWM to control the current)? In most datasheets I can't say I've found that information... I mean the L298 which is an older driver, did not seem  to use this approach.

They do, and it's usually somewhere at the top of the data sheets (e.g. A4988, DRV8825, TMC2209). The L298 is technically not a stepper driver - if you used that, yes, you should definitely not supply it with 40V, but only the rated voltage of the stepper motor - unless you manage current and PWM yourself on the MCU driving the L298.
If it's called an "integrated" or "complete" stepper motor driver, it'll use PWM to drive the coils and regulate the current.
Note: When stopped on a full step, you could measure the "rated" voltage across the coils too - it's just created via PWM from Vcc.


text:
Very weird bug / odd behavior of OUTPUT
So, I have this code (Arduino Mega):
void setup()
{
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(6, OUTPUT);

  analogWrite(10, 50);
  analogWrite(11, 50);
}

very basic motor speed control. Now when I do this (nothing else is connected to board, only 10 and 11 PWM control pins):
void setup()
{
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(6, OUTPUT);

  analogWrite(10, 50);
  analogWrite(11, 50);
  digitalWrite(6, 0);
}

motors stop. As if those analogWrites are ignored. Is this some exteption about Arduino board? Or is it just a bug? Again, nothing else is connected. Only 10 and 11 PWM outputs. Pin 6 is free. I tried puting digitalWrite above analogs - nothing.

what does this mean? ... I tried puting digitalWrite above analogs - nothing.

Is it a genuine Arduino or a cheap Chinese knock-off?

Chinese. But does it matter?

How are you measuring the PWM output? With an oscilloscope?


text:
Is it possible to use CCMP as cipher type on ESP32's softAP mode?
Currently I'm starting softAP mode on ESP32 with WPA2_PSK as auth type(as WPA3 is not supported for softAP). When I am trying to connect my iPhone to the softAP, iOS gives a warning that WiFi security is weak as it is using WPA2(TKIP). Instead it is asking to configure the AP to use WPA2(AES). I learnt that I need to use CCMP as cipher type instead of TKIP. But I cannot find any API to set cipher type for softAP. Is it supported? Or should I use only TKIP as encryption type? Thanks in advance!


text:
ESP8266 always resetting after 65 second of running
I have a simple code where ESP8266 is asking MySQL database about actual state of LED (whether 1 or 0) and when DB has 1 ESP8266 turns LED on... But my problem is after 65-66 seconds of server running is still resetting... The program does what it is supposed to do, but after 65-66 seconds resets and trying to reconnecting to wifi
---- EDIT -----
After some experiments with code I have found, it doesn't matter the running time but, number of loop cycles... Every time no matter on delay or processing speed, it crash after 48 cycles....
.ino code
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

// Replace with your network credentials
const char* ssid     = "XXXX";
const char* password = "XXXX";
const char* host = "http://www.XXXX.XX/arduino_PHP/post_data.php";

// Set web server port number to 80
WiFiServer server(80);
HTTPClient http;

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 5;
const int output4 = 4;
byte green, red= 0;

void setup() {
 Serial.begin(115200);
 // Initialize the output variables as outputs
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
 delay(1000);
 pinMode(output5, OUTPUT);
 pinMode(output4, OUTPUT);
 // Set outputs to LOW
 digitalWrite(output5, LOW);
 digitalWrite(output4, LOW);

 // Connect to Wi-Fi network with SSID and password
 Serial.print("Connecting to ");
 Serial.println(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 // Print local IP address and start web server
 Serial.println("");
 Serial.println("WiFi connected.");
 Serial.println("IP address: ");
 Serial.println(WiFi.localIP());
 server.begin();
}

void loop(){
delay(500);
DB_state("Green",green);
DB_state("Red",red);
delay(500);
}

void DB_state(String component,int state){
 String postData =("component=" + String(component) + "&state=" + String(state));
 Serial.println(postData);
  http.begin("http://www.XXXX.XX/arduino_PHP/DB_state.php");
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
 http.POST(postData);   //Send the request
 String payload = http.getString();    //Get the response payload
 Serial.println(payload);
 http.end();  //Close connection
 state_LED(payload,component);
 }

void state_LED(String str, String led){
 int x;
   if (led== "Green") {
     x = 4;}
   else if (led== "Red") {
      x = 5;}
   if (str == "State: 1") {
     digitalWrite(x, HIGH);}
   else if (str == "State: 0") {
     digitalWrite(x, LOW);}
 }

ESP8266 Stack debug
Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads
PC: 0x4020744a: ClientContext::state() const at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
EXCVADDR: 0x00000184

Decoding stack results
0x40203f10: HardwareSerial::write(unsigned char const*, unsigned int) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 164
0x40203f1c: HardwareSerial::write(unsigned char const*, unsigned int) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 165
0x40207512: HTTPClient::connected() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 475
0x40202d24: HTTPClient::disconnect(bool) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 434
0x40203ac8: HTTPClient::end() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 425
0x402012ba: DB_State(String, int) at C:\Users\XXXX\Documents\Arduino\ESP8266_php_DB_control/ESP8266_php_DB_control.ino line 87
0x40201334: loop() at C:\Users\XXXX\Documents\Arduino\ESP8266_php_DB_control/ESP8266_php_DB_control.ino line 73
0x40100175: esp_schedule() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 125
0x40205628: loop_wrapper() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 197

Thanks for any advice

So it might be a memory issue like a leak or resource allocation problem.

I thought so, but how fix it?

Before you can fix it, you need to identify it. Read the documentation of WiFiServer and HTTPClient, use your web search skills on the detailed error message of "exception 28", and so on. Check your findings and assumptions with test programs; for example, call http.POST() twice in DB_state() and count the numbers of loops.

as first I would stop using String

Why? And how you replace it?

@Juraj pozdravujem slovenského brata v programovaní :D :D :D

I don't know how, but finally I have found working solution... I have add HTTPClient http; at top of function and it works...
void DB_state(String component,int state){
HTTPClient http; // THIS IS ADDED
 String postData =("component=" + String(component) + "&state=" + String(state));
 Serial.println(postData);
  http.begin("http://www.XXXX.XX/arduino_PHP/DB_state.php");
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
 http.POST(postData);   //Send the request
 String payload = http.getString();    //Get the response payload
 Serial.println(payload);
 http.end();  //Close connection
 state_LED(payload,component);
 }

Can anyone explain me how it's possible? Because I don't fully understand this procedure.

You now construct and destruct the HTTPClient object in that scope each time, as C++ specifies. Presumably the global one leaks some sort of resource, but I can only speculate on that front.

Sorry, i don't understand. Could you be more simlier?

I can't break this down any further in the space provided to me by a comment. I suggest taking a tutorial on C++ that covers objects, constructors, destructors, and such, which will provide this info in a far cleaner way. But basically, instead of having one HTTPClient for the lifetime of the program, you create a new HTTPClient and clean it up after each request -- This makes sense intuitively, but I don't know the internals of HTTPClient enough to know why it happens to eventually crash if you reuse the same instance over and over again.

https://github.com/esp8266/Arduino/issues/7613#issuecomment-700782051


text:
Arduino Nano stucks on uploading
I'm trying to upload an simple blink sketch to my Arduino Nano, which not used for a while.
As I remember, I uploaded an sketch to control RF module, at the last time I used. Now, when I connect my Arduino Nano, I 'm getting error message every second, from my serial monitor saying the the RF communication cant start, because I have disconnected all connections to the RF module.
It seems the Nano is working, and the Nano driver is working properly. I tried resetting manually, and uploading many times with random timings. But up to now, the sketch not uploaded, and waiting. When I press reset button while uploading, Arduino shows me the error it cant communicate.
I think the Arduino IDE not getting enough time to upload from serial, because it's busy all the time.
Is there any way to wipe out the existing sketch from Nano? or any working solution to upload my new empty sketch or simple blink sample? It's a big help if anyone can shed me some light to make my Nano work again.

select "Old bootloader" in Tools menu

@Juraj, I'm unable to find 'Old bootloader' in tools menu. You mean 'Burn bootloader'?

@Juraj, Ok I found it on sub menu and worked great! Thank you so much.

@Juraj I solved it thank you

You should use the "That solved my problem" button, not write an answer

@Juraj, There is no button available to me?

it should be in the box above the question

Edit and delete buttons are available, nothing else?

https://meta.stackexchange.com/questions/250922/can-we-clarify-to-the-op-that-their-question-is-not-yet-closed-and-the-duplicate/250930#250930

I have solved the issue by selecting,
Tools > Processor > ATMega (Old bootloader)
@Juraj, Thank you for suggestion.


text:
Storing value in EEPROM in Arduino Uno
Hi I am a beginner in Arduino Uno. I wanted to store a value of 77880 in EEPROM and fetch it later. I made the code as follows to check my logic(I am using Arduino Uno) :
#include <EEPROM.h>
int addr = 0;
byte value;
void setup() {
  // put your setup code here, to run once:
  int val = 77880;
  EEPROM.write(addr, val);
  Serial.begin(57600);
}

void loop() {
  // put your main code here, to run repeatedly:
  value = EEPROM.read(addr);

  Serial.print(addr);
  Serial.print("\t");
  Serial.print(value);
  Serial.println();
  delay(1000);
}

but I am not getting the value of 77880 when I read the EEPROM address. instead I am getting a value of  56 in my serial output. Can anybody pls explain how should I implement the same?

EEPROM can only store the values 0-255 in any one address. That's the maximum range of an 8-bit value, and EEPROM "cells" are 8-bit in size.
You will have to split your value up into multiple 8-bit chunks and store each chunk at a different address - for example for 32-bit values you can use:
uint32_t val = 77880; // In hex is 0x13038
int addr = 0;
EEPROM.write(addr, val & 0xFF); // Stores 0x38 in address 0
EEPROM.write(addr + 1, (val >> 8) & 0xFF); // Stores 0x30 in address 1
EEPROM.write(addr + 2, (val >> 16) & 0xFF); // Stores 0x01 in address 2
EEPROM.write(addr + 3, (val >> 24) & 0xFF); // Stores 0x00 in address 3

Then to read you do the opposite and shift the values and OR them:
uint32_t val = (uint32_t)EEPROM.read(addr) |
               ((uint32_t)EEPROM.read(addr + 1) << 8) |
               ((uint32_t)EEPROM.read(addr + 2) << 16) |
               ((uint32_t)EEPROM.read(addr + 3) << 24);

Alternatively the EEPROM library has a "store anything" helper to do it for you:
EEPROM.put(addr, val);

That will store the variable val across enough cells to fit it (4 in the case of a 32-bit variable), so you must know not to write to the other cells used by it (0, 1, 2 and 3 in this case) or you will corrupt your data.
You recall it with:
EEPROM.get(addr, val);

Thank you for your prompt reply

See Majenko's answer for why you have to problem. This is alternative solution to the problem.
Using the Arduino library for EEPROM is very limited. It can only read/write one byte at a time. Your variable val is of the type int which is a 16 bit integer on the uno. So two bytes, which is also called a word.
I use the AVR EEPROM "library" directly.
#include <avr/eeprom.h>

EEMEM int eepVariable; // using EEMEM will make the compiler handle the location in EEPROM for you
                           // the compiler makes sure no data will ever overlap inside the EEPROM.

int value; //should be an `int` too.
void setup() {
  // put your setup code here, to run once:
  int val = 77880;
  eeprom_write_word(&eepVariable, val);
  Serial.begin(57600);
}

void loop() {
  // put your main code here, to run repeatedly:
  value = eeprom_read_word(&eepVariable);

  Serial.print(value);
  Serial.println();
  delay(1000);
}

"Using the Arduino library for EEPROM is very limited." You may not be aware, but this hasn't been true for years. See EEPROM.put(). You can write any type. The Arduino EEPROM library also lets you access the EEPROM as though it was an array, using the overloaded operator[], which is very convenient at times. The Arduino EEPROM library also will not unnecessarily cause wear. It only updates values. It won't rewrite bytes if they are already what you are writing. The Arduino EEPROM library is for sure what I recommend using, for these reasons.


text:
9 volt battery unable to power 2 plastic yellow motors
I am trying to build a robot using a kit I got from amazon:
https://www.amazon.co.uk/DFRobot-Tank-Mobile-Platform/dp/B014L1CF1K?th=1
(it uses plastic motors).
The main problem that I am having is that whenever I try to apply a battery with 9 volts to one of the motors it only moves the slightest amount. I am not sure if the voltage is too low or not because in the manual it is using 7.4 volts.
The motors are connected up to a motor driver, here is a diagram of what it looks like

Could the motors potentially be broken? (Hope not because it means I will have to dissect the whole robot)
The motors I am using look like this:

9V batteries are utter junk.

Could you try to use 2 Li-ion battery (like 18650)? They will give you 7.4 - 8.4V.

@AleksejVasinov Isn't that going to give less voltage than the current battery that I am using though?

In specification it is written - "Working Voltage: 3-8V DC". So you should be good :)

@AleksejVasinov One thing I tried doing was connecting one of the motors up to the 9V battery and this seemed to only nudge the motor forwards slightly (almost nothing). So could this mean its the motor that is faulty?

Good news, I seem to have solved the problem! I found some other batteries and they worked perfectly.

@DigitalRookie4 good news. I wanted to advise you to use tester for checking voltage of you battery. But you were faster :)

9v batteries are incapable of supplying enough current for a motor; their best application is tiny-current, standby devices like smoke detectors. You need a power supply that can deliver much more current than the 9v brick can. 6 AA cells in series would do much better. 6 pairs of AA-cells would give you longer run time (each 2 cells in parallel; the 6 parallel pairs in series). You could accomplish the same thing using AAA-cells if your project values space over run-time.

6 D-sized cells would be better yet. Those provide both a large peak current and a large amount of power (measured in amp/hours.) Those are large and heavy, however.

@DuncanC the robot's width is about 20cm. It could still work though. I might be able to find a way around it


text:
Why do we use bitwise operators to assign PORTx, DDRx and Pinx?
I have come accross a lot of examples using ways similar to the ones shown below to assign values to the pins.

PORTB |= (1<<PORTB2); //set bit 2

PORTB &= ~(1<<PORTB1); //clear bit 1

DDRD = DDRD | B11111100;  //Sets up the pins for output

My question is why do we need to use bitwise operations to make assignements?

You have "set bit 2" in comment, not "set bit 2 and clear all others"

@KIIV that is a bitwise OR operator ... it cannot clear bits

@jsotola exactly my point. PORTB |= (1<<PORTB2); //set bit 2 and keep the rest unchanged and PORTB = (1<<PORTB2); //set bit 2 and clear everything else.

Take a look at the LPC3250 User Manual on page 64 (Table 20. HCLK PLL Control register (HCLKPLL_CTRL - 0x4000 4058)). Now tell me, how would you put the PLL in power down mode, and later power it up again, without changing anything else? :) You need to only change bit 16, in a 32-bit register. The C language doesn't have an explicit "Set/change/read only this specific bit" (although, you can do some cool struct/bit member mask stuff with "bitfields"), so you have to be creative and use available operations to modify a subset of bits.

My question is why do we need to use bitwise operations to make assignements?

Because you're not assigning, you're modifying.
If you want to turn on just pin 3 (for example) you need to only control bit 3 of PORTB and leave the others alone.
That means you need to "or" the value of just bit 3 being on with the existing PORTB to turn the bit on, or AND it with the inverse (all pins on except bit 3) to turn it off.
To get the value of bit 3 you can remember that it's 4, or you can just use 1<<3 to say "Bit 3" - or use the macro PORTB3 to make it more readable instead of just the number 3.
The operation is commonly known as "Read Modify Write" and in some low-end microcontrollers you have to take special care when doing it.
For example, if you want to control the output pin 3 and currently you have pins 2, 5 and 6 on and the rest of pins 0-7 off (those are the ones on port B on the Uno) the sequence may be like:
Turn on:

Calculate bit value 1<<3    => 0b00001000
Read PORTB                  => 0b01100100
OR the two values together  => 0b01101100
Write to PORTB              <= 0b01101100

Turn off:

Calculate bit value 1<<3    => 0b00001000
Invert it                   => 0b11110111
Read PORTB                  => 0b01101100
AND the two values together => 0b01100100
Write to PORTB              <= 0b01100100

Could you put examples into your answer as you write (refer) to them?
I have learned from your and &Gerbens answer, but it would make things easier to understand if reference and example are seen simultaneously. Thanks

@Tomas Does that help you?

Thanks. That just become one of the posts to read when learning Arduino

Possibly worth noting that some chips (including the AVR) have specific "set bit" instructions, and at least gcc-avr will recognize this idiom and use the single instruction.

If you want to change all pins on a port at once, you don't have to.
The point isn't just that you want to set/clear the pins you want, it's that you want to not change the state of the other pins.  To do that, you need to modify only the bits for the pins to be changed, and leave all the other bits as they are.  The only way to do this is with bitwise operators.
But if you do want to change all the pins at once, then you can perfectly well just set the port register to a value.  Outputting a value on an 8-bit bus would be a classic case where you'd do this.
I do need to pick you up on one thing in your question though.  In many cases, it is a bad idea to read the state of the port, modify the bits, and write the value back.  The reason is that almost all microcontrollers use the same port address for setting the output state and reading the input state.  So by reading back the port state, you aren't necessarily reading the actual outputs you set.  Logic-high outputs are generally weaker than logic-low, so it's entirely possible for your connected electronics to pull down a logic-high.  The sequence of faults for the bug goes:-

Your program sets a bit (pin) to 1.
Another component pulls that pin down to logic-low.
The next time you read that port back to change another pin, the input for the pin reads 0.
You modify the value for the pin you intended to change.
You write the value back.  Now not only has the intended pin changed state, but so has the pulled-down output.
The other component stops pulling the pin down.  But your micro keeps outputting 0 (logic-low) for that pin.

The solution is that you don't do bitwise operations directly on the register.  Instead, you keep a "shadow" variable containing the state you want the outputs to be.  You do all your bitwise operations on that shadow variable, and then you write the shadow variable directly to the register.  And the bug goes away.

The registers are 8 bits in size. And in the above two cases you want to set/clear 1 bit, while leaving the others the same.
In the last example you want to set pins D2-D7 to output, while leaving pins D0 and D1 unchanged.

It makes code easier to write and re-use.
Let's say your program needs to do 3 unrelated things on different pins. Control a motor, flash a light, count some input pulses.
Since this bitwise technique allows you to read/change only the bits you need to, and leave the others alone, you can totally separate the code for the 3 tasks. It can even be written in separate files by separate people, and without knowing what other pins in the project are being used for. The code for one of the 3 tasks could be copy-pasted into a separate project, without needing to untangle it from project 1 nor make major changes to project 2. In software engineering lingo this is called making code "more maintainable" and also "modular."


text:
Stepper motor slow when reading from MPU 6050 sensor
I'm trying to get an inverted pendulum project working (following the instructions here), and while my stepper motor moves the cart just fine when that's the only code in the Arduino sketch, as soon as I add the MPU 6050 sensor for detecting the angle of the pendulum, the cart moves much slower, far too slow to be useful for keeping the pendulum upright.
I imagine the timing of the motor commands is messed up by the sensor reads, but I'm not sure how to avoid the problem. Also, the author of the example posted essentially the same code as his working solution for proportional control, so there may be something else that I'm missing that messes my motor performance up.
Does anyone have any suggestions for how to get the stepper motor turning fast enough while also reading data from the MPU 6050?
My code is below. I'm using a Nema 17 stepper motor with an A4988 driver, a 12 V 10 A power supply, and this Aukru MPU-6050. To be sure that updates to the speed and Serial prints aren't the problem, I use an interval of 500 ms between updates/printing.
#include "I2Cdev.h"
#include <AccelStepper.h>
#include "MPU6050_6Axis_MotionApps20.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 mpu;

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// Defines pins numbers
const int stepPin = 3;
const int dirPin = 4;
AccelStepper stepper(1,stepPin,dirPin);

int motorSpeed, currentPos;
unsigned long t_start, t_elapsed;
int interval = 500; // ms between printing speed

int speedMax = 4000;
float k_proportional = 4;

float angleCurrent, speedSet;

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
      Wire.begin();
      Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
      Fastwire::setup(400, true);
  #endif

  Serial.begin(115200);

  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);

  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
      // turn on the DMP, now that it's ready
      Serial.println(F("Enabling DMP..."));
      mpu.setDMPEnabled(true);

      // enable Arduino interrupt detection
      Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
      mpuIntStatus = mpu.getIntStatus();

      // set our DMP Ready flag so the main loop() function knows it's okay to use it
      Serial.println(F("DMP ready! Waiting for first interrupt..."));
      dmpReady = true;

      // get expected DMP packet size for later comparison
      packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
      // ERROR!
      // 1 = initial memory load failed
      // 2 = DMP configuration updates failed
      // (if it's going to break, usually the code will be 1)
      Serial.print(F("DMP Initialization failed (code "));
      Serial.print(devStatus);
      Serial.println(F(")"));
  }

  stepper.setMaxSpeed(speedMax);
  stepper.setAcceleration(10000);
  stepper.setSpeed(2000);
}

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
      // wait for correct available data length, should be a VERY short wait
      while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

      // read a packet from FIFO
      mpu.getFIFOBytes(fifoBuffer, packetSize);

      // track FIFO count here in case there is > 1 packet available
      // (this lets us immediately read more without waiting for an interrupt)
      fifoCount -= packetSize;

      // display Euler angles in degrees
      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    }

  t_elapsed = millis() - t_start;

  if (t_elapsed >= interval) {
    t_start += interval;
    motorSpeed=setMotorSpeed();
    stepper.setSpeed(motorSpeed);
    Serial.print("Roll ");
    Serial.print(ypr[2] * 180/M_PI);
    Serial.print("Motor speed: ");
    Serial.println(motorSpeed);
  }

  stepper.runSpeed();
}

int setMotorSpeed() {
  // Proportional control
  angleCurrent = ypr[2];
  speedSet = constrain(-angleCurrent*k_proportional*speedMax, -speedMax, speedMax);
  return speedSet;
}

Edit: Adding my code which limits the sensor logic to the same interval as the speed update, based on the answer by chrisl. The cart moves quite a bit faster, though still not fast enough to keep the pendulum upright.
#include "I2Cdev.h"
#include <AccelStepper.h>
#include "MPU6050_6Axis_MotionApps20.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 mpu;

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// Defines pins numbers
const int stepPin = 3;
const int dirPin = 4;
AccelStepper stepper(1,stepPin,dirPin);

int motorSpeed, currentPos;
unsigned long t_start, t_elapsed, t_mpu, t_start_mpu;
int interval = 50; // ms between printing speed
unsigned long count = 0;

int speedMax = 800;
float k_proportional = 3;

float angleCurrent, speedSet;

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
      Wire.begin();
      Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
  #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
      Fastwire::setup(400, true);
  #endif

  Serial.begin(115200);

  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);

  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
      // turn on the DMP, now that it's ready
      Serial.println(F("Enabling DMP..."));
      mpu.setDMPEnabled(true);

      // enable Arduino interrupt detection
      Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
      mpuIntStatus = mpu.getIntStatus();

      // set our DMP Ready flag so the main loop() function knows it's okay to use it
      Serial.println(F("DMP ready! Waiting for first interrupt..."));
      dmpReady = true;

      // get expected DMP packet size for later comparison
      packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
      // ERROR!
      // 1 = initial memory load failed
      // 2 = DMP configuration updates failed
      // (if it's going to break, usually the code will be 1)
      Serial.print(F("DMP Initialization failed (code "));
      Serial.print(devStatus);
      Serial.println(F(")"));
  }

  stepper.setMaxSpeed(speedMax);
  stepper.setAcceleration(10000);
  stepper.setSpeed(100);
}

void loop() {

  t_elapsed = millis() - t_start;
  count += 1;

  if (t_elapsed >= interval) {
    t_start += interval;

    // wait for MPU interrupt or extra packet(s) available
    // Slows down cart tremendously, but code freezes without it
    while (!mpuInterrupt && fifoCount < packetSize) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)

    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
      // wait for correct available data length, should be a VERY short wait
      while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

      // read a packet from FIFO
      mpu.getFIFOBytes(fifoBuffer, packetSize);

      // track FIFO count here in case there is > 1 packet available
      // (this lets us immediately read more without waiting for an interrupt)
      fifoCount -= packetSize;

      // display Euler angles in degrees
      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    }

    motorSpeed=setMotorSpeed();
    // Use one potentiometer to turn system on or off (A0)
    int A0val = analogRead(A0);
    // Use another potentiometer to tune response time (or max speed)
    int A1val = analogRead(A1);
    //speedMax = 2*A1val;
    interval = A1val/2;
    Serial.print("Roll: ");
    Serial.print(ypr[2] * 180/M_PI);
    Serial.print(", motor speed: ");
    Serial.print(motorSpeed);
    Serial.print(", A0: ");
    Serial.print(A0val);
    Serial.print(", interval: ");
    Serial.print(interval);
    //Serial.print(", speedMax: ");
    //Serial.print(speedMax);
    Serial.print(", iterations: ");
    Serial.println(count);
    count=0;
    if (A0val > 512)
      stepper.setSpeed(motorSpeed);
    else
      stepper.setSpeed(0);
  }

  stepper.runSpeed();
}

int setMotorSpeed() {
  // Proportional control
  angleCurrent = ypr[2];
  speedSet = constrain(-angleCurrent*k_proportional*speedMax, -speedMax, speedMax);
  return speedSet;
}

how about, did you manage to finish the project?

I cannot say, why that principle works for the author of that tutorial. Though I can guess the reason, why your motors runs so slow.
The function, that actually drives the motor, is stepper.runSpeed(). You call it exactly once at the end of the loop() function. Though that function is designed to be called very often, as it only checks, if it is time to do a step, and then do so. It just an do max 1 step per execution. So you get 1 step per loop() iteration.
And at the start of the loop() you wait for the MPU data to be ready with this line:
while (!mpuInterrupt && fifoCount < packetSize)

So you do the steps at max with the same rate, that you read the MPU. That seems to be not enough for your setup.
You can try calling the runSpeed() function more often (and with that removing the limit on the steps). Either rewrite your code to only do the MPU communication, if the MPU data is ready, and proceed with the other code otherwise. Or you can insert the runSpeed() function into the while loops, that are waiting for the MPU data. The first option would be cleaner and would make the code easier to extent.

That makes sense, thanks. My solution was to put all the MPU reading code inside the if (t_elapsed >= interval) block so that the sensor values are only read at set intervals and runSpeed() gets called every step. My cart speed is still slower than it is without the MPU (around 2/3 as fast), but it's much closer now. I'm still unsure how to get a smooth, fast speed -- I think my max right now is around 200 rpm, and setting the motor speed above around 1000 gives me trouble, but at least it's in the ballpark now.