text:
Two adruino are connected to the raspberry via usb, but one is reconnected during processing code is running
I try to solve this a month..but still problem...

I want to make below led-matrix spectrum.
Thumbnail image
https://youtu.be/X35HbE7k3DA

※Environment
Device UML
One Raspberry pi 3 : 2019-09-26-raspbian-buster-full
Two arduino uno with each matrix shield and 16x32 matrix
One usb Microphone

If i attached two arduino Uno to raspberry pi and try to run Processing code(.pde) , one of them is reattached to raspberry pi.
The other one is still working well..
If i connect these arduinos to windows and running pde file...It works well.
(two matrix are showing spectrum well)
What should I do???
Is this code problem? or raspberry problem?
I really need to solve this...

I already tried....

Reloaded ino code to both arduino Uno.
(both arduino has same code)
Changed boardrate number 115200 -> other number
(but it must be 115200 to running well)
Add arduino to udev rules like below link.
https://www.intorobotics.com/how-to-setup-raspberry-pi-to-identify-two-arduino-devices/
Cross exchange each matrix and arduino.
Try to use arduino mega with same code.

Here is the arduino code(.ino) and Processing Code(.pde)
https://github.com/snskreationz/Real-Time-RGB-Matrix-Spectrum-Analyzer
arduino Uno Matrix Pin number
#define CLK 8
#define LAT 10
#define OE  9
#define A   A0
#define B   A1
#define C   A2

Main processing code
import ddf.minim.analysis.*;
import ddf.minim.*;
import processing.serial.*;

Serial port1;
Serial port2;

Minim minim;
AudioInput in;
FFT fft;

int buffer_size = 4096;
float sample_rate = 200000;

int freq_width = 250; // <-O-> set the frequency range for each band over 400hz. larger bands will have less intensity per band. smaller bands would result in the overall range being limited

//arrays to hold the 64 bands' data
int[] freq_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
float[] freq_height = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

void setup()
{
  size(200, 200);

  minim = new Minim(this);
  port1 = new Serial(this, "COM8" , 115200); // <-O-> set baud rate and port for first RGB matrix
// Here can be changed to "/dev/ttyACM0" via Raspberry pi
  //port2 = new Serial(this, "COM5" , 115200); // <-O-> set baud rate and port for second RGB matrix
// Here can be changed to "/dev/ttyACM1" via Raspberry pi

  in = minim.getLineIn(Minim.MONO,buffer_size,sample_rate);

  // create an FFT object that has a time-domain buffer
  // the same size as line-in's sample buffer
  fft = new FFT(in.bufferSize(), in.sampleRate());
  // Tapered window important for log-domain display
  fft.window(FFT.HAMMING);
}

Here are the kernel logs for Raspebrry pi
Nov 11 00:17:27 raspberrypi kernel: [ 5974.165722] Under-voltage detected! (0x00050005)
Nov 11 00:17:27 raspberrypi kernel: [ 5974.665649] usb 1-1.3: new full-speed USB device number 9 using dwc_otg
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809539] usb 1-1.3: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809556] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809566] usb 1-1.3: Manufacturer: Arduino (www.arduino.cc)
Nov 11 00:17:27 raspberrypi kernel: [ 5974.809576] usb 1-1.3: SerialNumber: 55639313932351518040
Nov 11 00:17:27 raspberrypi kernel: [ 5974.810729] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device ---------------------> connected first arduino
Nov 11 00:17:28 raspberrypi kernel: [ 5975.685661] usb 1-1.2: new full-speed USB device number 10 using dwc_otg
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829541] usb 1-1.2: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829558] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829569] usb 1-1.2: Manufacturer: Arduino (www.arduino.cc)
Nov 11 00:17:28 raspberrypi kernel: [ 5975.829578] usb 1-1.2: SerialNumber: 8563431373935121D0B2
Nov 11 00:17:28 raspberrypi kernel: [ 5975.830752] cdc_acm 1-1.2:1.0: ttyACM1: USB ACM device --------------------->  connected second arduino
Nov 11 00:17:33 raspberrypi kernel: [ 5980.405877] Voltage normalised (0x00000000) --------------------->  almost at this time starting processing code
Nov 11 00:17:37 raspberrypi kernel: [ 5985.121964] usb 1-1.2: USB disconnect, device number 10
Nov 11 00:17:37 raspberrypi kernel: [ 5985.122315] cdc_acm 1-1.2:1.0: failed to set dtr/rts
Nov 11 00:17:38 raspberrypi kernel: [ 5985.425669] usb 1-1.2: new full-speed USB device number 11 using dwc_otg
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569812] usb 1-1.2: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569831] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569843] usb 1-1.2: Manufacturer: Arduino (www.arduino.cc)
Nov 11 00:17:38 raspberrypi kernel: [ 5985.569853] usb 1-1.2: SerialNumber: 8563431373935121D0B2
Nov 11 00:17:38 raspberrypi kernel: [ 5985.571468] cdc_acm 1-1.2:1.0: ttyACM2: USB ACM device --------------------->  reattached second arduino automatically
Nov 11 00:17:39 raspberrypi kernel: [ 5986.645829] Under-voltage detected! (0x00050005)
Nov 11 00:17:43 raspberrypi kernel: [ 5990.805775] Voltage normalised (0x00000000)

I really want to run both arduino spectrum via raspberry pi.

Under-voltage detected! I think it says it all. Rapsberry have many times problem to feed itself from "common power source", not mentioning attached devices. Especially, if you power your LEDs from it too.
You need better power source for Rapsberry (and maybe even power it from pins, but then you need read much more to not damage it) and other powersource for those LEDs.
On normal PC the Power Source is way more powerfull and can feed a LOT of power to each USB.

Thank you for answer my question!
Your right... it's under-voltage problem..  BOD (brown out detector)...
I given more power to arduino and it works fine:)


text:
STM32duino Can bus library
I couldn't find any library for can bus for STM32duino (Maple Mini) on arduino or even on STMcubeIDE
I found one library on github but it doesn't compile it has a lot of error (its a fork of the stm32duino github library)
I hope that someone could provide a working library or a simple example on how to implement can bus peripheral on STM32F103

source: Stack Exchange

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

sort: votes


text:
Pin Change Interrupt Flag timing on 1284P
I want to ask about pin change interrupts on a 1284P chip using MightyCore.  I have a question about the timing of multiple interrupts on one port.  Specifically, if I am servicing a PCINT vector and another pin in the port changes while I am in the ISR, will it generate another interrupt immediately following the one I am servicing?
When I read the datasheet I see:

Bit 2 – PCIF2: Pin Change Interrupt Flag 2 When a logic change on any
PCINT[23:16] pin triggers an interrupt request, PCIF2 will be set. If
the I-bit in SREG and the PCIE2 bit in PCICR are set, the MCU will
jump to the corresponding Interrupt Vector. The flag is cleared when
the interrupt routine is executed. Alternatively, the flag can be
cleared by writing '1' to it.

When it says that the flag is cleared when the interrupt routine is executed, does that mean when it enters or exits the ISR?  If it is at the end, can I clear the flag in the first line of the ISR and allow another pin change to set it again even if it happens before I exit the ISR?

When it is entered. The wording is slightly vague but I think "when the interrupt routine is executed" means the commencement of execution. Otherwise multiple pin-change interrupts could be easily missed, depending on how long you took inside the ISR.
I suggest writing a simple test that saves somewhere what the flag is, upon entering the ISR, and check it is cleared already.

I wrote this test for the Uno (which is the same basic architecture):
volatile bool firstTime = true;
volatile byte PCIFR_copy = 0;

ISR (PCINT0_vect)
 {
 // handle pin change interrupt for D8 to D13 here

 if (!firstTime)
   return;

 firstTime = false;
 PCIFR_copy = PCIFR;
 }  // end of PCINT0_vect

void setup ()
  {
  pinMode (9, INPUT_PULLUP);
  Serial.begin (115200);

  // pin change interrupt (for D9)
  PCMSK0 |= bit (PCINT1);  // want pin 9
  PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13
  }  // end of setup

void loop ()
  {
  Serial.print ("First time is ");
  Serial.print ((int) firstTime);
  Serial.print (", Flag is ");
  Serial.println ((int) PCIFR_copy);
  delay (1000);
  }  // end of loop

The PCIFR flag was always zero, even after triggering the pin-change interrupt, which shows that it was cleared upon entering the ISR.

will it generate another interrupt immediately following the one I am servicing?

