text:
UART between arduino UNO and pc via USB not in sync
I connected my arduino uno to my system and then using serial tried writing and reading data but there is a problem which I found when I tried giving arduino crafted messages.
My arduino code is pretty simple.
void setup() {
  Serial.begin(115200);

}

void loop() {
  if (Serial.available() > 0) {
    String data = Serial.readStringUntil('\n');
    Serial.print(" You sent me: ");
    Serial.println(data);
  }
}

and my python code on my system
#!/usr/bin/env python3
import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
    ser.flush()

    while True:
        string=input("Enter the string: ")
        ser.write(str.encode(string))
        line = ser.readline().decode('utf-8').rstrip()
        print(line)
        time.sleep(0.01)

Now this gives me ability to write instructions to my arduino but following sequences of communication occur
└──╼ $python3 serial_communication.py
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v
Enter the string: d

Enter the string: r
 You sent me: sd
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds
Enter the string: r
 You sent me: e
Enter the string:

Looking at them I understand that this might be a problem with my code or I am using the wrong protocol.

please format your code

Does this answer your question? Python - Arduino communication not reliable

I don't know Python, but from the behavior you show I am willing to bet that the input() function does not preserve the terminating \n.

using the serial monitor solves the issue but still why arduino gives delayed message of redundant data

There's a number of things going on here that combined give you the results you're seeing.
First off there's the delay at the start:
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v

This is because when you first open the serial port the Arduino resets and enters the bootloader. Thus the first few things that get sent are discarded, and nothing is sent back from the Arduino - your sketch just isn't running at that point.
Next is the format of what you're sending compared to how you're receiving it.
You input a string and then send that string verbatim.  But on the Arduino you are reading all data up until a terminating newline character, which you are not sending.
But the reading function also has a timeout in it so it will return whatever it has managed to read in that time even if the terminator hasn't arrived. That timeout is 1 second by default.
So everything that gets sent within a 1 second window gets grouped together, which is what you see here:
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds

The "out of sync" appearance is because of that 1 second timeout - you are seeing what was sent a second ago.
The fix is simple enough: make sure that you send the terminating newline character from Python:
ser.write(str.encode(string + "\n"))

And wait a few seconds after starting your program and opening the serial port before asking for anything to be sent. Maybe add a time.sleep(2) after opening the port to enforce that delay.

Thank you for the answer.
This really helps as my target was something else to get to work but as this is the starting point I did not want my concepts to get messed up.


text:
Switched from 3ft to 10ft connection wires. My setup doesnt run correctly now. Timing issues?
Running a DC motor(6.5A max input), motor driver (MD10C 7Amp peak output), and Arduino Mega. I am stabilizing an object with an accelerometer as my sensor. I switched to longer wires so I can have my board next to me and the stabilized object far away. Now I believe there are timing issues because of this. How would I fix this? How would i test to see how long it takes to travel through my wires?
I can add my code if that helps.

The extra 2 m of wires will delay the signals by about 10 ns. 2. A schematic of your setup might help.

@EdgarBonet I have edited my original post with wiring setup

I2C over long wires is bad. Very bad. You mustn't do it. Not without an I2C repeater / extender.

@EdgarBonet is the repeater/extender a physical thing or something in the code

@ThunderDornhofer I'm Majenko not EdgarBonet :P and it's a physical thing. I think Maxim do some.

@Majenko oh my bad oops. okay I will have to look into that. thank you

The pins of logic chips and processors are not line drivers and will not operate properly when used as such. Sometimes you may get lucky but that generally would be intermittent in operation. They make drivers to drive wires off board from the controller and other chips that are receivers on the other end. This needs to be done with each digital line. There are some specialty drivers such as I2C repeater chips, RS485 etc. Remember the wires are antennas and the system is operating at a high enough frequency to be a great radio transmitter. The main thing is to isolate the controller wires from the world.

Okay thank you!

A better solution would be to get a Pololu Wixel and companion shield for your Mega, and then put the Mega near the object.  You can then program the Mega wirelessly and completely avoid problems with long signal lines.  See this post for how I used it on one of my wall-following robots.  You'll need two Wixels and one Wixel shield.  They aren't particularly cheap, but you won't regret getting them.
There are other options for wireless control and programming, using Bluetooth rather than a proprietary protocol, but they aren't as easy to implement as the Wixel method.

I ended up putting everything close and then using a relay attached to my switch which is on a smaller signal wire. Runs great now. I think what I am doing is basically the wired version of what you were saying above. I like your idea better than what I am doing though, I am going to look into that and try to implement it, thank you!

Would one wixel be on my computer and the other on the wixel shield which is on my mega? and is communicates through the two wixels?

yes, exactly.  The two wixels form a 'wireless serial bridge' so the two ends (your PC and the Mega) don't know they aren't wired together with the normal USB cable.  Of course, this requires that the Mega have a separate power supply, as it will no longer have +5 & GND available via the USB cable

source: Stack Exchange

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

sort: votes


text:
Does anyone know code for a filter that bypasses small vibrational movements in my accelerometer input data
So basically I have a DC motor that is self stabilizing a platform using an accelerometer as its input. When i hit the table, everything freaks out and the platform moves rapidly back and forth for a little bit. I would like to know if anyone has some sort of code that would filter this out.
Here is my code:
//Code for accelerometer controlling an encoded DC
#include <Encoder.h>
#include <Wire.h>
#include <MPU6050.h>
//#include <QueueArray.h>

//Class to read the encoder
Encoder myEnc(19,18);

//I2C address of the MPU-6050
const int MPU_addr=0x68;

const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 200 Hz              = 1250
const uint16_t t1_comp = 1250;

// Buffered data for sending/receiving to/from the ISR
volatile bool isr_flag = false;  //Used to flag when the ISR when triggered
volatile unsigned long isr_time = 0;  //Input updated by ISR
volatile byte isr_motor_direction; //Output calculated and updated in loop()
volatile byte isr_motor_speed = 0; // Output calculated and updated in loop()

//initializing the MPU6050 (accel/gyro input)
MPU6050 sensor;

//accerleromter in the y direction
int16_t AcY;
//not using
int16_t AcX, AcZ, GyX, GyY, GyZ, Tmp;

//new varible for mapping the accelerometer to degrees
int yAng;

//Variables to create PID method
int currentTheta;
float error;
int dt = 5;
long integral=0;
long deriv;
int previousError;

//accel on light, always want it at 0
int setpoint = 0;

//change speeds of the motor
#define MOTOR_SPEED_PIN    3
//change direction of the motor
#define MOTOR_DIRECTION_PIN   2
#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //Disable global interrupt
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);

  Serial.begin(9600);

  pinMode(MOTOR_SPEED_PIN, OUTPUT);
  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);

  sensor.initialize();
}

void loop()
{
    //Begin critical section
    //

    cli();
    bool flag = isr_flag; //Copy the ISR flag
    isr_flag = false; //Reset the ISR flag
    sei();

    //
    //End critical section

    if (flag == true)
    {
      DebugMsgTime("PID algorithm begin");

      //Begin critical section
      //

      //Getting a copy of the data that has been modified by the ISR
      cli();
      unsigned long time = isr_time;
      sei();

      //
      //End critical section

      static unsigned long previous_time = 0;
      previous_time = time;

      //Wire reading

      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);

      //reading each of the 6 axis's of the MPU6050 and the temp
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      //Only using AcY
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();

      //mapping AcY to yAng from accel units to degrees
      yAng = map(AcY, -17000, 17000, -90, 90);

      //Calculate motor parameters locally

      long pos = PID(yAng);
      byte motor_direction = pos > 0 ? MOTOR_DIRECTION_CW : MOTOR_DIRECTION_CCW; //make sure that this is correct
      pos = abs(pos);
      pos = constrain(pos, 0, 100);
      byte motor_speed = map(pos, 0, 100, 0, 220);

      Serial.print(yAng);
      Serial.print(",");
      //Begin Critical Section
      //

      // Update the ISR data ready for output at the next interrupt.
      // This keeps the outputs locked to each other and synchronised to the interrupt.
      cli();
      isr_motor_direction = motor_direction;
      isr_motor_speed = motor_speed;
      sei();

      //
      //End Critical Section

      DebugMsgTime("PID algorithm end");
    }
}

ISR(TIMER1_COMPA_vect)
{
  //Output
  digitalWrite(MOTOR_DIRECTION_PIN, isr_motor_direction);
  analogWrite(MOTOR_SPEED_PIN, isr_motor_speed);

  //Input
  isr_time = micros();
  isr_flag = true;
}

//PID loop to find error between setpoint and currentTheta
long PID(int currentTheta)
{
    error = setpoint - currentTheta;
    integral = integral + error*dt;
    deriv = (error-previousError)/dt;
    long output = 2.4 * error + .01 * integral + 3.3 * deriv; //2.4; .01, 3.3
    //Serial.print(output);
    //Serial.print(",");
    //Serial.println(isr_time);
    previousError = error;
    return output;
}

void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = micros();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}

The code below is in the setup()
 for (int i = 0; i < 10; i++)
  {
    queue.enqueue(0);
    queue2.enqueue(0);
  }

The code below is apart of the averaging that is in the loop
if (firstQueue)
    {
        queue.dequeue();
        queue.enqueue(yAng);

      for (int i = 0; i < 10; i++) // copy the queue over
      {
        tempVal = queue.peek();
        sum = sum + tempVal;
        queue2.enqueue(tempVal);
        queue.dequeue();
      }
        yAngAverage = sum / 10;
        float pos = PID(yAngAverage);
        setMotor(pos);
        yAngAverage = 0;//set average back to 0
        firstQueue = false;
    }
    else
    {
        queue2.dequeue();
        queue2.enqueue(yAng);
      for (int i = 0; i < 10; i++) // copy the queue over
      {
        tempVal = queue2.peek();
        sum = sum + tempVal;
        queue.enqueue(tempVal);
        queue2.dequeue();
      }
        yAngAverage = sum / 10;
        float pos = PID(yAngAverage);
        setMotor(pos);
        yAngAverage = 0;//set average back to 0
        firstQueue = true;
    }
  sum = 0;
  tempVal = 0;*/
  }