So, based on the above, the answer is yes it will. Upon leaving the ISR one more instruction will be executed and then the next interrupt will be serviced (assuming a higher-priority interrupt doesn't get in first).

Another way of looking at it is that the pin change will always set that flag. Between instructions the processor would check that flag (and the flags for the other interrupts) and for the highest priority interrupt, if that flag is set, then it would clear that flag and then commencing processing that interrupt. That is really the only logical way it could work.

Also, it makes more sense from the design of the processor to clear the flag upon entering the ISR. Apart from the problem that interrupts could be missed if it didn't, when it enters the ISR the processor "knows" which interrupt it is servicing, because it would have checked the PCIFx flag, it would have checked the PCIEx flag (to see if the interrupt should be executed) and it would have then changed the program counter to the appropriate address for that interrupt, after pushing the current program counter onto the stack. This would be the logical time to clear that flag while all this information is in the processor's "head" so to speak.
At the end of the ISR the code simply executes a RTI (Return from Interrupt) instruction which doesn't have associated with it which interrupt it is returning from. Thus it would be hard to clear the flag at that point.

Thanks for the quick and thorough (and tested) response.

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


text:
analogRead over a certain time
I would like to read an analog value using analogRead, save this value and compare it to an analogRead value 5 ms later. How would this code look? Because giving a variable the value of analogRead(A0); would mean it is constantly changing, making it impossible to compare two values.
thanks in advance

The simplest and crudest method:
int val1 = analogRead(A0);
delay(5);
int val2 = analogRead(A0);

if (val2 > val1) {
    // It went up (for example).
}

You just need to copy the value into another before you overwrite it with analogRead(A0) and then compare those two variables.
int prev_value = 0;
int value = 0;
unsigned long prev_read_time = 0;

void setup() {
    prev_read_time = millis();
    value = analogRead(A0);
}

void loop() {
    if (millis() - prev_read_time > 5) {
        prev_read_time = millis();
        prev_value = value;
        value = analogRead(A0);
        if (prev_value != value) {
            // value changed
        }
    }
}

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


text:
Problem with measuring vibrations (Arduino UNO + step motor + accelerometer)
I'm trying to measure vibrations of the motor's shaft that is oscillating due to an eccentric load. For that, I am using the MPU 6050 6 axis accelerometer. The motor is a NEMA 17 stepper, connected to Arduino UNO via EasyDriver v4.4.
I first uploaded my code for the stepper, where I have 2 buttons to control the rotation direction (if you press the left, it goes clockwise and if you press the right button it goes counter clockwise). This code works fine.
Later I uploaded the code only for the accelerometer and it worked fine, however when I'm trying to combine both so that the vibrations could be measured while the motor is running, apparently, I'm losing steps of the motor. Here is the code:
#include<Wire.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;

#define RPMS                300.0
#define STEP_PIN                9
#define DIRECTION_PIN           8
#define GO_PIN_L                3
#define GO_PIN_R                4

#define STEPS_PER_REV         200
#define MICROSTEPS_PER_STEP     8
#define MICROSECONDS_PER_MICROSTEP   (1000000/(STEPS_PER_REV *
MICROSTEPS_PER_STEP)/(RPMS / 60))

uint32_t LastStepTime = 0;
uint32_t CurrentTime = 0;

int Distance = 0;

void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);

  pinMode(STEP_PIN, OUTPUT);
  pinMode(DIRECTION_PIN, OUTPUT);
  digitalWrite(STEP_PIN, LOW);
  digitalWrite(DIRECTION_PIN, LOW);
  pinMode(GO_PIN_L, INPUT);
  pinMode(GO_PIN_R, INPUT);
}

void loop() {
  Distance = Distance + 1;   // record this step
  if (digitalRead(GO_PIN_L) == LOW)
  {
    CurrentTime = micros();
    digitalWrite(8, LOW);
    if ((CurrentTime - LastStepTime) > MICROSECONDS_PER_MICROSTEP)
    {
      LastStepTime = CurrentTime;
      digitalWrite(STEP_PIN, HIGH);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
      digitalWrite(STEP_PIN, LOW);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
    }
  }
  if (digitalRead(GO_PIN_R) == LOW)
  {
    CurrentTime = micros();
    digitalWrite(8, HIGH);
    if ((CurrentTime - LastStepTime) > MICROSECONDS_PER_MICROSTEP)
    {
       LastStepTime = CurrentTime;
      digitalWrite(STEP_PIN, HIGH);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
      digitalWrite(STEP_PIN, LOW);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
    }
  }
//  Wire.beginTransmission(MPU_addr);
//  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
//  Wire.endTransmission(false);
//  Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
//  float AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
//  float AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
//  float 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();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
//  Serial.print("AcX = "); Serial.println(AcX / 16384);
//  Serial.print(" AcY = "); Serial.println(AcY / 16384);
//  Serial.print(" AcZ = "); Serial.println(AcZ / 16384);
//  Serial.print(" Tmp = "); Serial.print(Tmp / 340.00 + 36.53);
//  Serial.println("");
//  // Serial.print(" | GyX = "); Serial.print(GyX);
//  // Serial.print(" | GyY = "); Serial.print(GyY);
//  // Serial.print(" | GyZ = "); Serial.println(GyZ);
//  delay(333);
}

So the commented portion of the code is used to read and print accelerations. Since this is in the same loop as the code for the motor, I'm sure that the delay(333) has a negative effect, but also when I tried step-by-step to include lines of code for accelerometer, the motor slowly started to losing speed and steps...
Does anyone of you have a clue how this could be done so that both devices (the motor with EasyDriver v 4.4 and the accelerometer) could run simultaneously since there can't be 2 void loops? I don't know how I could timewise separate their individual codes since I need to monitor the motor with the accelerometer...
Kind regards,
Luka

Thank you gilhad and Jot for your time, I really appreciate it. However, my best friend who happens to be an electric guru as far as I am concerned, proposed an ever more elegant solution to this multi-tasking problem.
He proposed to use timer settings in the void setup, like this:
#include<Wire.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;

#define RPMS                300.0
#define STEP_PIN                9
#define DIRECTION_PIN           8
#define GO_PIN_L                3
#define GO_PIN_R                4

#define STEPS_PER_REV         200
#define MICROSTEPS_PER_STEP     8
#define MICROSECONDS_PER_MICROSTEP   (1000000/(STEPS_PER_REV * MICROSTEPS_PER_STEP)/(RPMS / 60))

uint32_t LastStepTime = 0;
uint32_t CurrentTime = 0;

int Distance = 0;

void setup() {
  bitClear(SREG, 7);
  pinMode(10, OUTPUT);

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
  TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
  OCR1A = 2423; //timer šteje do 444, tako dobim PWM frekvenco 36,363kHz
  OCR1B = int(OCR1A / 2); //prilagajam duty cyle, naj bo kar 50%

  bitSet(SREG, 7); //global interrupt enable

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);

  pinMode(DIRECTION_PIN, OUTPUT);
  digitalWrite(DIRECTION_PIN, LOW);
  pinMode(GO_PIN_L, INPUT);
  pinMode(GO_PIN_R, INPUT);
}

void loop() {
  Distance = Distance + 1;   // record this step
  if (digitalRead(GO_PIN_L) == LOW)
  { TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0;
    delay(100);
    TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
    OCR1A = 2423; //timer šteje do 444, tako dobim PWM frekvenco 36,363kHz
    OCR1B = int(OCR1A / 2); //prilagajam duty cyle, naj bo kar 50%

    digitalWrite(8, LOW);
  }
  if (digitalRead(GO_PIN_R) == LOW)
  {
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0;
    delay(100);
    TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
    OCR1A = 2423; //timer šteje do 444, tako dobim PWM frekvenco 36,363kHz
    OCR1B = int(OCR1A / 2); //prilagajam duty cyle, naj bo kar 50%

    digitalWrite(8, HIGH);
  }
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
  float AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  float AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  float 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();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.println(AcX / 16384);
  Serial.print(" AcY = "); Serial.println(AcY / 16384);
  Serial.print(" AcZ = "); Serial.println(AcZ / 16384);
  Serial.print(" Tmp = "); Serial.print(Tmp / 340.00 + 36.53);
  Serial.println("");
  // Serial.print(" | GyX = "); Serial.print(GyX);
  // Serial.print(" | GyY = "); Serial.print(GyY);
  // Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}

So the portion in void setup:
  bitClear(SREG, 7);
  pinMode(10, OUTPUT);

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
  TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
  OCR1A = 2423; //timer counts to 444, PWM frequency is thereby 36,363kHz
  OCR1B = int(OCR1A / 2); //duty cyle is 50%

  bitSet(SREG, 7); //global interrupt enable

rotates the step motor WITHOUT any code in the void loop, void loop is only used to change the rotation direction of the motor by using the buttons that I incorporated (GO_PIN_L and GO_PIN_R) and to measure the acceleration with the accelerometer.
I hope this helps to anyone that might have similar problems.
Kind regards,
Luka

This is common problem, how to do two (and more) things with waiting, without blocking delay (the simplest way is in example BlinkWithoutDelay)

You wait for motor microsteps (with delayMicroseconds)
You wait between reading MCU (with delay(333))
You spend time sending Transmission over Wire (that is relatively slow) and getting answer requestFrom (also slow)
You spend time sending prints over Serial

Each of this is blocking delay of some kind under Arduino (and writing the transmission in non-blocking way is not an easy task)
You should use some kind of state automaton (google that) for that (or more such automats - each for one task), to overcome the blocking nature of the steps.
basically you can have lot of loops running together in this manner:
long state1_micros,state2_micros,state3_micros; // last time it happened
long state1_delay,state2_delay,state3_delay; // how long wait for next step
#define LOOP1_STEP1 1
#define LOOP1_STEP2 2
#define LOOP1_STEP3 3
#define LOOP2_STEP1 1
#define LOOP2_STEP2 2
#define LOOP2_STEP3 3
#define LOOP2_STEP4 4
#define LOOP2_STEP5 5
#define LOOP2_STEP6 6
#define LOOP2_STEP7 7
void setup(){
...
 long current_micros=micros() ; or millis, if less precision needed
 state1=LOOP1_STEP1;
 state1_micros=current_micros;
 state1_delay=0;
 state2=LOOP2_STEP1;
 state2_micros=current_micros;
 state2_delay=0;
 // state3=LOOP3_STEP1;
 // state3_micros=current_micros;
 // state3_delay=0;
}

void loop(){
 long current_micros=micros() ; or millis, if less precision needed
 if (state1==LOOP1_STEP1 && current_micros-state1_micros>=state1_delay) {
   //state1 paused for at least state1_delay
   if (/*some condition for leave state1 step1  like (digitalRead(GO_PIN_L) == LOW)*/) {
     state1=LOOP1_STEP2;// next step
     state1_micros+=/*some delay like MICROSECONDS_PER_MICROSTEP */;
     /* do action for STEP1, like  digitalWrite(8, LOW); */
    }
  }
 if (state1==LOOP1_STEP2 && current_micros-state1_micros>=state1_delay) {
   //state1 paused for at least state1_delay
   if (/*some condition for leave state1 step2  like (True)*/) {
     state1=LOOP1_STEP3;//next step
     state1_micros =/*some delay like(MICROSECONDS_PER_MICROSTEP * 0.9) / 2) */;
     /* do action for STEP2, like  digitalWrite(STEP_PIN, HIGH); */
    }
  }
 if (state1==LOOP1_STEP3 && current_micros-state1_micros>=state1_delay) {
   //state1 paused for at least state1_delay
   if (/*some condition for leave state1 step3  like (True)*/) {
     state1=LOOP1_STEP1;//next step
     state1_micros =/*some delay like(MICROSECONDS_PER_MICROSTEP * 0.9) / 2) */;
     /* do action for STEP2, like  digitalWrite(STEP_PIN, LOW); */
    }
  }
////////
 if (state2==LOOP2_STEP1 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step1  like (digitalRead(GO_PIN_L) == LOW)*/) {
     state1=LOOP2_STEP2;// next step
     state1_micros+=/*some delay like 100*1000 (333/3) */;
     /* do action for STEP1, like
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
  float AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  float AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  float 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();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
 */
    }
  }
 if (state2==LOOP2_STEP2 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state1 step2  like (True)*/) {
     state2=LOOP2_STEP3;//next step
     state2_micros +=/*some delay like 10*1000 (10ms) */;
     /* do action for STEP2, like  Serial.print("AcX = "); Serial.println(AcX / 16384);  */
    }
  }
 if (state2==LOOP2_STEP3 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step3  like (True)*/) {
     state2=LOOP2_STEP4;//next step
     state2_micros +=/*some delay like 10*1000 (10ms) */;
     /* do action for STEP3, like Serial.print(" AcY = "); Serial.println(AcY / 16384); */
    }
  }
 if (state2==LOOP2_STEP4 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step4  like (True)*/) {
     state2=LOOP2_STEP5;//next step
     state2_micros +=/*some delay 10*1000 (10ms) */;
     /* do action for STEP4, like  Serial.print(" AcZ = "); Serial.println(AcZ / 16384); */
    }
  }
 if (state2==LOOP2_STEP5 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step5  like (True)*/) {
     state2=LOOP2_STEP6;//next step
     state2_micros +=/*some delay 10*1000 (10ms) */;
     /* do action for STEP5, like  Serial.print(" AcZ = "); Serial.println(AcZ / 16384); */
    }
  }
 if (state2==LOOP2_STEP6 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step6  like (True)*/) {
     state2=LOOP2_STEP7;//next step
     state2_micros +=/*some delay 10*1000 (10ms) */;
     /* do action for STEP6, like  Serial.println(""); */
    }
  }

 if (state2==LOOP2_STEP7 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step7  like (True)*/) {
     state2=LOOP2_STEP1;//start over
     state2_micros +=/*some delay (333-100-4*10)*1000 (rest to 333ms) */;
     /* do action for STEP7, like  nothing*/
    }
  }
/////
/* if we have more automatons, like stat3, stat4 and so on, put it her */
} // end loop()

I associate a state machine with a switch-case statement. The name 'STEP' for the state machine is confusing because a stepper motor is involved. The name 'STATE' might be better. Whatever you do, you MUST make the timing variables "unsigned long" to avoid the rollover problem. mcluka, gilhad is making two seperate state machines in the loop function. Using a state machine together with the millis function is indeed the ideal solution.

Yes, unsingned long of course, my bad, wrote it from head before first cofee. switch-case is also sometimes more descriptive, in my last project I needed one machine "preferred", so I used if series (with returnin each part), where the more critical parts was solved first, then the less critical and the machines was reordered and interchanged heavily. So I first mentioned the google, then ofered one exapmle approach. There is much more ways hoe to do it.

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


text:
Arduino Mega - Multithreaded (run two loops simultaneously)
I am new to Arduino and I am not sure about how to get two loops run parallel to each other. I have tested the individual loops and both of them work perfectly before I combined them together.
One loop will take input from the LCD touchscreen. One loop will take input from vibration sensor which will determine the state (on/off) of LED. Once the LED is turned on, it has to stay at the ON state for 3 seconds before switching to OFF state.
The problem I am facing is that when the LED is triggered to ON state by vibration sensor, I have to wait 3 seconds for the input from LCD to get processed. Is there any way I can combine these two loops in such a fashion that I run them simultaneously, i.e. run two inputs together?

Arduino Due, Zero support multi-threading. You can try them.

Please search for delay on this site and you will find several questions similar to yours, and for some, answers that probably are relevant to you. What you want is replace delay(0) with something else: a timer or calls to millis() with comparison to some time reference.

Just answered something really similar here: https://arduino.stackexchange.com/questions/38713/problem-with-measuring-vibrations-arduino-uno-step-motor-accelerometer/38737#38737 please read it for reference

You can combine the 2 programs into 1 program.  But when you start wanting to do multiple things at once then you can't have any code that "blocks" and waits to finish before letting the next thing happen.  The Arduino has a single core, it can't do multithreading.  But if you write non-blocking code you can make things appear to happen at the same time.  I imagine the problem with your code now is that you have probably used the delay function.  That function blocks, so nothing else can happen while the delay is running.  Instead you have to use millis to record the time and periodically check against that time to see if it is time to take the next step instead of calling a delay to wait for the next step.  See the "Blink Without Delay" example that comes with the IDE and any of the multitude of tutorials about it on the web to see how it works.

"The Arduino has a single core, it can't do multi threading." This is simply 100% not true, and is a falsehood (if not a downright lie) that started to appear around the advent of dual core PC's. CPU's of any architecture or core count can do multi-threading. Multi threading != multiple cores .https://stackoverflow.com/a/16117084https://stackoverflow.com/a/16117084
If you want multi-threading on an embedded system such as Arduino or any other microcontroller, you should probably start looking at RTOS's or OS's.

So you're saying that the Arduino UNO or Mega is capable of executing multiple machine instructions at once?  Sure, you can have task schedulers and all sorts of switching back and forth.  But it is just not possible for the processor used in those boards to execute more than one instruction at any time.  If you think there is a way then please explain it.  I'm not talking about a pre-emptive multi-tasking where two processes take turns using the processor.  But true multi-threading where the processor actually does two things at once.

@Delta_G in fact... I also used to agree with you, and went searching for the definition of multi-threading to prove that the temporal multi-threading is a sort of "emulation" but... I discovered that user9993 is right: Multithreading on wikipedia says that the ability to switch from one thread to another, even on the same CPU, is also considered multithreading.

@frarugi87 Yep, I have no reason to lie. Quite frankly I think it shows an appalling lack of knowledge in the "arduino world" when I have to create an account to correct something that is so incorrect it would leave OP in a worse place. Multithreading has not once meant multicore. Threads executing in parallel on multiple cores is an implementation detail.
On Windows open Task Manager (or equivalent on your OS eg top), note how you likely have several thousand threads. Does your CPU also have several thousand cores?

@user9993 in fact I think everybody knows the time-based multithreading; the misconception is about terminology. I've always thought that "real" multithreading was the ability to execute threads concurrently, and so a single core CPU can "emulate" this by dividing the time they are performing tasks and act as if they were run concurrently. It looks like that this behavior is still classified as multi-threading, so... it's just a terminology issue, not a lack of knowledge ;)

Either way, it's a moot point.  Please take a look at the poster's question.  Do you think he needs any sort of complicated task scheduler or multi-threading system to solve it?  Or do you think he could just write a little quick non-blocking millis based code and be done?