Basically it created two different queues and would switch between them averaging 10 numbers and using that as my new input value. Way too slow

try averaging the readings .... or read 5 times and discard highest and lowest

ill update my code so you can see my averaging code beneath it. It made it super duper slow. Like the code would barely work.

Without spending hours going through your code it appears the PID gain is to high. Also slow down the motor response. Be aware different motors will act different.

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


text:
My motor driver gets stuck in either high or low with a certain speed super randomly. Motor output stops going based on accelerometer input
Running a DC motor(6.5A max input), motor driver (MD10C 7Amp peak output), and arduino Mega.
Basically, I am creating a stabilized object based on the accelerometer's input. It works great but all of a sudden, very randomly, it glitches and gets stuck in whatever mode it was in last, so if it was motor A HIGH and motor B LOW at speed 200, itll just do that and I have to unplug it, put in a blank code, then my code again, then start it, itll work great then do it all over again. The time it takes for it to glitch out is random, I can't seem to find any patterns to it.
here is my code
//Code for accelerometer controlling an encoded DC
#include <Encoder.h>
#include <Wire.h>
#include <MPU6050.h>
#include <QueueArray.h>

//Class to read the encoder
Encoder myEnc(19,18);

//I2C address of the MPU-6050
const int MPU_addr=0x68;

const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 200 Hz              = 1250
const uint16_t t1_comp = 1250;

// Buffered data for sending/receiving to/from the ISR
volatile bool isr_flag = false;  //Used to flag when the ISR when triggered
volatile unsigned long isr_time = 0;  //Input updated by ISR
volatile byte isr_motor_direction; //Output calculated and updated in loop()
volatile byte isr_motor_speed = 0; // Output calculated and updated in loop()

//initializing the MPU6050 (accel/gyro input)
MPU6050 sensor;

//accerleromter in the y direction
int16_t AcY;
//not using
int16_t AcX, AcZ, GyX, GyY, GyZ, Tmp;

//new varible for mapping the accelerometer to degrees
int yAng;

//Variables to create PID method
int currentTheta;
float error;
int dt = 5;
long integral=0;
long deriv;
int previousError;

//accel on light, always want it at 0
int setpoint = 0;

//change speeds of the motor
#define MOTOR_SPEED_PIN    3
//change direction of the motor
#define MOTOR_DIRECTION_PIN   2
#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //Disable global interrupt
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);

  Serial.begin(9600);

  pinMode(MOTOR_SPEED_PIN, OUTPUT);
  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);

  sensor.initialize();
}

void loop()
{
    //Begin critical section
    //

    cli();
    bool flag = isr_flag; //Copy the ISR flag
    isr_flag = false; //Reset the ISR flag
    sei();

    //
    //End critical section

    if (flag == true)
    {
      DebugMsgTime("PID algorithm begin");

      //Begin critical section
      //

      //Getting a copy of the data that has been modified by the ISR
      cli();
      unsigned long time = isr_time;
      sei();

      //
      //End critical section

      static unsigned long previous_time = 0;
      previous_time = time;

      //Wire reading

      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);

      //reading each of the 6 axis's of the MPU6050 and the temp
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      //Only using AcY
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();

      //mapping AcY to yAng from accel units to degrees
      yAng = map(AcY, -17000, 17000, -90, 90);

      //Calculate motor parameters locally
      long pos = PID(yAng);
      byte motor_direction = pos > 0 ? MOTOR_DIRECTION_CW : MOTOR_DIRECTION_CCW //make sure that this is correct
      pos = abs(pos);
      pos = constrain(pos, 0, 100);
      byte motor_speed = map(pos, 0, 100, 0, 200);

      //Begin Critical Section
      //

      // Update the ISR data ready for output at the next interrupt.
      // This keeps the outputs locked to each other and synchronised to the interrupt.
      cli();
      isr_motor_direction = motor_direction;
      isr_motor_speed = motor_speed;
      sei();

      //
      //End Critical Section

      DebugMsgTime("PID algorithm end");
    }
}

ISR(TIMER1_COMPA_vect)
{
  //Output
  digitalWrite(MOTOR_DIRECTION_PIN, isr_motor_direction);
  analogWrite(MOTOR_SPEED_PIN, isr_motor_speed);

  //Input
  isr_time = micros();
  isr_flag = true;
}

//PID loop to find error between setpoint and currentTheta
long PID(int currentTheta)
{
    error = setpoint - currentTheta;
    integral = integral + error*dt;
    deriv = (error-previousError)/dt;
    long output = 1.9 * error; + .8 * integral + 40 * deriv; //2.8,.7,70 //1.3,.8,40
    previousError = error;
    return output;
}

void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = micros();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}

What is that while loop for? I cannot see any sense in it, considering, that you don't have any other code inside void loop(), but outside of the while loop, and void loop() is already looping. Also you seem to be reading the raw accelerometer data, which can be quite noisy. You can use a complementary filter to do sensor fusion with the gyroscope and get more stable results. And lastly you are using a library for the MPU, but then you are reading the data directly via Wire, instead of using the libraries functions. Is there a reason for this?

How would I use a complementary? what would that look like?
Would using the library be better than reading directly from the wire? I thought they were one in the same.

You can google for the complementary filter. Basically you mix the acceleration with the integral of the gyroscope measurements to get a more stable reading. About the library: I think its  the same, was just curious why you are first using the library and then not.

What happens if the while condition fails? i.e. if millis() - time is greater than or equal to 20. Is this what you intended? If there's too much other stuff in the while loop, it may quit it and never re-enter it.
loop()
I've added a call to a function that prints debug information.
unsigned long time = 0;

void loop()
{
  DebugMsgTime("loop() begin");

  while (millis() - time < 20)
  {
    DebugMsgTime("while begin");

    time = millis();

    //delay(10);  // Short delay OK.
    delay(20);  // Long delay causes while loop to quit.

    DebugMsgTime("while end");
  }
  DebugMsgTime("loop() end");
}

DebugMsgTime()
This function prints a message along with the current time and the delta time since it was last called.
void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = millis();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}

Debug Output

It works great but all of a sudden, very randomly, it glitches and
gets stuck in whatever mode it was in last

Basic Encoder Test:
loop() begin
0
0
while begin  // It works great...
1
1
while end
2
1
while begin
12
10
while end
34
22           // but all of a sudden, very randomly, it glitches...
loop() end   // and gets stuck in whatever mode it was in last
54
20
loop() begin
74
20
loop() end
97
23
loop() begin
118
21
loop() end

As you can see, using this while loop is a very inaccurate way to generate regular sampling times.
loop() FIX
As @FerryBig pointed out in the comments, you need to change the time comparison < at the start of the loop. You also don't need the while loop because loop() is already called cyclically. Instead, put the time comparison in an if statement, something like this which gives you a rough 20 ms:
void loop()
{
  static unsigned long previous_time = 0;
  unsigned long time = millis();
  unsigned long delta_time = time - previous_time;

  if (delta_time >= 20)
  {
    previous_time = time;

    // Do PID algorithm.
  }
}

However, for a PID controller you may need more accuracy.
Timer Interrupt
A better method would be to use a timer interrupt to call an Interrupt Service Routine (ISR) at regular intervals. This ISR would do two simple things in this order:

Output: digitalWrite(motor_direction); and analogWrite(3, mtr2);
Input: set a flag that indicates that the gyro Wire needs reading.

Then, when the flag is set, the main loop() would read the gyro Wire, and calculate motor_direction and mtr2 in readiness for the next interrupt.
const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 10 Hz              = 25000
const uint16_t t1_comp = 25000;

volatile bool isr_flag = false;       // Used to flag when the ISR has updated the data.
volatile unsigned long isr_time = 0;  // The data.

void setup()
{
  // Disable global interrupt
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Serial.begin(9600);
}

void loop()
{
  //
  // BEGIN CRITICAL SECTION (Atomic)
  //

  cli();
  bool flag = isr_flag;  // Copy the ISR flag.
  isr_flag = false;      // Reset the ISR flag.
  sei();

  //
  // END CRITICAL SECTION
  //

  Serial.println(flag);

  if (flag == true)
  {
    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Get a copy of the data that has been modified by the ISR.
    cli();
    unsigned long time = isr_time;
    sei();

    //
    // END CRITICAL SECTION
    //

    static unsigned long previous_time = 0;
    Serial.println(time - previous_time);
    previous_time = time;
  }

  delay(25);
}

ISR(TIMER1_COMPA_vect)
{
  //TCNT1 = t1_load;  // No need to reload here because it auto reloads.
  isr_time = micros();
  isr_flag = true;  // Indicate that new data is available.
}

PID Controller
This is the full implementation of the PID controller. It should give you a solid foundation to develop the PID algorithm for your motor, and to filter the gyro inputs.
//Code for accelerometer controlling an encoded DC
#include <Encoder.h>
#include <Wire.h>
#include <MPU6050.h>
#include <QueueArray.h>

//Class to read the encoder
Encoder myEnc(19, 18);

//I2C address of the MPU-6050 idk if i need
const int MPU_addr = 0x68;

const uint16_t t1_load = 0;

// Timer1 compare value:
// Clock frequency / Prescaler / Required frequency = Compare value
// 16 MHz          / 64        / 10 Hz              = 25000
//const uint16_t t1_comp = 25000;

// If the PID algorithm takes less than 5 ms, it's possible to run Timer1 at a maximum of about 200 Hz.
// 16 MHz          / 64        / 200 Hz             = 1250
const uint16_t t1_comp = 1250;

// Buffered data for sending/receiving to/from the ISR.
volatile bool          isr_flag = false;            // Used to flag when the ISR has triggered.
volatile unsigned long isr_time = 0;                // Input updated by ISR.
volatile byte          isr_motor_direction = LOW;   // Output calculated and updated in loop().
volatile byte          isr_motor_speed = 0;         // Output calculated and updated in loop().

//initializing the MPU6050 (accel/gyro input)
MPU6050 sensor;

//accerleromter in the y direction
int16_t AcY;
//not using
int16_t AcX, AcZ, GyX, GyY, GyZ, Tmp;

//new varible for mapping the accelerometer to degrees
int yAng;

//Variables to create PID method
int currentTheta;
float error;
int dt = 5;
long integral = 0;
long deriv;
int previousError;