I totally second Delta's answer. Make the two loops "non blocking", then run them one after the other.
Just wanted to add another solution, to be applied only when strictly needed. And only if the program really needs it. And only if other solutions are not enough. And... Well, you understood.
You can use FreeRTOS to have a sort of "multi-threading" environment. You have, IIRC, four "threads" which can jump from one loop to the other. You will have to carefully design it (particularly the shared memory) but in the end you will have even blocking "threads" running in parallel. Here are some more infos.


text:
getting " .error: failed sending 1116 bytes warning: espcomm_send_command: didn't receive command response"
I'm getting error while uploading sketch into nodemcu ch340g as shown below

I have tried these things to rectify the error
1) Changed usb cable
2) changed the port
3) flashed the firmware with nodemcu_float_0.9.6-dev_20150704.bin by esptool.py
4) flashed with nodemcu flasher
But no change at all and it is showing same error only what can i do now

I had a similar problem yesterday, I had plugged a shield into my D1 the wrong way around.  Is it possible you have made some incorrect connections?

I have disconnected all the things ,even though it is showing same error

Problem solved by doing this
In boards, I have mentioned node MCU 1.0 and that's the mistake I have done, after changing the board to node MCU 0.9, then the program is uploading and thanks for all your suggestions

3) flashed the firmware with nodemcu_float_0.9.6-dev_20150704.bin by esptool.py

So assuming that actually completed successfully you can rule out anything being wrong with your hardware. There is no difference between manually flashing a firmware file and flashing using the IDE.
You need to take a look at the command you used to flash that firmware successfully, especially things like which port you used and what baud rate, and make sure you replicate those same settings in the IDE. Especially the baud rate, which you can select in the Tools menu.


text:
Can I upload with avrdude 2 hexes with 2 usbasp connected to computer, one hex with one usbasp ? If yes, how?
If I have connected 2 usbasps in the same time to ubuntu, can I upload 2 hexes one after the other(using avrdude) on each usbasp without disconnecting a usbasp ? If yes, how do I select each port for each hex ?

Can you please edit your question and add a little background on what you are trying to achieve. Also, how is this related to Arduino??

https://electronics.stackexchange.com/questions/130984/can-avrdude-address-individual-usbtiny-programmers


text:
Arduino 101 I/O voltage levels
As per the Arduino 101 schematic.
The Arduino 101 has level shifters (TI make LSF0108) connected to the I/O ports I guess these are to make them Arduino compatible(5V) since the Intel Curie Module is 3.3V rated.
I have 2 doubts regarding this

The level shifters are also connected to the analog pins so I was wondering how do these shifters pass through analog signals?
I have some 3.3V sensors that I want to interface to the Arduino 101 via I2C. My question is can I use 3.3V levels at the I/O ports or am I restricted to 5V?

TIA

@Majenko that's a 4 page document, agreed that 1st page is a block diagram.. but the schematic is from pages 2 onwards..

Do you have a cloth I can wipe the egg off my face with? ;)

Even with the schematic I can't see how that can possibly provide any analog inputs at all. The Ax pins go straight into an LSF0108 digital logic level translator, so how it can claim there are analog inputs I don't know. You're right to be confused. Also if the schematic is to be believed the LSF0108 isn't being used according to the datasheet's recommendations. Not sure quite how/why they are doing it...

@Majenko yes I had the same thoughts... even the LSF0108 datasheet doesn't shed any light on analog levels.

Nexperia's appnote AN90033 explains how it works.

An Exploring the I/O Performance of the Arduino 101 webpage by Dan Watson has a number of relevant comments:

The board uses three Texas Instruments LSF0108 level translators to accommodate all of the I/O lines (including the analog inputs). This is an interesting part. It's not really a level "shifter", and it's not a buffer. The Curie is still sourcing and sinking current to the pins, but the voltage levels are clamped at 3.3V on the Curie's side of the chip. In this regard it's kind of like a fancy analog switch. The on resistance of each signal path is in the neighborhood of 10 ohms.

Somewhat later in the article:

Analog Input Linearity:  Next I tested the analog inputs. I was curious if the level translators affect the accuracy of the readings. I applied a DC voltage on pin A5, starting at 0V and increasing to 3.3V in 100 mV steps. At each step, I recorded the 10-bit analog-to-digital (ADC) readings reported by the Arduino 101. I then created a graph of the data, which is shown [on the webpage]. As you can see, the results are pretty linear across the entire input range. Spot-checking a few values, I found that there might have been a +20mV bias on the readings at the top end of the scale.

To summarize:  As a consequence of being like an analog switch, the LSF0108 allows the Curie's analog input pins to accept analog inputs, and apparently it works ok.
Regarding the second question, whether 3.3 V levels are ok at the I/O ports, I think they are.  See the article mentioned above for more comments.  Here is one that may be relevant:

Digital Input Logic Transitions:
  I applied a DC voltage to pin D7 and varied it up and down while the Arduino 101 reported the logic state in the serial monitor. This was done in order to discover the logic transition levels. Going from high to low, it returned a low state after crossing 1.26V. Going from low to high, however, the transition occurred at 1.55V.

Edit 1:  Regarding two questions in a comment...

What is the function of the level translators.. do they actually map the 0 to 5V levels to 0 to 3.3V on the curie side. ?

See the LSF0108 datasheet.  The LSF0108 has eight A, B pairs: (A1,B1);  (A2,B2); ... (A8,B8).  If you drive Ai low, Bi goes low too; and vice versa, if you drive Bi low, Ai goes low too.  That translates low to low. If neither side is driven low, connected inputs can pull up to an individual-pullup level but not higher than a reference level (VREFA or VREFB).  This translates high to high.

If I give a 0 to 5V analog voltage at the headers will the 3.3V to 5V level part of the signal be lost, I mean does the board only take care of the 0 to 3.3V part of the signal and the adc will give max counts at 3.3V?

It should be 'lost', because as noted in the Curie datasheet's Table 2-5. ADC - DC I/O specifications, the AIN Full-scale input range is ≤ ADC_3P3_VCC and ≤ AON_IO_VCC.  (The latter voltage is 1.8 or 3.3 V.)  I'm not clear on why the LSF0108 doesn't interfere with ADC measurements.  Maybe the switches operate in a linear mode when pullups are turned off?

thanks for digging that link out... for the analog input linearity test what did the autthor increase it to a max of 3.3V why not 5V?

I'll try and get in touch with the author to learn what his experiences were...

I still have a few questions... 1. What is the function of the level translators.. do they actually map the 0 to 5V levels to 0 to 3.3V on the curie side. ? 2. If I give a 0 to 5V analog voltage at the headers will the 3.3V to 5V level part of the signal be lost, I mean does the board only take care of the 0 to 3.3V part of the signal and the adc will give max counts at 3.3V?

@MiguelSanchez, see edit 1

I have a feeling the LSF0108, internally, is just an N channel MOSFET per channel. Your classic bidirectional MOSFET level translator. As such it will be fairly transparent to analogue voltages.


text:
ESP8266 constantly reconnects
So, my ESP8266 now has this problem where every three seconds it goes offline for a split second and the light blinks as it comes back. It seems to be constantly resetting... I recieved this problem when I had it connected to a power brick in my pocket, and I am pretty sure it happened because of static. I would have bought a protective case for it but it appears that I csn only find 3D printed parts but I currently do not own a 3D printer. I am wondering how I can fix it. If I try to re-flash it the re-flash fails because it disconnects before the flashing finishes.

It may be your code getting into a loop that takes longer than the watchdog timeout.

If it is static damage its unlikely you can fix it.  Have you tried running it of a different power supply?

@CodeGorilla I managed to fix the problem, I just needed to re-flash with a python script rather than Ubuntu's ESPTool.

I managed to fix the problem. I have a PC with Ubuntu 16.04 and I tried to re-flash it using Ubuntu's ESPTool, which was why it was failing. I noticed it failed constantly at a certain point. To fix it, I re-flahed the firmware with this python script, and it was successful.


text:
How to get Arduino to talk to two seperate motors wirelessly?
I have an Arduino Uno and I also have two Servo Motors. Say I have a room that is 15 feet wide, and I want to be able to place the Arduino in the center of the room and control two servo motors placed at each end of the room using a button on the Arduino. Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers? Or will I have to use three Arduinos, one for the center with the button and one for each servo. If so, will I be able to substitute the two servo Arduinos with an ATtiny chip?

Place the motors in two separate rooms.  Walk into room A and say "Hello motor, how are you today?", then go into room B and repeat.  Oh and do it while holding an Arduino Uno and you have done what you asked about.

You'll probably need 3 "controllers", of which the one in the middle of the room might need to be a full-featured Arduino. Depending on the the needed libraries of your bluetooth receivers at the remote servos, it seems likely that you could use ATTinys in place of more feature-filled Arduino, but you would still have to think of the ATTinys as Arduinos or at least the glue controller to translate commands from Bluetooth to servo signals (PWM).
You could provide us with more details, such what particular bluetooth modules or transceivers you plan to use; some might provide an asynchronous serial interface, others might present an I2C or SPI interface, and given the small flash and RAM size in the ATTiny line, you would need to evaluate the code and associated libraries needed to operate it on such a processor.
The answer to your question is, "Maybe", given the small amount of detail you have provided.

Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers?

Yes. The process goes like this:

Can you get your Arduino to talk?
Can you get your Arduino to talk to one servo via wires?
Can you get your Arduino to talk to one servo wirelessly?
R. Can you get your Arduino to talk to two servos wirelessly?

Or will I have to use three Arduinos, one for the center with the button and one for each servo.

That's certainly one aporoach.

If so, will I be able to substitute the two servo Arduinos with an ATtiny chip

It certainly can be done. Whether you can do it is unknown to anyone but you.


text:
Can't Upload Sketch, Atmel SDM Chip Overheating
I have a chinese CH340 clone arduino. It was working fine until now. The L light stays always on. The sdm Atmel chip is overheating to the point that I can't even touch it. The card is listed under com ports however I can't upload anything due to:
avrdude: stk500_recv(): programmer is not responding

Should I just throw it away or is there a way to save it?

I had a similar question, maybe it helps: https://arduino.stackexchange.com/questions/41806/possible-reason-for-broken-uno

How was it being powered?

It's dead, Jim.

@SDsolar It was powered with a 12V adapter. It was also connected with a rfc522 module and a relay module. Apparently rfc522 also doesn't work anymore.

Remember the Software Engineer from this joke:  http://www.cs.uni.edu/~mccormic/humor.html

Here are some fun links about Arduinos on fire:  https://www.google.com/search?q=arduino+on+fire

SDM... Do you mean SMD (Surface Mount Device)?


text:
All floats feedback a rounded down integer
So I am very confused at the results I am getting.
It seems that floats aren't working properly, and I don't understand why.
I was trying to read a temp sensor and convert the reading to celsius. However, when I tried to divide the value (an int between 145-165) by 1024, and multiply by 5 I would get back a float value of 0.00
Here's the code I was using
    void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(A0, INPUT);

}

void loop() {
  int sensorVal = analogRead(A0);
    Serial.print("Sensor Value: ");
    Serial.println(sensorVal);

  float voltage = ((sensorVal/1024) * 5);
    Serial.print("Voltage Value: ");
    Serial.println(voltage);

}

This would only return values of 0.00 for voltage, even though the sensor itself is working fine, returning varying values between 146 and 165 based on how much heat I apply.
This didn't make any sense, so I tried it with some other values, eg.
Serial.print(float (10 / 6));

and
Serial.print(float (5 / 2));

which should have returned 1.67 and 2.50 respectively, but instead returned 1.00 and 2.00
I think it might be a settings thing, where all floats round down to an int, but that seems really weird.
Any help would be great!

Hint: Try float voltage = ((sensorVal/1024.0) * 5.0);

FYI, your intermediate results are truncated, not rounded. ( 0/11 will yield 1, since the answer is ≈1.81, and it simply strips away the decimal part. By comparison, round(20.0/11.0) will give you a value of 2.0, since 1.8181 rounded rounds up to 2.)

You are doing integer arithmetic. Try adding .0 to the end of your values where you need the floating point results.
For example...

  float voltage = ((sensorVal/1024.0) * 5.0);

Remember the results of analog read is an integer. So the conversion to a float in you original code only happens when the "=" is being "executed". Another possibility is to cast it to a float straight away.

  float voltage = ((((float)sensorVal)/1024.0) * 5.0);

Or more simply

  float voltage = ((float)sensorVal)/1024.0 * 5.0;

This helped a lot. I realized that I should have also initialized my sensorVal as a float

You already got a couple of perfectly good answer. I will nevertheless
suggest a slightly different idiom:
float voltage = sensorVal * (5.0 / 1024);

or, maybe better:
const float V_REF = 5.0;  // at the top of the sketch

float voltage = sensorVal * (V_REF / 1024);

The reason this is slightly better than the other options is because
division – even integer division – is a very expensive
operation on the smaller Arduinos. By writing the conversion as in the
lines above, the ratio V_REF / 1024 becomes a compile-time constant,
which is evaluated by the compiler at build time. Then, only the much
cheaper multiplication needs to be done by the Arduino itself, at run
time. Not a big deal if you are not time constrained, but it's a
low-hanging fruit in terms of optimization.
You may write 1024.0 instead of 1024 if it feels safer. I tend to
keep the .0 for the voltage only, because 1024 is an integer, whereas
the “5” in “5 volts” is conceptually a real number (it's an
analog voltage, and not even exactly 5 V if you bother to measure
it). But this is just a personal preference at the end.

Good point on avoiding runtime division. (voted)

I must admit @edgar_bonet, I found what you said very hard to believe - after all one of the things that an optimising compilers should check for is "constant arithmetic" and "work it out for you" and just apply the result. That is, x / 1023.0 * 5.0 should be optimised as (X / 204.6) . Since I didn't believe you (sorry about that), I tried a simple program and was stunned to see that it actually executes the division of the constants in the generated assembler - unless you put that part of the expression in parenthesis.