//accel on light, always want it at 0
int setpoint = 0;

//this is the enable pin (PWM) to run speeds to the motor
#define MOTOR_SPEED_PIN         3

//change direction of the motor
// TODO: Check whether LOW and HIGH are correct.
#define MOTOR_DIRECTION_PIN     2
#define MOTOR_DIRECTION_CW      LOW
#define MOTOR_DIRECTION_CCW     HIGH

void setup()
{
  // Disable global interrupt.
  cli();

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  // Set to prescalar of 64
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B |= (1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupt
  sei();

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);

  Serial.begin(9600);
  Serial.println("Basic Encoder Test:");

  //pinMode(MOTOR_SPEED_PIN, OUTPUT);  // Not needed for analogWrite().
  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);

  sensor.initialize();
}

void loop()
{
  //
  // BEGIN CRITICAL SECTION (Atomic)
  //

  cli();
  bool flag = isr_flag;  // Copy the ISR flag.
  isr_flag = false;      // Reset the ISR flag.
  sei();

  //
  // END CRITICAL SECTION
  //

  //Serial.println(flag);

  if (flag == true)
  {
    DebugMsgTime("PID algorithm begin");

    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Get a copy of the data that has been modified by the ISR.
    cli();
    unsigned long time = isr_time;
    sei();

    //
    // END CRITICAL SECTION
    //

    static unsigned long previous_time = 0;
    //Serial.println(time);
    //Serial.println(time - previous_time);
    previous_time = time;

    //
    // Read gyro Wire.
    //

    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true);

    //reading each of the 6 axis's of the MPU6050 and the temp
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    //Only using AcY
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read();

    //mapping AcY to yAng from accel units to degrees
    yAng = map(AcY, -17000, 17000, -90, 90);

    //
    // Calculate motor parameters locally.
    //

    long pos = PID(yAng);
    byte motor_direction = pos > 0 ? MOTOR_DIRECTION_CW : MOTOR_DIRECTION_CCW;  // TODO: Check whether defines are correct.
    pos = abs(pos);
    pos = constrain(pos, 0, 100);
    byte motor_speed = map(pos, 0, 100, 0, 200);

    //
    // BEGIN CRITICAL SECTION (Atomic)
    //

    // Update the ISR data ready for output at the next interrupt.
    // This keeps the outputs locked to each other and synchronised to the interrupt.
    cli();
    isr_motor_direction = motor_direction;
    isr_motor_speed = motor_speed;
    sei();

    //
    // END CRITICAL SECTION
    //

    DebugMsgTime("PID algorithm end");
  }

  //delay(1);
}

ISR(TIMER1_COMPA_vect)
{
  // Output.
  digitalWrite(MOTOR_DIRECTION_PIN, isr_motor_direction);
  analogWrite(MOTOR_SPEED_PIN, isr_motor_speed);

  // Input.
  isr_time = micros();
  isr_flag = true;
}

//PID loop to find error between setpoint and currentTheta
long PID(int currentTheta)
{
  error = setpoint - currentTheta;
  integral = integral + error * dt;
  deriv = (error - previousError) / dt;
  long output = 1.9 * error + .8 * integral + 40 * deriv; //2.8,.7,70 //1.3,.8,40
  previousError = error;
  return output;
}

void DebugMsgTime(const char *msg)
{
  static unsigned long previous_time = 0;
  unsigned long time = micros();
  unsigned long delta_time = time - previous_time;
  previous_time = time;

  Serial.println(msg);
  Serial.println(time);
  Serial.println(delta_time);
}

And I think there might be a typo in your PID controller:
long PID(int currentTheta)
{
    ...
    long output = 1.9*error; + .8*integral + 40*deriv;
                           |
                         typo?

This is equivalent to:
    long output = 1.9*error;

Which is not a PID controller.

For some reason that needs to be there. If i dont have that semi colon there, it wont work.
I had that while loop to run it every 20 ms. I think someone else on here told me that using that way instead of delay was better. It made it so a time was controlling each run time instead of every time it got information.

@ThunderDornhofer The semicolon will end the expression there. So the rest of the line has no effect. What exactly do you mean by "if i don't have that semicolon there, it won't work"? How exactly does it now work?

@ThunderDornhofer, I've updated my post to show why your while loop doesn't work. A better method to generate regular time intervals is to use timer interrupts.

@ThunderDornhofer Your loop conditions actually seems reversed, if it is based on the Arduino blink without delay loop. https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay Your code works because you actually update time with the new values. tim's example doesn't include updating the time, which your code has

@Ferrybig, sorry, that was a sloppy copy-and-paste error when I updated my post. I've put the loop-breaking code back in now.

@tim the loop still breaks in the way you explained, but the loop is fixed by changing < to >, as that wil l prevent going into the loop for 20 MS< and only then go into the loop, resetting the "timer"

@Ferrybig, I agree, I was just about to follow-up my comment with if (currentMillis - previousMillis >= interval) from the tutorial you linked to. However, it's still not as accurate as a timer interrupt.

Thanks for the help. This made a lot of sense. I am going to try and fix this today.

@tim I believe i have attached an ISR interrupt? I followed a guys tutorial. I might be doing it wrong. I updated my original code if you could take a look at it. Thanks

@ThunderDornhofer, the timer code in setup() is good. I've added a code snippet to the Timer Interrupt section that will output the interrupt timings and it uses "critical sections" to retrieve data that has been modified by the ISR. But the code in your ISR takes for too much time to execute (over 3ms) which will interfere with the update of millis() because interrupts are disabled during an ISR and interrupts are used to update the counter that is read by 'millis()'. The maximum allowed is 2ms. The PID algorithm should be placed within the if statement in the loop().

@ThunderDornhofer, I've added a full implementation of the PID controller. There are a couple of TODO comments you need to verify are correct. Not sure what frequency you want to run the timer at, but I got about 200 Hz max. Hope that helps.

@tim Wow, tim that helped so much. It works great when I am moving my sensor, but still seems to glitch out causing me to have to press the reset button when the sensor is at rest, no motion. Do you have any idea what that might be or how to fix that? I have updated my code.

@tim Also side question, if i wanted to add more to this code such as buttons, would that output also go into the ISR method?

@tim It runs a lot better but after my tests, I have found that after a while, randomly, it will stop working yet again. When looking at the serial moniter, as it is runnning through the print statements, it reads "PID algorithm begin", then the time, then the delta time and then when it glitches it out, it stops and doesn't print "PID algorithm end


text:
I need help creating a code that moves a DC motor CW or CCW based off of 2 different buttons
I know I can make the motor move backwards and forwards with buttons but I don't want it to move at full speed. I want it to increment in very small amounts to where it can be adjusted very small amounts at a time. I should also be able to hold the button so it moves continuously. I also have a motor with an encoder on it. Maybe there is a way to use the numbers on the encoder to increment? so press the CW button and now the motor wants to move till the encoder reaches +10 from where it was at? I understand what I want to do, just need help getting there. Thanks
HERE IS THE CODE I FIGURED OUT THAT MAKES MY DC MOTOR INCREMENT CW AND CCW

#define MOTOR_DIRECTION_PIN   2
#define MOTOR_SPEED_PIN       3

#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //button inputs
  //pullup so we do not need to include a physical resistor
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);
  pinMode(MOTOR_SPEED_PIN, OUTPUT);

  Serial.begin(9600);

  Serial.println("test");
}