What was also of interest was that in my first version I simply put int reading = analogRead(A0);  float result = reading / 1023.0 * 5.0; in my setup() function with nothing else. Long story short, the compiler optimised the whole block of code out of the generated assembler (because I wasn't doing anything with the result). It wasn't until I put in Serial.println(result); that the calculation was emitted by the compiler.
I was going to down vote you ('cos I thought you were wrong), but after checking and found you were right - you get an upvote from me to.

@GMc: The compiler cannot optimize x / 1023.0 * 5.0 into x * (5.0 / 1023.0) because the two expressions, although equivalent in the realm of real numbers, are not equivalent for floating point numbers. The compiler is not allowed to perform an optimization that can possibly modify the result of a computation. That is, unless you give it an option like -funsafe-math-optimizations, which is off by default.

@edgar_bonet thanks for the insights and the great addition to the answer I will definitely explore this further.

GMc explained what to do, but didn't explain in detail why your code fails to give floating point results.
Most languages evaluate expressions using order of operations. C and C++ are no exception to this.
In C/C++, while the expression is being evaluated, the compiler also decides what data types to use for each part. integer-integer expressions are evaluated using integer math. If either of the parts of an expression is a larger/floating point type, both values are "promoted" to the larger/more complex type before evaluating the expression.
in your code
float voltage = ((sensorVal/1024) * 5);

The sensorVal/1024 bit is evaluate first. Since both sensorVal and 1024 are integers, the compiler uses integer math. That yields an int result, and so any fractional part is truncated and lost.
It then evaluates result*5 (where result is the result of the first part, sensorVal/1024, which is an integer.) Both of those parts are integers, so the result of that expression is an int.
Finally, you ask the compiler to store the result into a float, voltage. The compiler then promotes the integer result of the whole expression to a float, but you've lost any floating point part of your calculations.
By rewriting your line as
float voltage = ((sensorVal/1024.0) * 5.0);

The compiler does what you want. The sensorVal/1024.0 bit is now integer-float math, so the compiler "promotes" sensorVal to a float and then does float-float math. The second part is now float-float, so the result is also floating point.
float voltage = ((sensorVal/1024.0) * 5);

Would also work in this case (where 5 is an integer constant.) That works because float_result*5 is float-integer math, and the compiler will promote 5 to a floating point value and do float-float math. to get the final result. However, it's safer to use all floating point constants so you don't accidentally do part of your calculations using integer math and truncate that part before converting to floating point.
As you say, making sensorVal a float also would be a good idea. (Again, to avoid accidentally doing integer math on part of your expression and getting wrong results in the process. In this case making sensorVal a float isn't needed, but with a different expression you might wind up with integer math for part of the calculation.)


text:
New to arduino, help wiring relay
I am new to arduino and need some help. I just baught light bars for my jeep and wiring harnesses with them, the harnesses come with buttons and I wanted to replace the button and have them controlled on my phone. The harnesses come with a relay and a fuse and a button all 12v, How would i go about using my raspberry pi or udoo x86(which has built in adruino) to basically replace the rocker switch so i can then turn things on and off without needing to have actual switches.

a simple MCU can do it. no need to have a computer for this. use Arduino Nano or Mini

Google: "Arduino relay" and look at the pretty pictures.

Or, if you don't want to mess with the harnesses electronic, you can bridge the buttons using a MOSFET, which can be directly controlled by Arduino or the Pi.

To drive a relay you'll need a transistor (a MOSFET is a good choice) and you'll need a diode across the relay coils to protect the transistor from the reverse current pulse when you remove power from the relay coils.
As Majenko says, if you Google "Arduino relay" you'll find lots of articles covering the topic. (And if you use a digital output line from your PI the exact same circuit will work.)
This MOSFET is a good option for switching high current loads with a 5V logic signal:
https://www.adafruit.com/product/355
The diode will need to be a power diode that can handle your voltage/current needs. You'll need to figure out how much current your light bar uses, and then I'd suggest a diode that can handle twice that much current (at 12V) for a margin of safety.

Re “handle twice that much current (at 12V)”: Not at 12 V. It should handle the current when forward biased, and the voltage when reverse biased.

why not MOSFET only

An inductive coil like a relay coil dumps a large surge of reverse current when you remove power from it. (sometimes called "flyback current".) That is enough to destroy a transistor, so you need a diode to protect the transistor.

how do i see how much current the lights bar uses, can i just use the volts and amps that the relay says on it? also things say i need a resistor, how do i choose that also.

http://henrysbench.capnfatz.com/henrys-bench/arduino-output-devices/tip122-arduino-relay-tutorial/ this is the circuit i think i will use with the mosfet, does each mosfet use a different ground or all the same

I meant without the relay

@Juraj, sure, you could skip the relay and drive the light bar directly without the relay. In that case it would be a straight inductive load and you wouldn't need a protection diode. To the OP, it would be simpler to get rid of the relay from your harness and control the lights directly with a MOSFET like the one I linked in my answer. You can drive that MOSFET's gate directly with a logic line from a PI or Arduino, and it will switch a large amount of current (although you'll need a heat-sink for larger current loads - see the specs.)


text:
How does use an arduino like a A/D converter for convert 3 analogue signal from 3 poteciometer to a raspberry?
I am developing a control system in my raspberry, but i have the problem that it doesn't have any analogue port, so if i use an arduino to convert de signal from analogue to digital and after send this signal into a I/o digital port from anduino to raspberry, thas is posible?
my plan was receive the analog signal in arduino and transforms here in a digital signal and after send it by Digital port to rasberry

It is not clear what you mean by “digital port”. The simplest mean to
communicate from the Arduino to the Raspberry is to use the Arduino's
serial port, which gets into the Raspberry Pi through USB. Just like you
would do if you had a PC instead of the Raspberry:
/*
 * Continuously report the analog readings on pins A0 through A2.
 */

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

void loop() {
    Serial.print("0 "); Serial.println(analogRead(A0));
    Serial.print("1 "); Serial.println(analogRead(A1));
    Serial.print("2 "); Serial.println(analogRead(A2));
}

This program will continuously output a text stream like this:
0 145
1 220
2 865
0 142
1 223
...

where the first column is the analog channel number and the second
column is the ADC value. How you handle this stream on the Raspberry
side is up to you.

i could manipulate this data in my rasberry? to make a controller?

@JesusMiguelHerrera: Of course! It's your data, you do whatever you want with it.

the last question, how could i activate the serial port in my raspberry with the goal of receive this signal?

@JesusMiguelHerrera: On the Raspberry side, the serial port (usually /dev/ttyACM0) is activated by connecting the USB cable.

thank you edgar i will proud this


text:
Shield Compatible third party motor driver
I recently purchased an Arduino UNO along with some other hardware. At the time of purchase, I didn't know about Arduino's motor shield and so I purchased a two channel stepper motor driver (2A per channel) that was said to be "Shield Compatible". I recently received my hardware and have been following the introductory tutorials since I'm completely new to the Arduino platform. Things are going well but I didn't receive any documentation with the motor driver. There is a datasheet provided on the vendor's website but it is beyond my current level of competency.
My question: since the driver is said to be "Shield Compatible", does this mean that I can assume that I can interface with it the same way as an authentic Arduino shield. In other words, can I follow the motor shield tutorial on Arduino's website without any risk of damaging hardware and expect the driver I purchased to function properly.
The product that I purchased can be seen here: http://www.robotshop.com/ca/en/dual-bipolar-stepper-motor-controller-arduino.html

You should do you own research as the path followed here did not result in the identically pictured nor identically model numbered item.
You indicated you are using a certain Arduino motor driver board.  On that page there is an "made by" or "by" reference to an OEM.  On the OEM's web page there is a "Dual Bipolar Stepper Motor Shield for Arduino" but the part number and the picture do not (exactly) match your original link.  Regardless, there is what they are calling a "WIKI page" for this (slightly) different motor shield.  I scanned this page and the example code.  I don't see where any device driver is mentioned.  And I don't think the code will compile by its self.
In general, I suggest people who are starting out with Arduino's to stick with well known hardware and software.  Even then I have had problems with newly released hardware.  Also check if drivers and SDKs have been updated each time you start a project.
Another approach you might entertain is to follow a path starting with the chip used on your shield.  It appears to use two DRV8825.  (But I cannot be sure as pictures and model numbers do not (exactly) match.) Here is a discussion on the a well known Arduino web site where people are talking about boards with this chip on it.

Thanks. After a lot more reading, I connected the driver board onto my Arduino, powered it with an external supply and ran the code on the WIKI page that you linked to and everything is working fine.

Good to hear you had success!


text:
Circuit requirement for Arduino Due custom circuit without the ATMEGA16U2
I would like to create a custom Arduino board based on the Arduino Due. Upon looking at the Due's schematics under the documentation tab there are some stuff that i do not need and removed them. the last thing that i want removed is the ATMEGA16U2. This part just takes so many components that i want it removed.
I would like to build my code using the arduino IDE and with the 16u2 gone i do not know a way how to upload my codes.
This seems to be possible since under the documentations there is a native usb port of the due that is directly connected to the SAM3X8E,
from here on out im lost what how do i upload my code to the same sam3x8E
Special tools that i have that might be usefull:

J-link EDU Mini
USB to UART

My Current draft schematics:

Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool)

@Majenko thank you good sir, the erase button is handled by the 16u2 and without it how will i erase the flash? which means i basically can upload only 1 code and thats it, which is kinda not ideal

You add a button (or a jumper) to your schematic.

@Majenko wait what ?? "Opening and closing the Native port at 1200bps" from the documentation can be done by  shorting PC0 ? or im misunderstanding, can you elaborate from where to where will the jumper be connected?

There are two ways of entering the bootloader: 1. Wipe the flash with the ERASE button (or trigger from 16U2). 2. Open the native port at 1200 baud. The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button. It should be there in the schematics already - did you erase the erase button?

Oh i get it now, i might have misunderstood the the erase button, the line from the 16u2 is parrallel to the reset button so it is an alternative, okay got it. A follow up question in actually uploading the code the steps are: plug the usb -> press the erase -> click upload on the IDE ? is this the right sequence?

Possibly. I'm a bit rusty on the Due - not having used it for ages. But I seem to recall that's how it works, yes.

If you may post the your comment as answer good sir, i would like to mark it as the correct answer.

Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool).
There are two ways of entering the bootloader:

Wipe the flash with the ERASE button (or trigger from 16U2).
Open the native port at 1200 baud.

The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button.
You can either provide a physical button (as shown in the existing schematics) or a simple jumper that can be shorted when erasing is needed.

By the way, does the reset pin (PC0) need to be pulled down ?

To erase? I can't remember. You'll have to check the datasheet.

It has internal pull-down resistor about 100k. So it can be left unconnected for normal operations.

@KIIV thanks for that !


text:
How to conect multiple output pin from sensors to a single digital pin on a arduino
Hello i have several power management IC that have an active low indicator for a fault, it would be a waste to dedicate a single digital pin for each of them. So i thought of  to interface them to a single digital pin. I do not need to know which of them has a fault, i just need to know that there is a fault.

How do i safely do this? and as a follow up question if the fault voltage is 5v and the arduino pins only take 3.3v how do i shift it down with minimal components. can i just add a resistor in series?

If the ICs output 5V and your Arduino is 3.3V, you can simply use one voltage divider at the Arduinos pin to divide the voltage down to 3.3V.
But there is still one important thing to connect them safely: You have to check, if the outputs of the ICs are driven actively high, when no fault occured, or if they simply use a pullup resistor internally.
A pin, that is actively driven high, does not have an overcurrent protection. So, if one IC would pull it's pin to low and the others are still high, a high current would flow between them, potentially destroying them. In that case you need current limiting resistors in series with the ICs (directly at the ICs, so that the resistors are between them).
On the other side, if the ICs output a high level through a pullup resistor, you are safe to connect them directly, as there can only flow a very little current through the pullup resistors. Often such a situation is called Open-Drain (passive high level through pullup resistors, active low level by driving the pin to low through a MOSFET, like used in a digital output pin). In that case you don't need the current limiting resistors.

EDIT: The datasheet of the ICs, that you linked to states that the fault output is an

Active-low open-drain output

Also the example circuit shows an external pullup resistor. That means, that the fault pin is internally connected to a MOSFET, which will connect the pin to ground in case of a fault. Otherwise the pin is floating. The external pullup resistor will pull the pin state to a high level, when the MOSFET is not activated. This is good for you, since you can now simply use 1 resistor (one resistor is enough for all ICs), to pull the level up to 3.3V. Then you directly have the correct level for your Arduino and you don't need a voltage divider.

according to the datasheet sample circuit fault is pulled up so does this mean that the voltage divider  and a pull up ? is the only thing i have to change in my circuit

Ah, yes. Though, since the IC doesn't use an internal pullup, you can simplify the circuit by directly pulling up to 3.3V with an external resistor instead of to 5V. Then you don't need the voltage divider. The high level will then be 3.3V. I will add this to the answer

oh yes ! thats an amazing trick to do. pulling it up to 3.3 thus reducing the components. Thank you good sir. Additional question good sir, do i have to adjust the pull up resistor so that the line all have 10k resistance equivalent on them , or it does not matter?

Or you can use the Arduino's internal pull-up.

@EdgarBonet or that . but i think its a good design practice to include one anyway :)


text:
Interrupts inside a class attaching to the function of the class
Hello i have a class and i would like to attach an interrupt inside the class and attach it to a function of the class.
class counter{
  public:

  counter(int pin){
    Ipin=pin;
  }
  void startCounting(){
    attachInterrupt(digitalPinToInterrupt(Ipin),this.addCount,CHANGE);
  }
  void stopCounting(){
    detachInterrupt(digitalPinToInterrupt(Ipin));
  }

  void addCount(){
    count++;
  }

  private:
  int Ipin;
  unsigned long count= 0;
};

Some what of the code above. There can be multiple intialization of this class. hopefully depending on the user uses a different pin.
There is a way arround this where the attaching of pin is done in the loop or setup and just calling a public function of the class. But to me that kinda doesn't fit the spirit of classes like a properly made library is done.
Im not very good at programming if you could teach me how it would be greatly appreciated.

I's not supported by attachInterrupt. You need some function that calls that desired method.

@KIIV so how do libraries with interrupts do it?

By using some function that calls method on specific object. You can't use more callbacks for the same interrupt source anyway.

So if we go by what you have said and to lets say i were to create a library. I would have 2 fuunctions that does not belong to any class in the .h or .cpp that  first function attaches the interrupt to the second function, and that second function calls a method of the class?? Is it possible to call a global function inside of a class?

I have a post about this problem.
Basically you cannot attach a class function with attachInterrupt because of the hidden "this" pointer which needs to be supplied to a (non-static) class function, where "this" is the particular instance of the class. You can work around it like this:
class myClass
  {
  static volatile bool switchChanged;  // declare

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);
    }  // end of myClass::begin

  static void switchPressed ()
    {
    switchChanged = true;
    }  // end of myClass::switchPressed

  };  // end of class myClass