void loop()
{
  int pushedButtonOne = digitalRead(12);
  int pushedButtonTwo = digitalRead(13);

  if(pushedButtonOne == LOW)
  {
    Serial.println("Button number 1 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CCW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }

  else if(pushedButtonTwo == LOW)
  {
    Serial.println("Button number 2 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }
  else
  {
    Serial.println("nothing has been pushed");
  }

  //delay(100);

}

Your first problem is selecting a type of motor. I would suggest a stepper motor for what you want to do. Those let you control the motor's position in very small increments.

@DuncanC Yeah I have used stepper motor. There is another application I want to extend off of this and it led me to a DC motor. I want it to work for both

What do you mean with "until it reaches +10"? 10 encoder clicks? That wont work with a DC motor, unless it is a geared one. DC motors are made to spin, not to step. Use a stepper motor, if you want to step. You can still let it rotate continously

@chrisl yeah so say the motor turns on and its at position 0 on the encoder. If a button is pushed I could make the motor move CW(or CCW, just depends on whatever button i push) until the encoder reads 10 and then it turns the motor off or stops it? Is this something that could work?

Most encoders have more than 10 tics per full rotation. That means, that 10 tics might be like a half rotation. DC motors are not meant for such precision positioning. You can try it, but instead of a half rotation you might as well get a 3/4 or a full rotation (that depends on your motor). Also you need to calculate the timing with regard to the acceleration and deceleration of the motor. If your lowest count is in the range of a few full rotations, then it might work with a DC motor. If you want full tic precision, use a stepper motor.

@chrisl Okay, I will try that thank you

Here is the code i eventually figured out. It increments my DC Motor basically by activating it for a small amount of time in the direction of whichever button was pushed.
#define MOTOR_DIRECTION_PIN   2
#define MOTOR_SPEED_PIN       3

#define MOTOR_DIRECTION_CW    LOW
#define MOTOR_DIRECTION_CCW   HIGH

void setup()
{
  //button inputs
  //pullup so we do not need to include a physical resistor
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);

  pinMode(MOTOR_DIRECTION_PIN, OUTPUT);
  pinMode(MOTOR_SPEED_PIN, OUTPUT);

  Serial.begin(9600);

  Serial.println("test");
}

void loop()
{
  int pushedButtonOne = digitalRead(12);
  int pushedButtonTwo = digitalRead(13);

  if(pushedButtonOne == LOW)
  {
    Serial.println("Button number 1 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CCW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }

  else if(pushedButtonTwo == LOW)
  {
    Serial.println("Button number 2 has been pushed");
    digitalWrite(MOTOR_DIRECTION_PIN, MOTOR_DIRECTION_CW);
    analogWrite(MOTOR_SPEED_PIN, 50);
    delay(7);
    analogWrite(MOTOR_SPEED_PIN, 0);
  }
  else
  {
    Serial.println("nothing has been pushed");
  }

}

To formulate the comments into an answer:
In principle it is of course possible to put an encoder onto a DC motor shaft and then drive the motor, until you reach the desired position. But you won't get good precision or accuracy with this. You wrote

till the encoder reaches +10 from where it was at

Since most encoders have more than 10 tics per full rotation (you didn't specifiy how much yours has), this can mean  rotating only a fraction of a full rotation. Let's assume, that the encoder has 40 tics per full rotation. With 10 tics you have a quarter rotation. It seems you want precision in the range of about 1 tic.
DC motors are made for spinning relatively fast. They don't give you control over the position with steps. They mostly have very few coil/magnet combinations (for example just 2 coils, which are switched internally). Thus you have just an inert motor shaft, which is driven by the motor. It will need time to accelerate and to decelerate. With most motors, you may even get a half or full rotation, when you wanted only a quarter rotation (the 10 tics). Calculating the correct timings to get it any better will be not easy for relatively small reward. DC motors are not made for rotations below a small number of full rotations.
You could tackle that problem by using a geared DC motor. The shaft after the gears will run slower and thus have the explained problem not so badly. Then you have to live with the smaller speed.
Or you could go a more proper way and just use a stepper motor, which is made for small steps in the range of sub-full-rotation. It is a bit more difficult to drive (also depending on the driver circuit), but it gives you the position control, that you want. And to rotate continuously: A continuous rotation on a stepper motor is nothing else but step after step taken in fast succession (much like running is a fast succession of steps with your feet).

Note: The stepper motor does not have a feedback like an encoder on it. The motor driver will just drive the coils to step the motor. If the motor is stalled or if it is overloaded, you might loose some steps (meaning that the coils are driven for the steps, but the motor doesn't actually move). You could sense that with an additional encoder on the motor shaft. But in most cases that is not necessary. If you just make sure, that the motor is not overloaded at any time, you will be fine. Or you might not worry about some steps being lost sometimes, if the overall precision is good enough. That is your decision.

I actually somewhat figured it out doing a simpler way of just shutting the motor off after a short delay. Ill throw the code the made into my original post.


text:
motor driver shield covering ports for ultrasonic sensor
im new to arduino and am making an arduino car. the motor driver shield covers the ports (am connecting an ultrasonic sensor) and i know that we can connect it to the 'holes' on the motor driver shield (l293d) but i do not have a solder or header pins. there's a lockdown and i cannot get any of those. can i make a makeshift arrangement? (refer img): it is a little loose, is there any fix using jumper wires or any other arrangement? please let me know!

There is such a thing as home delivery you know...

my area is under strict lockdown, deliveries have been stopped

@majenko is there any other fix?

Do you have a breadboard available?

Of course any way will be very hacky and non-permanent. Often the pins of jumper wires are actually small pieces of thin folded metal. In that case you could try to unfold them a bit, to make them bigger. That might give them better grip in the holes. Otherwise you might be able to improvise something with materials, that you already have. You could try paper clips, which are typically a bit thicker, than jumper pins. It really depends, what types of conductive material you have. You cannot really advice you further, since the standard way is not possible for you currently.

try this .... push the pin through the hole as far as it will go ... use pliers to flatten the end of the pin .... gently pull the pin back out of the hole (or push pin from back of board) ... it should bind because of the flattening ... experiment with the amount of flattening required .... start with slight flattening and keep increasing in small amounts

You might also try very small machine screws and nuts, if you can find any. You'd put a screw and nut through one of the breadboard holes, and then wrap a bare wire around the screw. When you tighten down the nut on the screw it should press the wire against the pad on the breadboard. For this to work you will need really tiny screws however.

Your home is in such tight lockdown that you can't take deliveries, even those left on your porch?

You really need a soldering iron with some electronics solder, and ideally some headers. Anything you try and do without a soldering iron is going to be a hacky, poor solution. I would focus on finding a way to get ahold of a soldering iron. Perhaps someone in walking distance of your home has one they can leave at their front door for you to borrow?

@DuncanC your comment about the screws gave me an idea ... put thin wire through the hole and jam the end of a toothpick through the hole next to the wire ... that should hold the wire fairly tight

True. Especially if you can use the tapered ends of round toothpicks. However, they are going to be prone to falling out.


text:
Checksum is wrong - Air Quality Monitoring Station PMS5003, BME280 | Code review
I working at air quality station. I measure particulate matter with PMS5003 and meteorological parameters with BME280. Everything seems to work just fine, but sometimes program hangs on checksum calculations.

I wonder if the problem lies either in my software or in hardware. Can anyone have a look at my code and tell me how I can improve it. Thanks in advance :)
Here's my code:

#include <Arduino.h>
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

// needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <PubSubClient.h>
#include <Wire.h>
#include <SPI.h>

// BME280 Sensor
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

//Constants
#define TOKEN "TOKEN"
char thingsboardServer[] = "SERVER_ADDRESS";

// Settings for PMS5003
#define LENG 31  //0x42 + 31 bytes equal to 32 bytes
#define TIMEOUT 10000 //Microseconds to wait for PMS do wakeup

unsigned char buf[LENG];
char ergebnisstr[50];

struct dustvalues {
 unsigned int PM10Val=0; // Byte 4&5
 unsigned int PM2_5Val=0; // Byte 6&7
 unsigned int PM01Val=0; // Byte 8&9
 unsigned int Beyond03=0; // Byte 16&17
 unsigned int Beyond05=0; // Byte 18&19
 unsigned int Beyond1=0; // Byte 20&21
 unsigned int Beyond2_5=0; // Byte 22&23
 unsigned int Beyond5=0; //Byte 24&25
 unsigned int Beyond10=0; //Byte 26&27
};

struct dustvalues dustvalues1, dustvalues2;

//unsigned char gopassive[]={ 0x42, 0x4d, 0xe1, 0x00, 0x00, 0x01, 0x70 }; //don't need here
//unsigned char readinpassive[]={ 0x42, 0x4d, 0xe2, 0x00, 0x00, 0x01, 0x71 };
unsigned char gosleep[]={ 0x42, 0x4d, 0xe4, 0x00, 0x00, 0x01, 0x73 };
unsigned char gowakeup[]={ 0x42, 0x4d, 0xe4, 0x00, 0x01, 0x01, 0x74 };

// BME280 init
Adafruit_BME280 bme;

// Connection to PubSubClient
WiFiClient espClient;
PubSubClient client(espClient);

int status = WL_IDLE_STATUS;
unsigned long lastSend;

void setup() {
    Serial.begin(9600);
    WiFiManager wifiManager;

    wifiManager.autoConnect("AP", "pass");
    Serial.println("Connected to the network :)");
    delay(500);
    //  pins for RGB diode
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(14, OUTPUT);
    //BME280 sensor check
    if (! bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
    }
    // set server for MQTT PubSubClient Library
    client.setServer( thingsboardServer, 1883 );
    lastSend = 0;

}

void loop() {

    if (!client.connected()) {
    reconnect();
    }
    if ( millis() - lastSend > 30000 ) { // Update and send only after 1 seconds
    getpms5003();
    getAndSendTemperatureAndHumidityData();
    lastSend = millis();
    }
    client.loop();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Connecting to ThingsBoard node ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("Stacja3", TOKEN, NULL) ) {
      Serial.println( "[DONE]" );
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 5 seconds]" );
      // Wait 5 seconds before retrying
      delay( 5000 );
    }
  }
}

void getAndSendTemperatureAndHumidityData()
{
  Serial.println("Collecting temperature data.");

  // Reading temperature or humidity takes about 250 milliseconds!
  float humidity = bme.readHumidity();
  // Read temperature as Celsius (the default)
  float temperature = bme.readTemperature();

  float pressure = bme.readPressure() / 100.0;

  // Check if any reads failed and exit early (to try again).
  if (isnan(humidity) || isnan(temperature) || isnan(pressure)) {
    Serial.println("Failed to read from BME sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print(" *C ");
  Serial.print("Pressure: ");
  Serial.print(pressure);
  Serial.print("hPa");

  String temperature1 = String(temperature);
  String humidity1 = String(humidity);
  String pressure1 = String(pressure);

  // Just debug messages
  Serial.print( "Sending temperature, humidity & pressure : [" );
  Serial.print( temperature1 ); Serial.print( "," );
  Serial.print( humidity1 ); Serial.print( "," );
  Serial.print( pressure1 );
  Serial.print( "]   -> " );

  // Prepare a JSON payload string
  String payload = "{";
  payload += "\"temperature\":"; payload += temperature1; payload += ",";
  payload += "\"humidity\":"; payload += humidity1;  payload += ",";
  payload += "\"pressure\":"; payload += pressure1;
  payload += "}";

  // Send payload
  char attributes[150];
  payload.toCharArray( attributes, 100 );
  client.publish( "v1/devices/me/telemetry", attributes );
  Serial.println( attributes );
}

bool checkValue(byte *buf, byte leng){
    int receiveSum, checkSum;
    for(byte i = 0; i < (leng - 2); i++){
        receiveSum += int(buf[i]);
    }
    receiveSum += 0x42;
    checkSum = (buf[leng-2] << 8) + buf[leng-1];
    testCheckValue(receiveSum, checkSum);
    if(receiveSum == checkSum){
        return true;
    }
    return false;
}

void testCheckValue(int calc, int found){
    byte strSize = 64;
    char strOut[strSize];
    snprintf(strOut, strSize, "Checksum Calculated: %d\nChecksum Found: %d\n", calc, found);
    Serial.print(strOut);
}

unsigned int transmitPM(char HighB, char LowB, unsigned char *buf){
 unsigned int PMValue;
 PMValue=((buf[HighB]<<8)+buf[LowB]);
 return PMValue;
}

void getpms5003(void){
  unsigned char found=0;

  Serial.println("PMS5003 Wakeup: ");
  Serial.write(gowakeup,7);
  Serial.println();
  Serial.println("gowakeup ist out");
  delay(30000); //Stable data should be got at least 30 Second from wakeup (Datasheet!)
  while (found<2){
   delay(TIMEOUT);
   if(Serial.available()>0){
    if(Serial.find(0x42)){  //start to read when detect 0x42
     Serial.println("0x42 found");
     Serial.readBytes(buf,LENG);
     if (buf[0] == 0x4d){ //second byte should be 0x4D
       found++;
       if(checkValue(buf,LENG)){
        Serial.println("Checksum okay");

        if(found==1){
         dustvalues1.PM01Val=transmitPM(3,4,buf);
         dustvalues1.PM2_5Val=transmitPM(5,6,buf);
         dustvalues1.PM10Val=transmitPM(7,8,buf);

         if (dustvalues1.PM2_5Val <= 36) {
           // digtal write green pin
           digitalWrite(12, LOW);
           // digitalWrite(13, HIGH);
           digitalWrite(14, HIGH);
         }

         if ((dustvalues1.PM2_5Val > 36 ) && (dustvalues1.PM2_5Val <= 80)) {
           // diode change to yellow
           digitalWrite(12, LOW);
           // digitalWrite(13, HIGH);
           digitalWrite(14, LOW);
         }

         if(dustvalues1.PM2_5Val > 84) {
           // diode change to red
           digitalWrite(12, HIGH);
           // digitalWrite(13, HIGH);
           digitalWrite(14, LOW);
         }

         sprintf(ergebnisstr,"PM2.5:%4dug/m3\nPM10: %4dug/m3\n",dustvalues1.PM2_5Val,dustvalues1.PM10Val);
         Serial.println(ergebnisstr);
         Serial.flush();

         // Just debug messages
         Serial.print( "Sending air quality PM2.5 & PM10 values: [" );
         Serial.print( dustvalues1.PM2_5Val ); Serial.print( "," );
         Serial.print( dustvalues1.PM10Val);
         Serial.print( "]   -> " );

         // Prepare a JSON payload string
         String payload = "{";
         payload += "\"pm25\":"; payload += String(dustvalues1.PM2_5Val); payload += ",";
         payload += "\"pm10\":"; payload += String(dustvalues1.PM10Val);
         payload += "}";

         // Send payload
         char attributes[100];
         payload.toCharArray( attributes, 100 );
         client.publish( "v1/devices/me/telemetry", attributes );
         Serial.println( attributes );
       }
        if(found==2){
         dustvalues2.PM01Val=transmitPM(3,4,buf);
         dustvalues2.PM2_5Val=transmitPM(5,6,buf);
         dustvalues2.PM10Val=transmitPM(7,8,buf);
         sprintf(ergebnisstr,"PM1: %4dug/m3\nPM2.5:%4dug/m3\nPM10: %4dug/m3\n",dustvalues2.PM01Val,dustvalues2.PM2_5Val,dustvalues2.PM10Val);
         Serial.println(ergebnisstr);
         Serial.flush();
        }
      }else{
       Serial.println("Checksum not okay");
       Serial.flush();
       if(found>0)found--;
       delay(500);
      }
     }
   }
   }
   }

  found=0;
  Serial.println("PMS5003 - go to sleep");
  Serial.write(gosleep,7);
  Serial.println();
 }

My hardware:

PMS 5003 Datasheet - http://www.aqmd.gov/docs/default-source/aq-spec/resources-page/plantower-pms5003-manual_v2-3.pdf

Is the checksum function expecting to be run on an 8-bit CPU with only 16-bit integers? You have a 32-bit one there...

Cited from the documentation

Check code=Start character1+ Start character2+……..+data13 Low 8 bits

Please try to change the code as follows:
...
bool checkValue(byte *buf, byte leng){
    int receiveSum, checkSum;
    receiveSum += 0x42;
    for(byte i = 0; i < (leng - 2); i++){
        receiveSum += int(buf[i]);
        receiveSum = receiveSum & 0xFFFF;
    }

    checkSum = (buf[leng-2] << 8) + buf[leng-1];
    testCheckValue(receiveSum, checkSum);
    if(receiveSum == checkSum){
        return true;
    }
    return false;
}
...

Or use the updated code by the same author :PMS7003-on-Particle

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


text:
Funduino Uno with 5V 1A power supply?
Can I use a "Funduino Uno" arduino with power from a power bank with DC 5V 1A output?

Yes. As long as it connects the the arduino clone via USB and can maintain a stable power output then it's suitable.

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


text:
Arduino Uno Constantly Resets with WiFi and 4 Relay Module
I am using an Arduino Uno with a 4 relay module (found here: http://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTEN3TM?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o04_s00) and an Adafruit CC3000 WiFi breakout board.  However, once I connect the power source, the board just constantly cycles on and off, e.g. about 1 second per cycle.  Could this have to do with too much current being drawn? Or that the current output of the digital pins isn't enough for all of the relay inputs? I'm new with this, but I am sure all of the pins are appropriately connected.
EDIT: If I use the USB connector (5V 1A) instead of the external power supply, I can connect 1 or 2 of the relays without problem, but must do so AFTER the wifi has already connected to the network, otherwise the wifi chip will never connect.  Also, if I toggle the relays a few times, the wifi becomes unresponsive.  I suspect a current issue maybe?. Any ideas? Thanks!

It Will be a power issue you need to supply power direct to the relay modules VCC independent of the arduino, ensure the earths are connected and just use the digital outputs from the arduino to control the relays. Digital low normally switches the corresponding relay on.


text:
Arduino Uno + aRest + ESP8266
So, I can use the aRest library to program to the ESP8266 standalone, but if I have the ESP8266 connected to the Arduino Uno, can I still use the aRest library? Or will this no longer work?  I am trying to send a request to the Arduino unit that will toggle a pin to turn on/off via the aRest library.  Thanks!
aRest can be found here: https://github.com/marcoschwartz/aREST

Please edit your question. It currently needs more detail on what you are trying to achieve and is too broad and unclear what you are asking.

Why don't you just try it? :)
In overview of GitHub repo, first sentence, it says: "A simple library that implements a REST API for Arduino & the ESP8266 WiFi chip." Next paragraph confirms it.

It is for the chip itself, not when the chip is connected to the Arduino unit.  The chip can be a standalone microcontroller

If it works on Arduino unit itself, it can be made to work with ESP8266 for sure, right? Maybe just there it no ready code, you need to edit a bit.

It doesn't work on the Arduino itself, it works with a wifi chip like the CC3000 connected to the Arduino, or the ESP8266 standalone.  Haven't seen anything that has it using an ESP8266 connected to an Arduino


text:
Sparkfun ESP8266 Wifi Shield does not receive data
When I make any GET request to my shield, the only thing I get when I read the request is '\r\n'.  I am sending query parameters, and when the request has been read in the past, there was the full http request.
EDIT:  Could this be due to some memory issue?  It seems to be fairly non-deterministic when it fails, and I have 69% of memory taken when the program starts.
/************************************************************
ESP8266_Shield_Demo.h
SparkFun ESP8266 AT library - Demo
Jim Lindblom @ SparkFun Electronics
Original Creation Date: July 16, 2015
https://github.com/sparkfun/SparkFun_ESP8266_AT_Arduino_Library

This example demonstrates the basics of the SparkFun ESP8266
AT library. It'll show you how to connect to a WiFi network,
get an IP address, connect over TCP to a server (as a client),
and set up a TCP server of our own.

Development environment specifics:
  IDE: Arduino 1.6.5
  Hardware Platform: Arduino Uno
  ESP8266 WiFi Shield Version: 1.0

This code is released under the MIT license.

Distributed as-is; no warranty is given.
************************************************************/

//////////////////////
// Library Includes //
//////////////////////
// SoftwareSerial is required (even you don't intend on
// using it).
#include <SoftwareSerial.h>
#include <SparkFunESP8266WiFi.h>

//////////////////////////////
// WiFi Network Definitions //
//////////////////////////////
// Replace these two character strings with the name and
// password of your WiFi network.
const char mySSID[] = "ssid";
const char myPSK[] = "pass";

const short out1 = 10;
const short out2 = 11;
const short out3 = 12;
const short out4 = 13;

bool on1 = false;
bool on2 = false;
bool on3 = false;
bool on4 = false;

//////////////////////////////
// ESP8266Server definition //
//////////////////////////////
// server object used towards the end of the demo.
// (This is only global because it's called in both setup()
// and loop()).
ESP8266Server server = ESP8266Server(80);

//////////////////
// HTTP Strings //
//////////////////
const String html = "HTTP/1.1 200 OK\r\n"
                          "Content-Type: text/html\r\n"
                          "Connection: close\r\n\r\n"
                          "<!DOCTYPE HTML>\r\n"
                          "\r\n"
                          "<link rel=\"icon\" href=\"data:,\">\r\n"
                          "<button>Toggle 1</button>\r\n"
                          "<button>Toggle 2</button>\r\n"
                          "<button>Toggle 3</button>\r\n"
                          "<button>Toggle 4</button>\r\n"
                          "\r\n";

// All functions called from setup() are defined below the
// loop() function. They modularized to make it easier to
// copy/paste into sketches of your own.
void setup()
{
  // Set pins
  pinMode(out1, OUTPUT);
  pinMode(out2, OUTPUT);
  pinMode(out3, OUTPUT);
  pinMode(out4, OUTPUT);

  digitalWrite(out1, LOW);
  digitalWrite(out2, LOW);
  digitalWrite(out3, LOW);
  digitalWrite(out4, LOW);

  // Serial Monitor is used to control the demo and view
  // debug information.
  Serial.begin(9600);

  // initializeESP8266() verifies communication with the WiFi
  // shield, and sets it up.
  initializeESP8266();

  // connectESP8266() connects to the defined WiFi network.
  connectESP8266();

  // displayConnectInfo prints the Shield's local IP
  // and the network it's connected to.
  displayConnectInfo();

  serverSetup();
}

void loop()
{
  serverDemo();
}

void initializeESP8266()
{
  // esp8266.begin() verifies that the ESP8266 is operational
  // and sets it up for the rest of the sketch.
  // It returns either true or false -- indicating whether
  // communication was successul or not.
  // true
  int test = esp8266.begin();
  if (test != true)
  {
    Serial.println(F("Error talking to ESP8266."));
    errorLoop(test);
  }
  Serial.println(F("ESP8266 Shield Present"));
}

void connectESP8266()
{
  // The ESP8266 can be set to one of three modes:
  //  1 - ESP8266_MODE_STA - Station only
  //  2 - ESP8266_MODE_AP - Access point only
  //  3 - ESP8266_MODE_STAAP - Station/AP combo
  // Use esp8266.getMode() to check which mode it's in:
  int retVal = esp8266.getMode();
  if (retVal != ESP8266_MODE_STA)
  { // If it's not in station mode.
    // Use esp8266.setMode([mode]) to set it to a specified
    // mode.
    retVal = esp8266.setMode(ESP8266_MODE_STA);
    if (retVal < 0)
    {
      Serial.println(F("Error setting mode."));
      errorLoop(retVal);
    }
  }
  Serial.println(F("Mode set to station"));

  // esp8266.status() indicates the ESP8266's WiFi connect
  // status.
  // A return value of 1 indicates the device is already
  // connected. 0 indicates disconnected. (Negative values
  // equate to communication errors.)
  retVal = esp8266.status();
  if (retVal <= 0)
  {
    Serial.print(F("Connecting to "));
    Serial.println(mySSID);
    // esp8266.connect([ssid], [psk]) connects the ESP8266
    // to a network.
    // On success the connect function returns a value >0
    // On fail, the function will either return:
    //  -1: TIMEOUT - The library has a set 30s timeout
    //  -3: FAIL - Couldn't connect to network.
    retVal = esp8266.connect(mySSID, myPSK);
    if (retVal < 0)
    {
      Serial.println(F("Error connecting"));
      errorLoop(retVal);
    }
  }
}

void displayConnectInfo()
{
  char connectedSSID[24];
  memset(connectedSSID, 0, 24);
  // esp8266.getAP() can be used to check which AP the
  // ESP8266 is connected to. It returns an error code.
  // The connected AP is returned by reference as a parameter.
  int retVal = esp8266.getAP(connectedSSID);
  if (retVal > 0)
  {
    Serial.print(F("Connected to: "));
    Serial.println(connectedSSID);
  }

  // esp8266.localIP returns an IPAddress variable with the
  // ESP8266's current local IP address.
  IPAddress myIP = esp8266.localIP();
  Serial.print(F("My IP: ")); Serial.println(myIP);
}

void serverSetup()
{
  // begin initializes a ESP8266Server object. It will
  // start a server on the port specified in the object's
  // constructor (in global area)
  server.begin();
  Serial.print(F("Server started! Go to "));
  Serial.println(esp8266.localIP());
  Serial.println();
}

void serverDemo()
{
  // available() is an ESP8266Server function which will
  // return an ESP8266Client object for printing and reading.
  // available() has one parameter -- a timeout value. This
  // is the number of milliseconds the function waits,
  // checking for a connection.
  ESP8266Client client = server.available(500);

  if (client)
  {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    String req;
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        req += c;
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank)
        {
          Serial.println(req);
          if (req.indexOf("toggle=1") != -1){
            if (on1){
              Serial.println(F("TURN 1 ON"));
              digitalWrite(out1, LOW);
            }
            else {
              Serial.println(F("TURN 1 OFF"));
              digitalWrite(out1, HIGH);
            }
            on1 = !on1;
          }
          else if (req.indexOf("toggle=2") != -1){
            if (on2){
              digitalWrite(out2, LOW);
              Serial.println(F("TURN 2 OFF"));
            }
            else {
              Serial.println(F("TURN 2 ON"));
              digitalWrite(out2, HIGH);
            }
            on2 = !on2;
          }
          else if (req.indexOf("toggle=3") != -1){
            if (on3){
              Serial.println(F("TURN 3 OFF"));
              digitalWrite(out3, LOW);
            }
            else {
              Serial.println(F("TURN 3 ON"));
              digitalWrite(out3, HIGH);
            }
            on3 = !on3;
          }
          else if (req.indexOf("toggle=4") != -1){
            if (on4){
              Serial.println(F("TURN 4 OFF"));
              digitalWrite(out4, LOW);
            }
            else {
              Serial.println(F("TURN 4 ON"));
              digitalWrite(out4, HIGH);
            }
            on4 = !on4;
          }

          // send html
          client.print(html);
          break;
        }
        if (c == '\n')
        {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r')
        {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
  }

}

// errorLoop prints an error code, then loops forever.
void errorLoop(int error)
{
  Serial.print(F("Error: ")); Serial.println(error);
  Serial.println(F("Looping forever."));
  for (;;)
    ;
}

It's an issue using String with arduino.  I've changed to use char[] and now it is working fine.

In serverDemo() you are setting currentLineIsBlank to true. Then you are reading in each char until you get to a \n at which point you are assuming the http request has ended.
boolean currentLineIsBlank = true;
....

// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank)

I think you want to set currentLineIsBlank to false to begin with ?...

no it's true to begin with, because if we get a \n, then we are at the end of the first blank line.  If the first character is not \r or \n, then we set currentLineIsBlank = false because there is something on the line

have you tried checking (Serial.print(c)) the value of c after reading it from client.read();  What are you seeing here as the request coming in...

It's an issue with using String.  I've made a bunch of changes to switch from String to char[], and it is working, thanks for helping


text:
Ethernet Shield: Failed to configure Ethernet using DHCP
I am currently making a design that uses the Arduino's Ethernet shield. I am using the PushingBox API for Arduino, and have tried it with my Arduino Mega (2560) with the ethernet shield attached to the router. When I did this, however, it displayed a message on my serial monitor saying Failed to configure Ethernet using DHCP. The model for my Ethernet Shield is a W5200 Seeed Studio Ethernet Shield, and I am using the libraries that Arduino provides. I do not have an SD card inserted and the DHCP on all other wired devices works. Any help is greatly appreciated.
The code (in case):
#include <SPI.h>
#include <Ethernet.h>

  /////////////////
 // MODIFY HERE //
/////////////////
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x19 };   // Be sure this address is unique in your network

//Your secret DevID from PushingBox.com. You can use multiple DevID  on multiple Pin if you want
char DEVID1[] = "{[I have replaced this with my DevID]}";        //Scenario : "The mailbox is open"

//Numeric Pin where you connect your switch
uint8_t pinDevid1 = 3; // Example : the mailbox switch is connect to the Pin 3

// Debug mode
boolean DEBUG = true;
  //////////////
 //   End    //
//////////////

char serverName[] = "api.pushingbox.com";
boolean pinDevid1State = false;                // Save the last state of the Pin for DEVID1
boolean lastConnected = false;                 // State of the connection last time through the main loop

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

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Serial.println("Please reconfigure the settings and try again.");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }
  else{
    Serial.println("Ethernet ready");
    // print the Ethernet board/shield's IP address:
    Serial.print("My IP address: ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
}

void loop()
{
      ////
      // Listening for the pinDevid1 state
      ////
      if (digitalRead(pinDevid1) == HIGH && pinDevid1State == false) // switch on pinDevid1 is ON
      {
        if(DEBUG){Serial.println("pinDevid1 is HIGH");}
        pinDevid1State = true;
        //Sending request to PushingBox when the pin is HIGH
        sendToPushingBox(DEVID1);
      }
       if (digitalRead(pinDevid1) == LOW && pinDevid1State == true) // switch on pinDevid1 is OFF
      {
        if(DEBUG){Serial.println("pinDevid1 is LOW");}
        pinDevid1State = false;
        //Sending request to PushingBox when the pin is LOW
        //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable
      }

      //DEBUG part
      // this write the respons from PushingBox Server.
      // You should see a "200 OK"
      if (client.available()) {
        char c = client.read();
        if(DEBUG){Serial.print(c);}
      }

      // if there's no net connection, but there was one last time
      // through the loop, then stop the client:
      if (!client.connected() && lastConnected) {
        if(DEBUG){Serial.println();}
        if(DEBUG){Serial.println("disconnecting.");}
        client.stop();
      }
      lastConnected = client.connected();
}

//Function for sending the request to PushingBox
void sendToPushingBox(char devid[]){
  client.stop();
  if(DEBUG){Serial.println("connecting...");}

  if (client.connect(serverName, 80)) {
    if(DEBUG){Serial.println("connected");}

    if(DEBUG){Serial.println("sendind request");}
    client.print("GET /pushingbox?devid=");
    client.print(devid);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(serverName);
    client.println("User-Agent: Arduino");
    client.println();
  }
  else {
    if(DEBUG){Serial.println("connection failed");}
  }
}

If the code for the DHCP error is removed, it does display an external IP address, but actual HTTP requests do not work. I tried port forwarding and that did not work either.
EDIT:
Now, unusually, it gives me an IP address WITHOUT the ethernet cord connected.

can you get it working without all the pushingbox stuff?

No, not even the WebClient sample that Arduino provides works.

so what was the point of putting in all the pusingbox code?

also: how do you know you don't have a defective shield?

If you have connected directly to the router are you sure you have the right sort of cable.  Some older router/switches/hubs require crossed network cables.  Can you switch the cable with a cable that is connected to a device that you know is working?

@JayEye The point of the pushing box code is because I am trying to make a doorbell that sends notifications to my phone and computer. I don't know if I have a defective shield, but I do know that if I use WebClient and comment out the DHCP error, it does return a public IP address, but when I actually make an HTTP request, it says Connection failed. @Matt Both the iMac and the router display a public IP address, but when I go to the router's configuration, it doesn't appear to be connected on either the iMac or the router.

i meant, if you can't get it working at all, there was no point in posting the pushbox code. When you are trying to figure out what's wrong with a piece of code, you test individual pieces. If you are not confident that the network code is working, there is no point in including the pushbox code in the test!

The reason that I added the Pushingbox code was to state that I was using Pushingbox as a server to connect to. I didn't mean for it to be a big part of it, but even connecting with www.google.com doesn't work. Also, I have tested individual pieces. That is what I mean by the "Connection failed" part of the edit, was that the HTTP request part was displaying that, and I was confused on why it would be doing that. When I tested the actual Ethernet.begin(mac) part, it always showed Failed to configure Ethernet using DHCP, yet showed an external IP when I ignored that part.

If I understood your problem correctly then you might want to check this out,
it's more or less the same thing :D
DHCP Failing on Arduino Uno

The page is no longer available


text:
Help with Arduino Due and APA102 LED strip Vs Matrix
I am in a fix since last one week regarding this:
As mentioned in a previous question (asked here only), I have been working to develop a APA102 LED based display. Now for this I have an Arduino Due. The display area is non rectangular however there is a central rectangular region measuring 63 cm X 36 cm. I have managed to do everything from the software side however stuck with the hardware (first time, its mostly vice-versa!!). The confusion is this, 2 options that I have at my disposal:

Go for the APA102 144 LEDs/meter (high density required) strip and then use them to make the display. On doing a small approximate calculation, I found I would have close to 2500-2600 LEDs. My first question is that:
a. Can Arduino Due handle this? I also need to display static images (bitmaps) (forget animations) and perform fading. Would the refreshing be fast enough? I have some values from APA102 datasheet and Arduino Due but cannot make head or tail of it...I do not know how to find out time taken, data rate etc.
b. The other problem I have with this is that for the bitmap to be "perfect", the pixel pitch needs to be same. In vertical direction, this is not possible without cutting the strip along the length to reduce its width. This a damn tedious and useless job. This act along with the soldering and everything involved makes me go for option 2 (below).
I go for eight 8*32 APA102 flexible displays and arrange them in two columns so that to display the bitmap, I split the bitmap data into two 32*32 matrices and then pass them separately. this is because I cannot find the relation between the bitmap pixel index and the actual display index. The arrangement is like that. Here Also, my question is: Can Arduino Due deal with this a good refresh rate without flickering etc. (POV display req.) The problem with this option is that I can cover only the rectangular region of the area and I am left with some area which makes me feel guilty to see it not lighted whereas with strip I can cover the whole area and only display bitmaps for the rectangular area. Both options have serpentine arrangement. This option also has cleaner and easy construction.

Both options seem plausible to me but I really cannot decide which one is better. Confused! Please, any help, idea, guidance, advice...anything would be great. I would be ordering this stuff from aliexpress etc. and thus a wrong decision would be taxing on my pocket.
I would be glad to provide any other info if required.
Thanks!


text:
stream a "big" array of measures to a server through wifi
I'm measuring accelerations at "high frequency" (4kHz) from an accelerometer (ADXL355/ADXL357) to an esp32. It's crucial that no sample is lost while performing a measure which last say 2 seconds, thus I first record all the samples and then send the complete array of measures to a server over wifi knowing the IP and the port of the server.
The measures array is an int array of size 3bytes * 3axis * 4000Hz * 2seconds = 72000 bytes.
I tried to make an http server and send the measures array from the microcontroller to the server with a POST request and serializing the payload with json (ArduinoJSON library), but this is very costy in terms of memory, because I need to duplicate the array of measures and convert it to an array of strings.
Is there a better way to send this array over wifi to the server (some sort of stream?) optimizing the memory usage on the microcontroller? which arduino libraries may help in the task? could you link an example with code of a similar situation?

JSON is a format trivial to write: you do not need a library for this.
For example, an array of numbers could be serialized like this:
void serialize_array(Print &client, int *data, int count) {
    client.print('[');
    for (int i = 0; i < count; i++) {
        client.print(data[i]);
        client.print(i==count-1 ? ']' : ',');
    }
}

This would effectively stream the data without storing the JSON
representation in memory.

Thank you Edgar, what is the client parameter of type Print? Where could I find documentation on understanding how to set it for comunnicate with a given ip:port?

@AlekseyFedorovich: client would be an instance of HttpClient, or EthernetClient, or WiFiClient, or... whatever you are sending your data to. It could even be Serial if you just want to check the payload on the serial monitor. See the documentation of whatever you would use to send an HTTP request.


text:
wrong leds lit in matrix display - wrong coding?
I wrote the following code for displaying a bitmap (small size) on a  LED matrix (formed using APA102 led strip):
//for 24-bit bitmaps

// the header files for the RGB data

 #include <FastLED.h>
 #include "redarray.h"
 #include "greenarray.h"   //g data header file (hex or dec)
 #include "bluearray.h"   //b data header file (hex or dec)*/

//matrix parameters

#define MatrixWidth 36 //columns
#define MatrixHeight 7 //rows
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

 void setup() {

     FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
     FastLED.clear();
  }

void loop() {

  for(uint8_t x=0 ; x<MatrixWidth ; x++)  {

      for(uint8_t y=0; y < 3; y++) {

            leds[XY (x, y)].setRGB(redarray[x][y],greenarray[x][y],bluearray[x] [y]);

           FastLED.show();

           delay(1);
         }
      }
   }

      uint16_t XY( uint8_t x, uint8_t y)
 {
   uint16_t i;

     if( MatrixSerpentineLayout == true) {
       if( y & 0x01) {
        // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
     } else {
       // Even rows run forwards
          i = (y * MatrixWidth) + x;
    }
   }

  return i;
}

The following is the data in one of the header files - its of same type for the other two colors.
const unsigned char redarray[36][3] PROGMEM  = {
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
};
The matrix is in a serpentine form (evident from the XY function in code). I am using an Arduino Due. The problem is that the code compiles and runs...but the bitmap is incorrect. Although I am sure, I am somewhat along the correct path because some LEDs do light up as they should as per the bitmap. But most of them are wrongly lit.
Could you somebody plz guide where I am going wrong with the coding? I fear there is some mistake in reading the color data from array and allocating it to leds[XY(x,y)].I do not know how a 2D array is read or dealt with by Arduino.
Thanks!

Your code is hard to read.  Please try to indent is better.

Why is your LED matrix 36 by 7 but your array is 36 by 3?

@st2000 Insuffcient power supply. On taking all LEDs into use, it doesnt work, I am working on this power supply thing but for testing took 3 rows of 36 LEDs each. sorry for the improper code. Will edit it.

It might help if you created a test array that only lit 1 LED.  Then walked that LED through all positions.  Knowing when the lit LED does not appear in the expected location may provide hints as to where to look for problems in the array or your code.

Initialize your arrays like this:
int a[3][4] = {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

...you can read more about it here.
Added later...
The following explanation came from here:
Arrays that are not explicitly divided into rows:
int M[4][5] = {10, 5, -3, 9, 0, 0, 32, 20, 1, 0, 0, 8};

...are filled like this:
int M[4][5] =
{
  {10,  5, -3, 9, 0},
  { 0, 32, 20, 1, 0},
  { 0,  8,  0, 0, 0},
  { 0,  0,  0, 0, 0}
};

As only you understand your data you will have to verify if your data is populating the array as you expect.

the problem is that - the color data I generated is not in the format arduino wants 2D array to be declared. Its tedious to put everything in brackets like this and I somehow realised that this is not the way c++ reads arrays. I can just declare the array like charlie[] [] = { }; With no individual bracketing on the elements and it reads it correctly. And also when I did like you told me, I am getting this error - expected unqualified-id before .... and it took me 20 minutes to arrange data like this.....Is the reading of the color data and consequent allocation to LEDs correct????

..Thanks bro..As per your links of declaring an array, I managed  to get it working (after resolving some array indexing problem - here it is - https://arduino.stackexchange.com/questions/24103/what-does-this-error-mean-arduino-due-loop-warning  - I got it working now...the pattern is displayed....Thanks for links :)


text:
Make LED blink using AVR assembly
I have an ATmega328P Arduino and am trying to make the LED blink using assembly without any additional includes. The goal is to have it blink for 1 second on, then 1 second off, however, it blinks incredibly quickly and is barely perceptible. Am I doing something incorrectly?
; DDRB       = 0x04
; PORTB      = 0x05
; TCCROB     = 0x25
; TCNT0      = 0x26
; 0b00000000 = OFF
; 0b00100000 = ON

setup:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x04, r16           ; Set DDRB to output
    out 0x05, r16           ; Set PORTB to ON
    ldi r16, 0b00000101     ; Set r16 with prescaler 1024 value
    out 0x25, r16           ; Set the TCCROB to 1024
    ldi r20, 0              ; Reset r20
    ldi r21, 1              ; Hold value 1 to increment r20
loop:
    in r17, 0x26            ; Read the timer
    cpi r17, 128            ; Check to see if the timer is halfway done (1/2 second, max 255 value)
    brbc 0, increment       ; If r17 <= 128 (max 255 val before resets to 0), invert current LED state
    rjmp loop
increment:
    adc r20, r21            ; Add r21 (1) to r20 (with carry)
    brbs 0, reset           ; If the carry branch is set, reset the register
    rjmp loop               ; Otherwise, run the clock
reset:
    ldi r20, 0              ; Reset the delay register
    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

It's part of my code. I thought that line should be there, but when it isn't commented, it doesn't blink, it remains solidly lit (as far as I can tell).

How long is your delay? It might be too small to see the LED blink.

“incredibly quickly”? It's so slow I can even see it blinking!

There is a bug with the logic of your program: once TCNT0 gets larger
than 128, it will continue to be larger than 128 for quite some time...
during which time you are continuously incrementing your r20 counter.
The simplest fix would be to reset TCNT0 right after the increment
label, with something like out TCNT0, zero_reg. Then you may want to
compare TCNT0 with 61 instead of 128, in order to get closer to the
desired blink frequency of 0.5 Hz.
Other than that, there are quite a few problems in the way you write
your code. jwpat7 has already pointed out some of them, and here are
more:

You should not increment a register with adc, but with plain add.
Both instructions update the carry bit, but adc also adds the
previous value of the carry bit to the target register.
Better yet, increment with inc, as it's purpose is more obvious. But
then you should test the zero bit, as inc does not update the carry
bit.
There is little point in resetting r20 once it has overflowed, as it
is zero at this point.

There are also quite a few ways the program could me made simpler. The
simplest would probably be to configure timer 1 to deliver an interrupt
every second, and toggle the LED in the ISR. If you do not want
interrupts, you can configure counter 1 in much the same way, only
without the “interrupt enable” bit, and check the interrupt flag in a
busy loop.
Below is a slightly simplified version of your program. I tried to keep
it as close as possible to yours, without using timer 1, nor interrupts,
and not even the interrupt flag. The code checks for timer 0 overflowing
by comparing its current value with the previous one.
.set PINB,     0x03
.set DDRB,     0x04
.set TCCR0B,   0x25
.set TCNT0,    0x26
.set LED_MASK, 0b00100000
.set PS_1024,  0b00000101

setup:
    ldi r16, PS_1024    ; Set r16 with prescaler 1024 value
    out TCCR0B, r16     ; Set the TCCROB to 1024
    ldi r16, LED_MASK   ; Set r16 to the LED bit
    out DDRB, r16       ; Set LED pin to output
    clr r18             ; Clear the saved timer
loop:
    ldi r20, 61         ; Initialize our software counter
check_timer:
    in r17, TCNT0       ; Read the timer
    cp r17, r18         ; Compare with previous value
    mov r18, r17        ; Save current value
    brsh check_timer    ; unless the timer has decreased, repeat
decrement:
    dec r20             ; decrement the software counter
    brne check_timer    ; if not zero, go back to checking the timer
toggle:
    out PINB, r16       ; toggle the LED
    rjmp loop

If we can use the timer overflow interrupt flag, then the test is
simpler, and we do not need to store the previous and current values of
the timer in registers:
check_timer:
    sbis TIFR0, TOV0    ; unless the timer has overflowed
    rjmp check_timer    ; check again for overflow
    sbi TIFR0, TOV0     ; otherwise clear the overflow flag

Thank you. I am new to assembly and the low-level mindset and this was very informative and helpful. The reason I didn't use more self-documenting instructions (like dec) is because I'm limited to an instruction subset as a challenge for an assignment.

Would you mind detailing a little bit more on why you use the value 61 exactly?

@JosueEspinosa: The Uno is clocked at F_CPU = 16 MHz. The timer ticks at F_T0 = F_CPU/1024. It overflows with a frequency F_TOV0 = F_T0/256. You want the toggling of the LED to happen at 1 Hz ≈ F_TOV0/61.

Just to clarify what out PINB, r16 does,  Atmel datasheets say "Writing a logic one to PINxn toggles the value of PORTxn, independent of the value of DDRxn."

It appears that your intent is to set TCCROB up with a 1024x prescale, and each time it counts up to 128, increment r20, and toggle the LED each time r20 overflows to zero.
That sequence ought to take 1024/16M · 128 · 256 seconds, or about 2.1 seconds, a fairly leisurely toggle rate.  If instead it's flashing a hundred or more times too fast, probably one of the comparisons is backwards.
Some of the following items might make it easier to debug the problem:
• Instead of brbc 0,..., say brcc ...
• Instead of brbs 0,..., say brcs ...
• Instead of brbs 1,..., say breq ...
That is, use proper mnemonic branch instruction names, rather than referencing SREG bits.
• If my arithmetic was correct and your branch tests were fixed, your rate would be off by a factor of two.  To fix this problem, you could replace one of the more problematic tests (testing for carry clear after cpi r17, 128) with cpi r17, 0 followed by a breq, and change the prescale factor to 256 instead of 1024, which gives 256/16M · 256 · 256 seconds, or about 1.05 seconds.
• Use named constants for register names instead of 0x04, 0x05, 0x25, and 0x26.
• Instead of your lengthy toggle sequence use EOR to toggle the value.  That is, replace
    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

with
    eor   r18, r16          ; Toggle LED bit
    out   PORTB, r18        ; Set the LED to the new state
    rjmp  loop              ; Go run the clock

where r16 and r18 are initialized as follows in setup:
    ldi r16, 0b00100000     ; bit mask for LED pin
    mov r18, r16


text:
What is "tws_delay" and how can I use it? (with an ATTiny85)
EDIT: Alright I'm stupid, I had the 2012 library installed somehow, maybe when I downloaded it indirectly from another old tutorial site. Thanks a ton to Peter Freerick for pointing that out! It finally compiled now
So I'm currently doing a little project where I have an ATTiny85 controlling some (neopixel) RGB addressable LEDs, which is controlled over i2c from an Arduino UNO Master. The goal is to make an Attiny85 into an i2c slave that receives a simple command (such as a single digit int) and decide which premade LED display program to use.
I'm using ATTinyCore, TinyWireS, and Adafruit's tinyNeopixel library for the tiny, and programming it using an Arduino UNO as ISP.
My issue is this: The led code requires a delay to change the speed of the light show. But I see in the TinyWireS example here that I should be using tws_delay instead of the normal delay.
Various googling attempts have left me nowhere to learn how to use tws_delay, what it is, or how to even declare it. I get a declaration error when I try to use the delay with the TinyWireS library included.
I would like to find a resource for learning how to declare and use this delay. Thank you for reading this far
EDIT: I have now added my code and error below, you can find the tws_delay in void loop near the bottom
// NeoPixel Ring simple sketch (c) 2013 Shae Erisson
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

#if (F_CPU>7370000) //neopixel library required 7.37MHz minimum clock speed; this line is used to skip this sketch in internal testing. It is not needed in your sketches.
#include <tinyNeoPixel.h>
#include <TinyWireS.h>
// Which pin on the Arduino is connected to the NeoPixels?
#define PIN            3

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      8

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
tinyNeoPixel pixels = tinyNeoPixel(NUMPIXELS, PIN, NEO_RGB + NEO_KHZ800);

int delayval = 500; // delay for half a second

void setup() {

  pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.

  for(int i=0;i<NUMPIXELS;i++){

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
    pixels.setPixelColor(i, pixels.Color(0,150,0)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    tws_delay(delayval); // Delay for a period of time (in milliseconds).

  }
}
#else //neopixel library required 7.37MHz minimum clock speed; these and following lines are used to skip this sketch in internal testing. It is not needed in your sketches.
#warning "Neopixel control requires F_CPU > 7.37MHz"
void setup() {}
void loop() {}
#endif

And the error:
C:\Users\Dean\AppData\Local\Temp\arduino_modified_sketch_145294\simple.ino: In function 'void loop()':

simple:36:5: error: 'tws_delay' was not declared in this scope

     tws_delay(delayval); // Delay for a period of time (in milliseconds).

     ^~~~~~~~~

C:\Users\Dean\AppData\Local\Temp\arduino_modified_sketch_145294\simple.ino:36:5: note: suggested alternative: 'delay'

     tws_delay(delayval); // Delay for a period of time (in milliseconds).

     ^~~~~~~~~

     delay

Multiple libraries were found for "tinyNeoPixel.h"
 Used: C:\Users\Dean\AppData\Local\Arduino15\packages\ATTinyCore\hardware\avr\1.3.2\libraries\tinyNeoPixel
Multiple libraries were found for "TinyWireS.h"
 Used: C:\Users\Dean\Documents\Arduino\libraries\TinyWireS
exit status 1
'tws_delay' was not declared in this scope

Can you please show your code and the full error message, that you get? When including the library, you should be able to use the tws_delay() function, just as it is used in this example from the library

Alright I have added the code and error message, just to note I tried putting tws_delay(50) as well and still got the same error

The "EDIT: Alright I'm" suggests someone answered your question.  If so, you should mark their answer accepted.  At a minimum you found it helpful, vote it up.  If you found the answer to your own question, post your own answer and mark that accepted.

Answer: Make sure you install the right library :P

It would make more sense to bring your answer-material out of the question and down here into your "answer" to make it a proper answer.

Sorry I'm not sure how to do that at all. Is there some button I'm not seeing?

You have edit links under both your question and answer, so can effectively cut and paste between them.  It's also possible to mark your own answer as accepted, so that there is an accept answer to the question.

tws_delay() is a function provided by the TinyWireS library here. As you can see from the declaration - void tws_delay(unsigned long); - it accepts a parameter of unsigned long, just like delay() does.
In fact, the comment on the line above that declaration says...
// Implement a delay loop that checks for the stop bit (basically direct copy of the stock arduino implementation from wiring.c)
... so, it's safe to say that wherever you would have used delay(), you can use tws_delay().
So there should be no need to declare or define it. But to simply use it. If using tws_delay() in code that includes TinyWireS.h doesn't work, I would be checking that you have a version of the library that declares/defines it. Which you should, given the example you linked, as that repo has had the function since 2012!

Thanks for the reply! So I've added my code and error to the original post. It seems I still get the error even though the library should have declared it right? Also yes I have the newest version of the library installed. I will go double check now just in case. Edit: Oh crap I actually somehow have the code from 2012!! That must be the issue! I'm going to install the new library right now and try that.

Okay sorry to be a pest but I have now solved the issue thanks to you but immediately came across another slight issue, the timing for the delays seems to be way off. For example if I put 1000 in the parenthesis it blinks for a fraction of a second. I wanted to ask you since you seemed to know how it works but I'll open another full question post for this if needed.

Sorry, can't help you with that one off the top of my head... the twi_delay function looks like it should operate properly... if the clock speed of your device is set properly. It should basically put in a 'blocking' 500ms delay (blocking as far as nothing else except TinyWireS_stop_check can repeatedly run, but no longer does anything, as the comment above the implementation suggests TinyWireS became interrupt driven). I bet that is the actual issue, and that tinyNeopixel  uses the interrupt TinyWireS wants to use.

Okay that actually makes sense, I'll look into it, thanks!

Voting your answer up because they didn't despite clearly finding it helpful.


text:
Cant upload arduino code when ESP8266-01 module is connected
I'm using this tutorial to connect my ESP8266-01 WiFi Module to Arduino UNO with Arduino IDE v. 1.8.13.

It works and the module can connect to my WiFi.
However, when I try to upload my code, it says:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
What could be the problem, since when I remove the reset pin it uploads the code, but now the WiFi goes down.

Your problem is that there are two ways of wiring your ESP-01 module to the Arduino:

Wired so the PC has access to it and the Arduino is effectively disabled, and
Wired so the Arduino has access to it

You are wired in configuration 1 at the moment whereby the Arduino is effectively turned off and the USB connection goes direct to the ESP-01. When you try and upload code to the Arduino it's the ESP-01 that the computer is talking to, not the Arduino.
You need to wire it in configuration 2. In this configuration the TX/RX pins of the ESP-01 connect to any two pins of the Arduino except pins 0 and 1, and the RESET pin is not connected to anything. Then you can't talk to the ESP-01 through the serial monitor - instead you have to write code for the Arduino that uses SoftwareSerial to communicate for you.
There are many many tutorials online about communicating between the Arduino and the ESP-01.

This answers so many questions that I have had. Thanks for explaining in such a clear way. Appreciate it