volatile bool myClass::switchChanged;  // define

myClass foo;  // make an instance of myClass

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

void loop ()
  {
  // whatever
  }  // end of loop

But that isn't great because, as you observed, you are really downgrading the class to use a static boolean.

Another way of doing it is to write "glue" routines, like this:
class myClass
  {
  volatile bool switchChanged;

  static myClass * instances [2];

  static void switchPressedExt0 ()
    {
    if (myClass::instances [0] != NULL)
      myClass::instances [0]->switchPressed ();
    }  // end of myClass::switchPressedExt0

  static void switchPressedExt1 ()
    {
    if (myClass::instances [1] != NULL)
      myClass::instances [1]->switchPressed ();
    }  // end of myClass::switchPressedExt1

  public:

  void begin (const byte whichPin)
    {
    pinMode (whichPin, INPUT_PULLUP);
    switch (whichPin)
      {
      case 2:
        attachInterrupt (0, switchPressedExt0, CHANGE);
        instances [0] = this;
        break;

      case 3:
        attachInterrupt (1, switchPressedExt1, CHANGE);
        instances [1] = this;
        break;

      } // end of switch
    }  // end of myClass::begin

  void switchPressed ()
    {
    switchChanged = true;
    }

  };  // end of class myClass

myClass * myClass::instances [2] = { NULL, NULL };

// instances of our class
myClass foo;
myClass bar;

void setup ()
  {
  foo.begin (2);   // pin D2
  bar.begin (3);   // pin D3
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

That's still not a great solution, but it might give you some ideas.

Your fundamental problem is that classes, by their nature, can be instantiated many times, however you only have a small, fixed, number of interrupts on the microprocessor.

Thank you for the great reference, the "glue" solution would work for me because i  am using a custom built board and there is a fix number of pins to interrupt. I just want to take the trouble off the user when using the library, when begin is called on my main class all the interrupts should be ready to go. Atleast i wont have to make a function on all interrupt pins (60+ pins = 60+ functions on due). Thank you again for the answer.

I can understand it would cause trouble where the number of instantiation would exceed the number of interrupts the processor. Although that can be fixed by adding protection macros that throws an error if the number of instantiation exceed the number of interrupts,but that would be a lot of macros for each board you want your class to work.


text:
Flame sensor and MQ2 sensor not working with Esp8266?
When ever flame is detected sms will be send this is what i am doing,but the  flame and smoke sensor works awesome when they are tested seperately(Without Esp8266) when they are integrated with Esp8266 they are not at all responding to the flame or smoke . I have tested flame Sensor with serial monitor the values are 150,148,147,......
When it is tested without Esp8266 it has given 1000,996.....(Without Flame)
52,64,38.....(With Flame )

Flame sensor Connections:
VCC : 5V
GND : GND
D0 : 7`
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const char *ssid = "NUS_006";
const char *password = "shankar006";
int flame=7;
void setup() {
    delay(1000);
    pinMode(flame,INPUT);
    Serial.begin(115200);
    WiFi.mode(WIFI_OFF);
    delay(1000);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    Serial.println("");
    Serial.print("Connecting");
    while (WiFi.status() != WL_CONNECTED) {
           delay(500);
           Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
}

void loop()
{
  Serial.print("Flame= ");
  Serial.println(digitalRead(flame));
  delay(3000);
}

your sketch is for the esp8266. you have an esp-01 module like on the picture? you wired the sensors to Uno and expect that the esp8266 sketch will read them by some magic?

thanks for responding so what should i do to read the sensor values?-Juraj

do you have an esp-01 module? then you can't connect sensors to it and you must work with sensors in Uno. put some firmware into esp-01 and use it as WiFi adapter. (or create your own 'firmware')


text:
what is this ets Jan 8 2013,rst cause:4, boot mode:(1,7)
i dont have any idea about this problem. can anyone help me how to fix this?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "NUS";
const char *password = "s006";
int lo=16.3441;
int la=80.5243;
const char *host = "http://smshorizon.co.in";
void setup() {
   delay(1000);
   Serial.begin(115200);
   Serial.println("Start");
   WiFi.mode(WIFI_OFF);
   delay(1000);
   Serial.println("Status");
   WiFi.mode(WIFI_STA);
   Serial.println("Begin...");
   WiFi.begin(ssid, password);
   Serial.println("");
   Serial.print("Connecting");
   while (WiFi.status() != WL_CONNECTED) {
       delay(500);
       Serial.print(".");
    }
   Serial.println("");
   Serial.print("Connected to ");
   Serial.println(ssid);
   Serial.print("IP address: ");

   Serial.println(WiFi.localIP());
 }
 void loop() {

  }

Sometimes it shows boot mode(1,0)

Do some further debugging so you can tell us where this error occures. Remove theWiFi.mode() lines, those should not be necessary in your case. Another vague guess: add a delay in your loop, I'm not sure if the compiler will do anything dump when there is no loop

Something else: 163441 is not an int. But I don't think that's a problem. It simply doesn't make sense

the 1 indicates that you have io 15 LOW, io 2 HIGH and io 0 LOW. and the esp8266 starts in flashing mode. pull io 0 up to start the sketch

reset cause 4 is watchdog reset. your sketch stops so the watchdog resets it


text:
How do you move motor car forward for set amount of time and turning left/right
Am new to Arduino, wanted to know how to give motor direction to move and the duration of those movements. Goal is to move forward for say 5 seconds, turn left, move for 0.5 seconds, turn right, move for 5 seconds.
void loop() {
  //turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(ENA, 100);
  //turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  analogWrite(ENB, 100);
  delay(1000);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(5000);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  delay(500);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(500);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(5000);

do you have a question about your program? .... it is unclear why you posted the program listing ........... your program looks vaguely familiar ..... you named  the output pins in1, in2 etc.  ..... that sort of thing sticks in memory

Are you following a specific tutorial? There are plenty of good ones available. Let us know what you have achieved so far. For example, have you got a motor connected and spinning? What code did you use for that? Please delete any non-applicable code and give us what you have done so far.


text:
Powering an Arduino directly from a motor driver (DRV8825) or external power source?
Hello people from StackExchange,
I'm new to Arduino and driving stepper motors in general; please excuse me for my limited knowledge on the subject. I've been doing research for a few hours already, looking into powering stepper motors and the Arduino, though I've gotten conflicting information regarding my problem.
My problem, or well question if you will, is as follows:
The circuit I need, simplified, contains an Arduino, a stepper motor driver (DRV8825), a NEMA17 5kg.cm stepper motor and a 12V battery pack (yet to be decided what kind of pack, though it will be 12V). Do I need another, lower voltage, battery pack?
After looking into how to power stepper motors using the Arduino online, I found several sites instructing me how to do so. All of the sites had the same circuit I would use, only the motor was different. Here is one of the circuits:

As you can see, it only has a single power supply (with capacitor to catch voltage peaks). I understand most of the circuit, though one question remains: why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver? (You can see the pin descriptions in the second image below) Or do they simply not show the (5v) power supply for the Arduino?
The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not? And if not, would connecting the Arduino to the power supply via the VIN pin work? That would be nice, as it would offer a simple way of fixing the problem instead of getting a separate power source. Connecting the Arduino through USB wouldn't work for my project, as it can't have any wires coming from it. It needs to be completely mobile.
For comparison, here is a circuit that does show the Arduino with an external power source:

I'm a first years mechanical engineering student, hence my little knowledge on Arduino's and stepper motors.
Thanks in advance.

The Arduino and the motor driver still need to have a 5V power supply.
In the circuit, the motor driver is supplied with 5V logic power from the Arduino board - the Arduinos power source has been omitted.
You can use your motor power supply to input power to the Arduino via the VIN pin or the DC jack and use the onboard 5V regulator for that task, but beware of the regulators heat dissipation at 12V.

why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver?

No. It is assumed that you will provide the power to the Arduino yourself - either through the USB connection to the computer, or through the barrel jack.

The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not?

No. The Arduino requires power to be provided.

And if not, would connecting the Arduino to the power supply via the VIN pin work?

Yes, but it's not ideal.  At 12V the power wasted by the on-board linear voltage regulator will be proportionally high.  As long as all that is being powered is the Arduino itself that shouldn't be too bad, but if you try to draw any significant current either out of the 5V pin or through multiple IO pins (for example to drive lots of LEDs) then it will overheat and potentially shut down.
A more ideal arrangement would be to connect a 5V switching regulator to the 12V battery and use that to power the Arduino either through the 5V pin or the USB connector. Personally, I use cheap UBEC modules from RC model suppliers. They are small, low-cost, and very easy to wire up.


text:
Single-channel serial communication
I'm trying to communicate with a device which only uses a single wire at 9600 Baud. How can I use my Arduino UNOs RX/TX-Pins to recieve and transmit on that one wire?

Please edit your question to include part # and/or datasheet link for the device.  Presumably it uses some communications protocol which you have left us to guess at.

Connect the data wire to RX, and connect RX to TX through a a 10K resistor?

Maybe it only communicates one way?

A bus called OneWire exists and may be what you are looking for. Just guessing. And you need to connect the ground of the devices too. So you will end up with two wires.

Bidirectional Asynchronous Serial schemes are not uncommon.  The famous ones, like RS485, utilize special line drivers and differential signalling, but for short distances you can accomplish something similar using the ability of most MCU's, including the Arduino's ATmega, to tristate the serial transmit pin.
Essentially, you would wire the shared line to both the receive and transmit pins, and when it is not the Arduino's "turn" to transmit, you would configure the Transmit pin as an input rather than as an output.
It's then up to a software protocol to make each node transmit at only the appropriate time.  Often a bus master can transmit essentially at whim, and subservient device(s) are only allowed to transmit in reply to specific queries from the master.  Of course the master should not transmit when it has just request a reply.
Also note that you cannot change the pin over to input mode when the last character is loaded into the UART, rather it has to stay in output mode until the last sent character has been clocked out onto the wire.
While putting a resistor between the transmit pin and the shared line could provide some theorectical safety against bus contention introduced by software errors, in practice the hardware will typically survive such conflicts during development, and having too large a resistor there may cause problems with signal quality.  If you are going to use a resistor, it should be sized for source termination of the line impedance, not for electrical protection.  You may also want a weaker pulling resistor to give the bus a known state when no one is driving it.  If this state matches the last driven one, the resistor won't have to overcome capacitance to "drive" the line, but rather merely "hold" it in the last driven position.
If you are using a device like the Uno which has only one hardware serial interface, you will have to decide if you are going to use the hardware interface at the cost of breaking the ability to use that to debug or upload sketches, or if you are going to use a software UART ("Software Serial" or its variants) on arbitrary digital pins.  If you do the later, it would be entirely possible to rework a library to receive and transmit on the same pin, rather than requiring two distinct ones.


text:
SoftwareSerial and HardwareSerial lost data
I need two Serial ports. One port is some sort of modified Software Serial, where I have to be listening constantly and send responses immediately if the port requires it. There is no XY problem hidden here, promise.
On the other hand I have a device on the hardware serial.
If I'm listening on the Software Serial, sometimes I lose data on the hardware serial. How can this be? Isn't the Hardware Serial "hardware", meaning independent of the CPU?

Software Serial turns off interrupts. Depending on the baud rate, they may be off for so long that the interrupt generated by the hardware serial is not serviced in time. Depending on the chip, the hardware serial may only have a buffer of a couple of bytes. Turn off interrupts long enough and one will be lost.
The external interrupts are higher priority than the UART interrupts, which won't help. I am referring to the Uno here.
It would help in future if you provide code to reproduce the situation, and also state what Arduino you are using. The lack of information about that in the question would be why you were downvoted.


text:
Solenoid "vibrates" instead of pushing
I'm using my Arduino Uno to control a 5V 1A solenoid.
I'm using an N-Channel MOSFET linked to the Uno's 0 pin to switch the solenoid on and off. It is protected by a Schottky diode. Initially, I tested the circuit with the blink example sketch (just set to blink Pin 0 instead of Pin 13). I used the Uno's built in 5V 500mA output and the solenoid "blinked" on/off perfectly at whatever interval I wanted:

I plan on controlling multiple solenoids in a future version, which will draw more current than the Arduino output can supply, so I bought a 5V 12A power supply. I proceeded to test it with my single-solenoid set up using the same blink example sketch:

When I power the solenoid with my 5V 10A my power supply, the solenoid doesn't push on command. It merely "vibrates," travelling only about .5mm at several hundred Hz. The solenoid vibrates constantly the moment I plug in the power supply, and does so completely independently of whatever interval I have set it to "blink."
Any ideas as to what may be causing this to work with the Arduino's built in power supply, but not with an external power supply? I've tested the voltage on my power supply, and it reads 5V as advertised. I'm somewhat new this, and feel like I may be missing something obvious.
Thanks,
Max

https://majenko.co.uk/blog/importance-sharing-grounds

From your schematics it looks like:

you connected the power supply backwards (on both schematics actually, I wonder how come you did not fry your Arduino)
the external supply and the Arduino do not share a common ground as they should.

Edit: about the orientation of the power supply:

the (−) side of the supply (and GND of the Arduino) should be connected to the source of the N-MOSFET
the (+) side of the supply should be connected to the cathode of diode (the side identified by the small white bar)

Could you please elaborate on what you mean by the power supply being connected backwards?


text:
how to increase the delay factor of DHT11?
There is no compiler error but output is showing timeout error.
as per as the instruction given in
https://github.com/RobTillaart/Arduino/issues/61
it says to increase the timeout factor but i did not found the constraints which were asked to be changed.

I think you need to change the library files themselves.

He has five dht libraries. Do you know which one you are using? The problem might be the nodemcu in combination with the library and the sensor. The dht11 and dht22 might behave differently than a few years ago. Some libraries cause a shortcut in the data signal, which is a serious problem for the nodemcu. The 'DHTLIB_TIMEOUT' is declared in the .h file. To be compatible with all arduino board, a timeout should be in milliseconds.

I didn't find any constraint named  DHTLIB_TIMEOUT which should be there in .h file.
I am using a NodeMCU board and i have tried three different DHT11 libraries but none of them seems to work.
can you provide me the  links from where can i download the necessary library

I don't know, there are so much more than 3 libraries. The libraries for the dht11 for a esp8266 is a big mess. Even the nodemcu code has troubles with the (newer) dht11 sensors: https://github.com/nodemcu/nodemcu-firmware/issues/2253 Which libraries did you try? Do you use a pullup resistor? What is the value of that resistor? Do you use long wires? Do you have another dht11 sensor, perhaps this one is broken. If you want to know the humidity then perhaps you should buy a better sensor with i2c. The dht11 returns a number that has little to do with the humidity, it is not accurate.

The dht11 that i was using had an onboard pull up register and i didn't use any sort of wire just jumper cables for minimalist connection.and i have tried 2 different sensor but all produced NAN value
I think instead of taking all this burden i will go for an i2c sensor.
Thanks a lot @Jot

I will make an answer for it.

The DHT11 and DHT22 used to be cheap and easy to use humidity and temperature sensors when they were used together with an Arduino Uno.
But things have changed.

They are not accurate and can become totally inaccurate with certain
gasses or fumes.
It turned out, that the most used DHT libraries have
a serious bug that creates a shortcut in the datasignal.
This was no problem with the Arduino Uno, which can output
40 mA with a pin. The newer processors have problems with
that shortcut.
In 2018 the DHT11 seems to behave differently,
the internal controller has probably changed.
Because the communication with the sensors requires accurate timing,
the interrupts are turned off temporarily. That was no problem
with the slow Arduino Uno, but it is not normal with
a faster processor.
Some libraries use a timeout with a loop or with clock cycles.
That worked well with the Arduino Uno,
but it is not always reliable with newer processors.

In 2018, all the DHT libraries for the ESP8266 and ESP32 have issues with the DHT11 and DHT22.
Since the sensors are not very accurate anyway, it is best to stay away from all the troubles and avoid them. There are a number of good humidity sensors with I2C interface.