text:
Programming Problem with a hand gesture controlled robot; the analogwrite() function doesn't work
So I recently tried to make a hand gesture controlled robot but ran into some programming error. Here are the specs:
For the transmitter module, I used the following:
*Arduino Nano 3.0 as the Microcontroller development platform
   *Grove 3 axis digital accelerometer 16g for sensing hand gesture
   *RF transmitter 433 Mhz (Transmitter: JMR-TX1)
   *Power source: 7.2V rechargeable battery unit to power up the Arduino Nano
For the robot, I used the following:
  *Pololu Chassis
  *Two DC geared motors, compatible wheels
  *L293D Dual DC motor controller module
  *Arduino Nano 3.0
  *RF receiver 433 Mhz (Receiver: RXB6)
  *Power source: 7.2V rechargeable battery unit to power up the Arduino Nano
I hooked up all the parts carefully. I uploaded the code entitled "Transimitter_code" to the transmitter. I uploaded a code called "Receiver_test" and used serial monitor to see if the robot's arduino received data from the transmitter, the data I wanted to receive was the angle that the accelerometer was tilted on x and y axis measured by the accelerometer. Fortunately, the Arduino was receiving data wirelessly and displaying it in the serial monitor, which means my basic concept was ok. You can see the code attached to this thread. P.s. You will need three libraries: Wire.h, VirtualWire.h and ADXL345.h to run the codes. You can google them up and get them for free. See the code for the transmitter below:
/* Code for the transmitter of the mind controlled bot */

#include <Wire.h>
#include <ADXL345.h>
#include <VirtualWire.h>

ADXL345 adxl; //variable adxl is an instance of the ADXL345 library
int ledPin = 13; //a sign when the transmitter is working

int TX_PIN = 11;// Tell Arduino on which pin you would like to Transmit data NOTE should be a PWM Pin
int TX_ID = 3; // Transmitter ID address

typedef struct roverRemoteData// Data Structure
{
 int    TX_ID;      // Initialize a storage place for the outgoing TX ID
 int    x1;// Initialize a storage place for the first integar that you wish to Send
 int    y1;// Initialize a storage place for the Second integar that you wish to Send
};

void setup() {
 vw_setup(2000);//Bits per second
 pinMode(ledPin,OUTPUT);
 vw_set_tx_pin(TX_PIN);// Set Tx Pin
 Serial.begin(9600);//Initialise the serial connection

 adxl.powerOn();

//set activity/ inactivity thresholds (0-255)
adxl.setActivityThreshold(75); //62.5mg per increment
adxl.setInactivityThreshold(75); //62.5mg per increment
adxl.setTimeInactivity(10); // how many seconds of no activity is inactive?

//look of activity movement on this axes - 1 == on; 0 == off
adxl.setActivityX(1);
adxl.setActivityY(1);
adxl.setActivityZ(1);

//look of inactivity movement on this axes - 1 == on; 0 == off
adxl.setInactivityX(1);
adxl.setInactivityY(1);
adxl.setInactivityZ(1);

//look of tap movement on this axes - 1 == on; 0 == off
adxl.setTapDetectionOnX(0);
adxl.setTapDetectionOnY(0);
adxl.setTapDetectionOnZ(1);

//set values for what is a tap, and what is a double tap (0-255)
adxl.setTapThreshold(50); //62.5mg per increment
adxl.setTapDuration(15); //625us per increment
adxl.setDoubleTapLatency(80); //1.25ms per increment
adxl.setDoubleTapWindow(200); //1.25ms per increment

//set values for what is considered freefall (0-255)
adxl.setFreeFallThreshold(7); //(5 - 9) recommended - 62.5mg per increment
adxl.setFreeFallDuration(45); //(20 - 70) recommended - 5ms per increment

//setting all interrupts to take place on int pin 1
//I had issues with int pin 2, was unable to reset it
adxl.setInterruptMapping( ADXL345_INT_SINGLE_TAP_BIT,   ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_DOUBLE_TAP_BIT,   ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_FREE_FALL_BIT,    ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_ACTIVITY_BIT,     ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_INACTIVITY_BIT,   ADXL345_INT1_PIN );

//register interrupt actions - 1 == on; 0 == off
adxl.setInterrupt( ADXL345_INT_SINGLE_TAP_BIT, 1);
adxl.setInterrupt( ADXL345_INT_DOUBLE_TAP_BIT, 1);
adxl.setInterrupt( ADXL345_INT_FREE_FALL_BIT,  1);
adxl.setInterrupt( ADXL345_INT_ACTIVITY_BIT,   1);
adxl.setInterrupt( ADXL345_INT_INACTIVITY_BIT, 1);
}

void loop()
{
struct roverRemoteData payload;
payload.TX_ID = TX_ID; // Set the Radio Address
int x, y, z;
adxl.readXYZ(&x, &y, &z); //read the accelerometer values and store them in variables  x,y,z
payload.x1 = x;
payload.y1 = y;
vw_send((uint8_t *)&payload, sizeof(payload)); // Send the data
vw_wait_tx();// Wait for all data to be sent
if ((x>80) || (x<-80) || (y>80) || (y<-80))
{
digitalWrite(13, HIGH); //ledpin indicator
}
else
{
 digitalWrite(13, LOW);
}
delay(100);

}

Now, I tried to use the received data to control the motion of the bot, that is: run the motors in specific direction. However, this time, the code seems to have some problem. Here's the code for the robot:
/* Mind controlled car - Car's code */

#include <VirtualWire.h>

int RX_PIN = 11;// Tell Arduino on which pin you would like to receive data NOTE should be a PWM Pin
int RX_ID = 3;// Recever ID address
int TX_ID;

typedef struct roverRemoteData// Data Structure
{
int    TX_ID;      // Initialize a storage place for the outgoing TX ID
int    x1;// Initialize a storage place for the first integar that you wish to Send
int    y1;// Initialize a storage place for the Second integar that you wish to Send
};

void setup() {
pinMode(5, OUTPUT); //in 1
pinMode(6, OUTPUT); //in 2
pinMode(9, OUTPUT); //in 3
pinMode(10, OUTPUT); //in 4
Serial.begin(9600);
vw_setup(2000);// Setup and Begin communication over the radios at 2000bps( MIN Speed is 1000bps MAX 4000bps)
vw_set_rx_pin(RX_PIN);// Set RX Pin
vw_rx_start();

}

void loop() {

struct roverRemoteData receivedData;
uint8_t rcvdSize = sizeof(receivedData);//Incoming data size
vw_wait_rx();// Start to Receive data now
if (vw_get_message((uint8_t *)&receivedData, &rcvdSize)) // Check if data is available
{
if (receivedData.TX_ID == RX_ID) //Check if the radio signal recieved matches the ID of the Reciever
{
  if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //halt
  {
    halt();

  }
  else if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && (receivedData.y1 > 80)) //forward
  {
    int a = receivedData.y1;
    goForward(a);

  }
  else if (((receivedData.x1 < 80) && (receivedData.x1 > -80)) && (receivedData.y1 < -80)) //backward
  {
    int b = -receivedData.y1;
    goBackward(b);

  }
  else if ((receivedData.x1 > 80) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //left
  {
    int c = receivedData.x1;
    goLeft(c );

  }
  else if ((receivedData.x1 < -80) && ((receivedData.y1 < 80) && (receivedData.y1 > -80))) //right
  {
    int d = -receivedData.x1;
    goRight(d);

  }
  }
  }
  }

  void goForward(int y)
  {
  analogWrite(5, y);
  analogWrite(6, 0);
  analogWrite(9, y);
  analogWrite(10, 0);
  delay(50);

  }

  void goBackward(int z)
  {
  analogWrite(5, 0);
  analogWrite(6, z);
  analogWrite(9, 0);
  analogWrite(10, z);
  delay(50);

  }

  void goLeft(int w)
  {
  analogWrite(5, w);
  analogWrite(6, 0);
  analogWrite(9, 0);
  analogWrite(10, 0);
  delay(50);

  }

  void goRight(int x)
  {
  analogWrite(5, 0);
  analogWrite(6, 0);
  analogWrite(9, x);
  analogWrite(10, 0);
  delay(50);

  }

  void halt()
  {
  analogWrite(5, 0);
  analogWrite(6, 0);
  analogWrite(9, 0);
  analogWrite(10, 0);
  delay(50);

  }

I wanted to use the analogWrite() function to control the speed of the motor. However, the code does not work at all if I use the analogWrite() function within the goForward(), goBackward(), goLeft(), goRight() functions to control the speed of the motor, only one of the motors keeps rotating at a certain speed without responding to the transmitter. Surprisingly, if I use digitalWrite() to control the motors, they work fine, instantly responding to the change in direction of the transmitter. P.S. I connected my motors to PWM pins of the Arduino.
What's the problem?

VirtualWire uses timer1, which would disable PWM on pins 9 and 10.

Oh God.. :( What should I do then? :/ I do need pwm to control speed of the motors. and the pins I have are 3,5,6,9,10,11 on the Nano.. Pin 11 is already in use by the radio receiver.. leaving me with 3,5,6..

The RX_PIN doesn't need to be on pin 11. So you could use that one and pin 3 for the motors, instead of 9 and 10.


text:
Using a L2938D Motor Driver Module. (Not IC, Module)
I have been trying to use my newly bought L293d Motor Driver Module to run motors(a single motor in this test case, simple 5V toy motor) from my Arduino UNO. Thing is, this is an entire module, not just the IC (in which case there are many tutorials available). So I was following this tutorial to try and get my motor running.
Here is the tutorial - http://www.instructables.com/id/Arduino-and-L293D-Robot-Part-1-/?ALLSTEPS
Here's what the module looks like -
There are 6 Pins on the module, which bring out the 6 inputs, EN1, EN2, IN1, IN2, IN3, IN4. Now since I am using only one motor, I connected my motor to the OUTPUT 1 & 2 header given on the module. I then take the 5V and GND from Arduino and connect them to my Module's 5V and GND header, (leaving the 12V one empty), I thought that this would be enough as my motor is also of 5V.
I then connected the IN1 and IN2 to the pins 7 & 8 on my Arduino and used the following code-
// Simple code to make the motor turn
int RightMotorForward = 7;
int RightMotorReverse = 8;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

Nothing happened. The motor didn't work and I have no idea why. I've gone through the entire datasheet for L293D but I found nothing that could help me. I suspect that it has something to do with the EN1 pin, but I don't really know how to use it, the tutorial said to connect it to 5V, which I tried but no results. So where am I making the mistake? How do I get this to work?

ooops. That 5V you are applying to 5V pin is actually an output pin.
You must apply some input voltage at the 12V & GND inputs.
Don't forget to remove that 5V connection to 5V pin

you can also try providing 5Vs from Arduino 5V output pin to module 12V input pin. that might also work.

I'm gonna try connecting the 12V with a 9V battery, that should be enough to run my motor shouldn't it?

that depends on how much current your motor is drawing...

I tried my above stated experiment and that did work. My battery was of no use after about 40 seconds though.. :P

While no one can tell you exactly how to connect that board without having its documentation or the board in hand to examine visually or with an ohm-meter, it is quite likely that by leaving the "12v" terminal unconnected, no power is being provided to the motor side of the circuit.
It kind of looks like there is a voltage regulator on board, so it may be that it will even provide 5v on that terminal when given something 7 volts (or so) or higher on the "12v" terminal - again, we cannot know without details of your exact board.
The L293 is an old and low-performing chip, with internal losses that mean  that to achieve 5 volts across a motor, you will need to supply very nearly 7 volts to the chip.  The difference gets wasted as heat.

Strangely there's no documentation or tutorials available for this on the internet, I'm gonna post a tutorial as soon as I can get it working. Anyways according to you this has nothing to do with the EN1 pin and I should try giving power to both the terminals right? I'm gonna keep the 5V power supply same and will add a 9V battery to the 12 V output, ground remains common.

No, I don't think you should power both terminals, rather, you almost certainly need to power the 12v.  And the EN pin is certainly relevant - it just is unlikely to be enough.  A 9v battery does not have the current capacity for a motor project - you need either a power supply or a series of connection of quality AA cells at minimum.

so uh, the EN1 pin just sits empty?

No.  Read the L293D data sheet.

I did. Acc to the datasheet the EN1 pin is to be connected to a 5v supply... I tried doing that but it didn't work.

Of course not - you still haven't powered the 12v pin.  But remember, even if you reverse engineer this board to the point of getting it working, it is still only going to work poorly.  Consider getting something not only better (FET rather than bipolar technology), but documented.

I see. I'll try wiring it that way. Actually I was planning to use the Motor Shield, but my teacher handed me the motor driver instead (most probably to test me), anyways, what do you mean by work poorly? Poorly as in taking time to respond, requiring more power or generating more heat?

Turning a lot of power into heat due to very high internal losses.  That chip along with its L298 brother, has long been obsolete.

Hmmm than shall I use it or are there better alternatives?

source: Stack Exchange

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

sort: votes


text:
Sketch behaves differently when motor driver is added
I have written a simple sketch that takes values via serial communication through a Python script.
Here's the code-
#define LEDPin 13

void setup() {
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
Serial.println("Ready");
}

void loop() {
char inByte = ' ';
if(Serial.available()){
 inByte = Serial.read();
}
if (inByte == 'L')
 digitalWrite(LEDPin, HIGH);
if (inByte == 'R')
 digitalWrite(LEDPin, HIGH);
if (inByte == 'S')
 digitalWrite(LEDPin, LOW);
}

Now this code runs perfectly fine with my python script. No problems at all. But When I add code for my L293D motor driver module, like this -
int E1 = 6;
int Left= 5;
int Right = 4;
char data = ' ';

void setup()
{
  pinMode(E1, OUTPUT);
  pinMode(Left, OUTPUT);
  pinMode(Right, OUTPUT);
  pinMode(13, OUTPUT);
  Serial.begin(9600);

  }

  void loop(){
    if (Serial.available()>0){
      data = Serial.read();
    }
    if (data =='L'){
      digitalWrite(E1, HIGH);
      digitalWrite(Left, HIGH);
      delay(2000);
      digitalWrite(Left, LOW);
      digitalWrite(E1, LOW);
      digitalWrite(13, HIGH);
    }
     if (data == 'R') {
      digitalWrite(E1, HIGH);
      digitalWrite(Right, HIGH);
      delay(2000);
      digitalWrite(Right, LOW);
      digitalWrite(E1, LOW);
      digitalWrite(13, HIGH);
    }
     if(data == 'S'){
      digitalWrite(E1,LOW);
      digitalWrite(Right, LOW);
      digitalWrite(Left, LOW);
      digitalWrite(13, LOW);
    }

     }

With this code added, the sketch, takes the first value it recieves, for example L, and then would go on executing the if block for that particular value ONLY. Even if the valueschange, still the same code block gets repeated. If I reset the Arduino, using the reset button, again the first value it recieves it starts executing the conditions of the same value and not the rest of the sketch.
P.S- I have attached the capacitor between the pins 5v and RESET.
EDIT
I put ser.readline() in my python script and found that no matter what the script only sends S to the Arduino. Even if the other two conditions are being satisfied, only S is send, and then suddenly, either L or R will be sent and then thats it. No more sending from the script.
Here's my script-
import numpy as np
import cv2
import serial
ser = serial.Serial('COM3',9600,writeTimeout = 0)
def f(x): return
cv2.namedWindow('Thresholding Control')

# create trackbars for color change
cv2.createTrackbar('High H','Thresholding Control',179,179, f)
cv2.createTrackbar('Low H','Thresholding Control',0,179, f)
cv2.createTrackbar('High S','Thresholding Control',255,255, f)
cv2.createTrackbar('Low S','Thresholding Control',0,255, f)
cv2.createTrackbar('High V','Thresholding Control',255,255, f)
cv2.createTrackbar('Low V','Thresholding Control',0,255, f)
cv2.createTrackbar('Guassian Blur','Thresholding Control',0,99, f)

cap = cv2.VideoCapture(0)
while(True):
  ret, image = cap.read()
  HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  # Getting trackbar values
  highH = cv2.getTrackbarPos('High H','Thresholding Control')
  lowH = cv2.getTrackbarPos('Low H','Thresholding Control')
  highS = cv2.getTrackbarPos('High S','Thresholding Control')
  lowS = cv2.getTrackbarPos('Low S','Thresholding Control')
  highV = cv2.getTrackbarPos('High V','Thresholding Control')
  lowV = cv2.getTrackbarPos('Low V','Thresholding Control')
  # Thresholding the image.
  thresh = cv2.inRange( HSV, (lowH, lowS, lowV), (highH, highS, highV))
  blurVal = cv2.getTrackbarPos('Guassian Blur','Thresholding Control')
  if(blurVal%2==0):
      blurVal=blurVal+1
  thresh_smooth = cv2.GaussianBlur(thresh, (blurVal, blurVal), 0)
  #Defining the kernel to be used for Morphological ops.
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  # Applying Opening and Closing.
  thresh_smooth = cv2.morphologyEx(thresh_smooth,cv2.MORPH_OPEN,kernel)
  thresh_smooth = cv2.morphologyEx(thresh_smooth, cv2.MORPH_CLOSE, kernel)

  #(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(thresh_smooth)
  eleR = np.count_nonzero(thresh_smooth[0:480, 320:550])
  eleL = np.count_nonzero(thresh_smooth[0:480, 0:320])
  eleO = np.count_nonzero(thresh_smooth[0:480, 550:640])
  if (eleL>eleR and eleL>eleO and eleL!= (eleR+eleO)):
     cv2.putText(image,"Left Turn", (320,240), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('L')
  elif (eleO>eleR and eleO>eleL):
     cv2.putText(image,"Right Turn", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('R')
  else:
     cv2.putText(image,"Straight", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     print ('S')
  cv2.imshow("BGR", image)
  cv2.imshow("Thresholded", thresh_smooth)
  print ser.readline();
  if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#cv2.imwrite('ImG.png', thresh_smooth)
cap.release()
cv2.destroyAllWindows()

One uses inByte and the other uses data? Also; are there any motors attached? Motors use a lot of current and can create a lot on electrical noise, which could make the Arduino freeze or reset.

@Gerben oh that's my fault, actually they are two different sketches I wrote, they are mostly identical except for variable names. Anyways, no there's only one motor attached.

Please post the actual entire sketch that you are having problems with.

How exactly are you updating the value received through serial? Also is the code exactly the same between Arduino sketches as I see you use a different variable to compare for the motor driver.

@Majenko post updated.

@RSM please see the entire code. Yes the sketches are different but very much identical except for variable names and a few things

Are you just being impatient and not waiting for the 2 second delays to expire before expecting it to look to see if there is an updated value? delay() is never a good idea.

@Majenko I wait. I mean once it receives its first value, it just keeps on iterating that code block. Even after quite sometime after the variable changes.

Have you tried adding some debugging (Serial.println()) to get some visual feedback about how your program flow is working?

@Majenko I removed the delay and the sketch responded. I got the motor to turn (L), stop(S) and run backwards (R) but it got stuck on R. Moreover I only got L as print output. Doing the same from the Serial Monitor works just fine.

Ok, then it's your python program that is at fault. Maybe you should show as that as well?

I don't suspect the python program. It runs the first script just fine.

@YaddyVirus    possibly post a link to the python code or put it here? Then people could possibly test it if need be.

@Majenko yes you were right... Most probably my python script is at fault. Posting it now

Okay I figured it out. Putting what I did here, for people who are curious and for those who need help.
It was probably the Arduino, autoresetoverserialcomm, for some reason the Arduino auto-resets whenever you send a value over the serial comm to the Arduino from a computer, not from the Serial port (obviously). I knew of this earlier, and another one of my script which also sends data to the Arduino was working fine with this setup.
What I did? I just put a 10µ capacitor between the RESET and the GND pins. That didn't work initially, but I tried putting the +ve of the capacitor in the GND pin and -ve in the RESET pin and voila! The script started working just fine.
I guess this wasn't a programming issue at all, but an issue of the Arduino and the script not being able to contact each other.
I still am not sure as to what was causing the problem or whether what I have done is a permanent fix, or even a fix at all, but my problem seems to have been solved. I'll keep updating the post.
Suggestions and discussions are always welcome!

You have got quite a bit of difference between the two codes.
In your first code you declare char inByte = ' '; at the beginning of void loop. This means that each time you run through the loop it clears the value which you assign the Serial value to.
In the second code you declare data as a global variable outside of loop.
What that means is that you first code basically allows a one-shot reaction to a Serial value because it clears the value at the beginning of loop. Thus it only goes into an if() statement once.
Whereas your second code will retain the value that it received at Serial.read() the first time. Thus it will continue to run the matching if statement.
What you could do is after each matched if() statement you do data = ' '; or at the beginning of loop you can clear it.
Also you might be missing the updates from your python script because of the delays during motor control. Also Gerben is correct about there possibly being issues with the motor drivers affecting the Arduino.

I tried putting the data = ' ' statement in all the possible places. Wherever I place it, the sketch stops working

3 things:
1: your delay statement is worrying, I'd highly recommend parallel coding in this case.
2: you don't have a "data = ' ';" statement in your loop function of the second code, but you do in the first. Is this intentional?
3: if your arduino receives Serial while executing Delay, you mustn't pour in more than the buffer.

I've removed the delay but that didn't help

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


text:
Controlling 12v DC LED strips using Arduino UNO
I have 2 LED strips with 6 LEDs on each. They use a 12V power supply.
My question, how can I use them like regular LEDs using Arduino UNO? Without any MOSFETS or transistors if possible.
And can I use PWM?

The only way is to cut out the individual leds an solder some wires to them, so you can connect them directly to the Arduino (with a resistor).

Do you have a picture? And are you sure it's 12v? As 8 LEDs is a weird number.

its 6 actually.. my bad @Gerben

That makes more sense. Two sets of 3 LEDs in series.

It's not safe for the MCU without transistors or so.
You can use some kind of LED driver (for example TLC5940 with on chip PWM) or ULN2003 as 8 channel low side switch (instead of 8 transistors, PWM is possible if you do it programmatically) or many others.
With single transistor it looks like:

Where R_1 can be about 1K and transistor can be any NPN that could handle led current.

so what transistor do I actually need? and in case I do use a transistor, how am I going to wire the enitre setup?


text:
Arduino IDE get stuck while uploading sketch
I was trying to use my L293D motor driver module. But when I upload the following sketch to try and run my motor, but it would get stuck on "Uploading". This happens with this sketch only, and happens randomly, with odds of happening being 3 in 5 times. After a bit fiddling around I found an error

Programmer is not responding.

When I try to reset the board or just reconnect it to my PC it might work.
Here's the sketch-
int RightMotorForward = 12;
int RightMotorReverse = 13;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

Can anybody point out where I am going wrong? I am using Arduino UNO. Is this just some problem in my code?

Can you please upload a schematic of your wiring? Do you use a bare L293D or do you use a prefabricated shield containing it?

I'm using a prefabricated shield. See this - http://arduino.stackexchange.com/questions/23383/using-a-l2938d-motor-driver-module-not-ic-module/23384?noredirect=1#comment44462_23384

This may very well be a problem related to power supply and/or grounding. Please report all power supplies connected in your setup (including the one powering your computer!) and how they are connected to your arduino, shield and further equipment.

That's the exact conclusion I came to just a moment ago (I was just going to post it!). I have a laptop, connected to the wall outlet. I am powering up the Arduino from a USB port on my laptop. I have inserted the 5v and GND pins from Arduino to the 12v and GND pins on the motor driver. If you have seen the link I send you, I think I should connect the 5v pin to the 5v input on the motor driver and some other power supply on the 12v output (Lets say a 9v battery for experimentation.)

Yes. the USB port definitely cannot supply the power for high power actors on any shield (there may be exceptions, though). If you connect another, let's say 12V, wall wart to the 12 V input of the shield, I strongly recommend to unplug your laptop from the wall outlet during testing, as two SMPS can cause problematic interference due to their so called Y-capacitors.

Found the solution... Just connect the 5v from arduino to the 5v on the Module. Then another battery (12-36 V, I tried a 9v one... it worked but only for about 40 seconds), to the 12 V input, keeping the ground common... That's gonna make the motors run!

Is the motor driver connected to the Arduino while you program it?
When the Arduino is reset, the output pins on the Arduino are driven high. If too much current is drawn though any of these pins, then the voltage supply to the ATMega328 may drop, and the ATMega328 gets stuck in a brownout.

Yes the motor driver is connected to the Arduino. What I don't understand is, it takes, sometimes, several resets and reconnections to get the board working again... And sometime it would say "COM8 not available". So even if to voltage supply drops on the ATMega, it should work in only one reset only. Is this some problem with my code?


text:
Sharp GP2Y0A710K0F IR sensor behaving strangely
I have just purchased a new Sharp GP2Y0A710K0F IR sensor online. As a sanity check, I wrote this simple code to check if the sensor is working correctly. The code is expected to print output voltage from the sensor, which is based on the distance
int sensorpin = A5;
int val = 0;

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

void loop()
{
val = analogRead(sensorpin);
Serial.println(val);
delay(100);
}

Now the output is quite strange. The output values start from zero and keep on increasing until they reach 1023, and then gradually decrease down to zero and this keeps on happening, even if something is kept in front of the sensor.
Is my sensor a faulty one? or is it supposed to give out similar outputs. If it has to, how do I convert these values to meter or centimeters.
The product description on the manufacturer's website said that it has a 3 pin interface, however it has a 5 pin one, the wires being Red, Black, Yellow, White, Green if seen from the left side. I guessed from the datasheet that Red and Black are for power and Yellow for signal output and hence I have connected only these 3 wires. The Green and White wires are unconnected. Also, pin numbers aren't marked.

The datasheet says there are 5 pins. 2 are Vcc and 2 are ground.

How close is "in front of the sensor"?

@Majenko , so I connected the Red and Black wires as Vcc and ground respectively. Used the yellow wire for output.

@Majenko roughly 40-50 cm away, it is supposed to be atleast 100 cm away right?

Well, that's probably why then. Does the graph on page 5 of the datasheet look like what you are describing? Also, did you note the description? Distance Measuring Sensor Unit Measuring distance: 100 to 550 cm Analog output type

@Majenko I tested with an object placed at about 200 m. Still the same problem. Since the object is at a constant distance, the reading should be stable right?

I suspect you have it wired wrongly.
You need to consult the outline diagram in the datasheet and work out which colour wire is which function. It's this bit:

By your wiring description it sounds like you may be powering it through Vo and reading the result through VCC, which won't work - and at worst may damage it.

Did the experiment, connected pin 3 to 5v on Arduino, 5 to GND on Arduino and 4 to A5. This time the readings start off with 927 and go to 1023 and then come back to 927 and the process repeats.

I think I have got it working. Connected both the postives to 5v and both the ground to 5v, I then get the voltage readings ranging between 355-388. If that's 3.5 to 3.8v, its horribly wrong as then according to the graph,it should be roughly 2v as the object is 1.5 m away from the sensor

Those are raw ADC values. You have to convert them to voltage.

But anyways, since I've got the sensor working, how to read its values is another question. Thanks


text:
How do I lock a servo motor?
I am working on a robot which uses Ackermann's steering principle. Now the steering principal itself is in the development stage and the first prototype is pretty much good except for the fact that it can get turned very easily.
So I was hoping to find a way to lock the servo operating the steering mechanism so that it only rotates when the servo does. Any way to do that??
I'm using a UNO.
Thanks!

Did you call servo.detach()? Servo's should usually hold their position when attached. This is because of the way how servo's work. They've got an internal feedback loop, which constantly adjusts the servo towards it's setpoint (if it's a bit off).

@Paul no I didn't

What type of servo do you have?

@Paul simple rc servo, Turnigy MX - 3505

It might not get enough current to hold it into position? If you touch it, would it jump back to it's position when you release it?

No it just moves with my steering mechanism as if moved by external force. I am giving it 5V 3 Amps through a UBEC and raw power from 2 ICR 16850 batteries, totalling somewhere near 8.5 V

Hobby servos are typically susceptible to backdriving when unpowered, and possibly also if they are powered but have no signal.  Counteracting backdriving would require that the internal control loop function, but a traditional analog implementation would have no memory of what the last commanded position was.  An MCU based servo could have such a memory, but its not clear it would be programmed to.  Make sure you are continuing to send pulses to the servo and do not subject it to torque above its rating.  This may turn out to be a mechanical design problem not an Arduino one.

It's Ackermann and principle.
What do you mean by "find a way to lock the servo operating the steering mechanism so that it only rotates when the servo does"? When what rotates?

@JayEye thanks for pointing that out. My design is just of wood and rotate s easily with any external force. I will control the rotation from my servo. So I want that my servo only moves when the Arduino tells it do so, otherwise stay "locked" in the centre position,

@ChrisStratton well that's most probably a mechanical problem, I can just counteract it by locking my servo.

Hobby servos do not offer "locking" as a feature.

This seems to be a question about servos rather than Arduinos, so I'm going to close it.

A normale servo will stay in position when:

It's powered up (with enough current)
You are feeding the control signal into it.

And

It's rated for the amount of force applied.

Based on your comments, it seems that it's not a regular servo or could be faulty.
I couldn't find the datasheet for your servo, so I can't tell if it's normal behavior, though it seems unlikely. (Servo's aren't made to bounce around)
Edit:
It doesn't really make sense that it could be easily rotated by touching it, that would also mean that it can't lift anything? I would suggest trying another servo.

authors: Зориг Өлзийжаргал


text:
Does serial communication between PC and Arduino has to be in a loop?
I am trying to send a few variables from my python script to my Arduino. I am using pySerial. I am able to send the variables to the Arduino, but my Arduino sketch runs only for a second and then stops. But if I put the ser.write() command in a while loop (which I want to avoid) the sketch runs fine.
For example, I wrote this script on my PC -
import serial
ser = serial.Serial('COM3',9600)
counter = 'Y'
ser.write(counter)

This script should pass a "Y" to the Arduino and should stop executing.
My Arduino code-
int flag = 0;
void setup() {
   Serial.begin(9600); // set the baud rate
   Serial.println("Ready"); // print "Ready" once
   pinMode(13, OUTPUT);
}

void loop() {
   char inByte = ' ';
   if(Serial.available()){
      inByte = Serial.read(); // read the incoming data
      Serial.println(inByte);
      flag ++;
   }
   if(flag == 1){
      digtalWrite(13, HIGH);
   }
}

Now according to me the Arduino should receive the data and increment the flag variable to 1. Next the program checks whether flag is one and if it is turns the onboard LED on. However when I run the python script, the onboard LED flashes for just a second and then goes blank. I again have to run the python script to make it light up or I have to put ser.write in a loop. I can't put ser.write in a loop as my script won't run further.
So how can a value be passed to an Arduino without having to put the ser.write() in a loop.
Thanks!
EDIT :
I wrote a new sketch, but it still doesn't work. Here's the sketch -
int ledPin = 13;
char data = ' ';

void setup(){
   pinMode(ledPin, OUTPUT);
   Serial.begin(9600);
}

void loop(){
   if (Serial.available()>0) {
      data = Serial.read();
   }
   if (data == 'Y'){
      digitalWrite(ledPin, HIGH);
   }
   delay(500);
}

Here's an image of the wiring -

Comments are not for extended discussion; this conversation has been moved to chat.

Just put a 10 µF capacitor between the 5v and RESET pins of your Arduino and do whatever you want, just make sure that the capacitor is connected after the board has been powered up, and also, remove the capacitor before uploading any code.


text:
Arduino IO long distance travel
I would like to use Arduino to control locks around a building which is 5 storeys high and on every floor there is 2 door.
I'm concerned whether the wires is able to travel all the way from the ground floor to the 5th floor to provide enough power to the relay located at the door.
The lock will be a 12V magnetic lock and it will be unlocked thru a SSR relay which will be controlled by the arduino

Even without the problem of long wires, if you are using a typical Arduino, like UNO, you will have to add something in between the pin and the lock (btw, adding a reference to the specific lock would help understanding better the question).

Pulling wires across a whole building seems a bit of a hassle. Have you considered using a radio connection? There are many radios available, over which you could send signed messages.

@IgorStoppa What would be the something be?

Something like this relay shield: http://www.seeedstudio.com/wiki/Relay_Shield_V2.0, but maybe your lock already has something similar built in, therefore I was asking you to be more specific about what type of lock you want to drive. Even if you have a relay, that might still require an additional transistor, depending on the specs of your relay.

@IgorStoppa I'm afraid that the walls of the building will affect the radio signal. The lock will be unlocked by touching 2 wires together which I will be using a relay to do that

If the locks already have their own 12V supply and the SSR are mounted next to them (1SSR per lock) you won't have much troubles. You can add a buffer right before the SSR input to lower the required current

Are you adding additional wires to the building?

Yes, losses in wires are proportional to the length, so an excessively long wire may not be able to deliver enough power. Many factors come into play here:

higher current consumed by the relay increases the losses
smaller wire diameter increses the losses
the voltage required by your relay defines how much you can afford to lose

For example, a pair of AWG23 wires 30m long will have a total resistance of 4 Ohm. If your relay consumes 100 mA, you will lose 0.4V in the wires. If Arduino delivers 5V, and the relay requires a mininum of 4.5V to work, you're just good enough: you're delivering 4.6V to the relay after the losses.

Possible to add a amplifier between each level?

Technically, yes. Do you have a power supply on each level?

Yes that would be possible. What kind of amplifier should I be looking for?

The simplest one, something like this. But like I said, maybe you will get away without one, if the wires you have are thick enough and the relays don't consume much current.

You are addressing a device control problem that auto, home and building automation has concerned itself with for years.
As such there are many solutions.  Most require a transmitter and one or more receiver(s). C-BUS is one such solution.  Another is CAN-BUS.

Use wireless nodes which are self-powered. It is easier (no need for lot of cables) and also solves this issue completely.
You can use ZigBee, which is mesh network. Every node re-transmit signal for nodes which are far. Because you have one on every floor, you would not have issues with reception.
EDIT:
If you want to use wires, I would still keep self-powered nodes and you can communicate with them using i2c or similar. You would need only 3 wires (SDA, SCL and GND) and they could be very thin, because they transfer only signals (<1mA range)). These 3 wires would connect all nodes. All nodes should have distinct address. I think this could be very cheap because you can create nodes with arduino micro which can be bought for ~1.5$ each.

Wireless would need a lot of additional work to maintain security

ZigBee already have security mechanism (128-bit key) implemented.

He mentions Arduino + basic lines. This will drive costs through the roof compare to that

I have added second (wired) option which is very cheap. It needs only 3 thin wire for whole building because all nodes would have distinct addresses. If you take into account number of thick cables he needs this can be even cheaper.


text:
PinChange Interrupts proplem with DRO scales
I am trying to read values from 2 separate DRO scales ( Digital Read Out ), most commonly used on lathe and milling equipment, CNC, or any X,Y,Z table.
These scales need to use 2 interrupt pins per device, due to using pulses for the measurement data. These scales are incremental only.
To get around only having 2 interrupt pins ( D2, D3) I want to use PinChange interrupts on 2 other pins.
The code I have so far compiles and serial mon displays the measurements from pin D2,D3, but I get nothing from pin D4,D5.
I am wanting to know how to invoke PinChange interrupts on D4,D5 to read the data from the scale.
I don't want to buy a different board with more interrupt pins as I have a supply on NANO's that I want to use, and will fit in the space available.
Pins require interrupts to read scale value. Scale is incremental only
/*

pinA, pinB are for dro scale 1
pinC, pinD1 are for dro scale 2

D2 = pinA - Hardware Interupt - Scale 1 clk
D3 = pinB - Hardware Interupt - scale 1 data
D4 = pinC - Pinchange Interupt - scale 2 clk
D5 = pinD1 -Pinchange Interupt - scale 2 data

counter1 = scale 1
counter2 = scale 2

*/

const int pinA = 2, pinB = 3, phaseLookup1[] = {0,-1,1,-1,1,0,-1,-1,-1,1,0,1,1,1,-1,0};
const int pinC = 4, pinD1 = 5, phaseLookup2[] = {0,-1,1,-1,1,0,-1,-1,-1,1,0,1,1,1,-1,0};  // seperat lookup tables for each scale

volatile bool A = false, B = false,C = false, D1 = false, updated = false;
volatile int scale1 = 0, phase1 = 0, scale2 = 0, phase2 = 0;

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

  pinMode(pinA, INPUT);
  pinMode(pinB, INPUT);
  pinMode(pinC, INPUT);
  pinMode(pinD1, INPUT);

  PCICR |= B00000100;// Enable PCIE2 Bit3 = 1 (Port D)
  PCMSK2 |= B00110000;// Enable PCINT20  & PCINT21 (Pins D4 & D5)
  //ISR (PCINT2_vect);

  attachInterrupt(digitalPinToInterrupt(pinA), trig, CHANGE);
  attachInterrupt(digitalPinToInterrupt(pinB), trig, CHANGE);
  attachInterrupt(digitalPinToInterrupt(pinC), trig, CHANGE);
  attachInterrupt(digitalPinToInterrupt(pinD1), trig, CHANGE);
}
ISR (PCINT2_vect);

void loop()
//
{
  if (updated)
  {
    Serial.println(String(scale1));
    Serial.println(String(scale2));
    updated = false;
  }
}

void trig()
{
  A = digitalRead(pinA);//Scale 1
  B = digitalRead(pinB);//  "
  C = digitalRead(pinC);// Scale 2
  D1 = digitalRead(pinD1);// "

  phase1 <<= 1;//Scale 1
  phase1 |= A;
  phase1 <<= 1;
  phase1 |= B;
  phase1 &= 0xF;

  phase2 <<= 1;//Scale 2
  phase2 |= C;
  phase2 <<= 1;
  phase2 |= D1;
  phase2 &= 0xF;

  scale1 += phaseLookup1[phase1];
  scale2 += phaseLookup2[phase2];
  updated = true;

}

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read "[ask]". Please [edit] your question when clarifying, this is not a forum.

Why do you use only one ISR for all edges? Did you consider to use separate ISRs, avoiding complexity? Or, since quadrature encoding never has edges on both signals at the same time, two separate ISPs for both sensors?

Boiled down, are you asking how to use pin change interrupts for 4 pins at the same time, or how to make pin change interrupt work on pins 4 and 5? If the latter, did you experiment with a simplified sketch just for that goal?

I noticed that this is solved at arduino.cc. Please mark this one so no body wastes any time giving you answers that you already have.  Please don't cross post in the future.  It wastes time.  It's the same basic group of people in both places.  All you're doing is showing people that you don't value their effort which makes many not want to help you.

Delta. Yes I do realise your point. I do appreciate and value the community. Been a while and I am rusty. I will be putting the code from this discussion on Github along with the project. I hope others can use it.

The Arduino function attachInterrupt() only works with the so-called
“external interrupts”, which on the Nano are only available on
pins 2 and 3. For any other pin, digitalPinToInterrupt()
returns the constant NOT_AN_INTERRUPT (-1), and attachInterrupt()
does nothing. If you want to work with pin-change interrupts you will
have to either find a library that provides a nice API for them, or do
it low-level by setting yourself the hardware control registers and
defining a real ISR.
As you are setting both PCICR and PCMSK2, you are following the
low-level way, and you are almost there. The only thing that is missing
is defining an ISR that actually does something useful. Maybe simply
this:
ISR(PCINT2_vect) { trig(); }

While you are at it, remove the two irrelevant calls to
attachInterrupt(). Also, I would avoid reading both scales each time
one scale sends a pulse: you only have to read the one scale that gave
the pulse. You can thus split trig() into one function for each scale,
then in setup():
attachInterrupt(digitalPinToInterrupt(pinA), trig_scale_1, CHANGE);
attachInterrupt(digitalPinToInterrupt(pinB), trig_scale_1, CHANGE);

and the ISR would then be:
ISR(PCINT2_vect) { trig_scale_2(); }

This should save you quite a few cycles in interrupt context, and thus
lower the interrupt latency and make the whole program more robust.

Thanks to all.
I have a solution from the Arduino forum.
I will put the code up on Github for all to see and share.
/*
  Pins require interrupts to read scale value. Scale is incremental only.
  pinA, pinB are for dro scale 1
  pinC, pinD1 are for dro scale 2

  D2 = pinA - Hardware Interrupt - Scale 1 clk
  D3 = pinB - Hardware Interrupt - scale 1 data
  D4 = pinC - Pinchange Interrupt - scale 2 clk
  D5 = pinD -Pinchange Interrupt - scale 2 data
*/
#include <avr/interrupt.h>
const int pinA = 2, pinB = 3, phaseLookup1[] = {0, -1, 1, -1, 1, 0, -1, -1, -1, 1, 0, 1, 1, 1, -1, 0};
const int pinC = 4, pinD = 5, phaseLookup2[] = {0, -1, 1, -1, 1, 0, -1, -1, -1, 1, 0, 1, 1, 1, -1, 0}; // seperate lookup tables for each scale

volatile bool A = false, B = false, C = false, D = false, updated = false;
volatile int scale1 = 0, phase1 = 0, scale2 = 0, phase2 = 0;

void setup()
{
  Serial.begin(9600);
  Serial.println("T.I.S.M"); // Google it
  pinMode(pinA, INPUT);
  pinMode(pinB, INPUT);
  pinMode(pinC, INPUT);
  pinMode(pinD, INPUT);
  cli();
  PCICR |= B00000100;// Enable PCIE2 Bit3 = 1 (Port D)
  PCMSK2 |= B00111100;// Enable PCINT20  & PCINT21 (Pins D4 & D5) + D2 + D3

  sei();
}

void loop() {
  if (updated)
  {
    Serial.println(String(scale1*2));
    Serial.println(String(scale2*2));
    updated = false;
  }
}

ISR (PCINT2_vect)
{
  static byte oldState = 0;
  byte newState = PIND & B111100;
  if (newState != oldState) {
    A = (newState & 1 << pinA) > 0; //Scale 1
    B = (newState & 1 << pinB) > 0; //  "
    C = (newState & 1 << pinC) > 0; // Scale 2
    D = (newState & 1 << pinD) > 0; // "
    if ((newState & B1100) != (oldState & B1100)) {
      phase1 <<= 1;//Scale 1
      phase1 |= A;
      phase1 <<= 1;
      phase1 |= B;
      phase1 &= 0xF;
      scale1 += phaseLookup1[phase1];
    }
    if ((newState & B110000) != (oldState & B110000)) {
      phase2 <<= 1;//Scale 2
      phase2 |= C;
      phase2 <<= 1;
      phase2 |= D;
      phase2 &= 0xF;
      scale2 += phaseLookup2[phase2];
    }
    updated = true;
  }
}

Link to the relevant forum page or post?

Did you try the solutions I posted?

Edgar - As yet, I have not tried your solution, but it is something to look at when I add the other functionality's that I want to try

https://github.com/MorryStu?tab=repositories

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


text:
Opening webpage using ESP8266 in Arduino
I am trying to open the webpage in ESP8266 via Arduino Mega.
I have successfully opened the webpage if I use the AT command in the Serial Monitor
The output is perfect
+IPD,382:HTTP/1.1 200 OK
Server: nginx
Date: Sun, 08 May 2016 06:44:47 GMT
Content-Type: text/html
Connection: close
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.26
Set-Cookie: PHPSESSID=rnsmo0b4kq07c5mi3mdsu280g4; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

S|R190|W5|O31.0|T0|A24|CLOSED

As you can see the output is fine.
Now If I issue commands using Arduino Serial1.print() and read the output using following code:
 while( Serial1.available() )
 {
     inChar = Serial1.read();
     Serial.write(inChar);
     //delay(1);         //could play around with this value if buffer overflows are occuring
 } // while

The output skips character randomly
+IPD,386:HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 May wed-y: HP/.5.26
SetCooie:PHPESSD=7kameos5kd7aqcn4e54; pth=
Epirs: hu, 19Nov198 0852:0 GT
ach-Cotro: n-stre,no-ach, mst-evaidate,pos-chck=, pe-ceck0
raga: o-cche
F~SR19|W5O310|T90|ENDLOSD

I have tried different values of delay() but of no help.
My baudrate is 9600 for both arduino Serial and ESP8266 Serial1
Can you please tell me what can be the reason.
Thanks

Can you share with us the At commands to access a web page ?

First things first: never use a delay when reading from serial.
You are just blindly trying to read data and send it out to another port. That's not going to work unless you know how much data you need to read.
And that information is handed to you on a plate - you just need to interpret it.
You are required to read the serial data as it comes in and decide what it means, then do different things depending on that data.  For instance, when you read the characters +IPD you know you have an IP Data response to be interpreted.  Just after that comes a comma, and following that a number. That number is how many bytes you then have to read to get your data. So you keep looking and reading until you have received all the data you should be receiving.

If you notice the output does contain END This is the flag that shows that entire response has been read. The problem is that data is being skipped in middle randomly. Cache-Control is read like ach-Cotro with skipped characters.

My guess is it's something happening outside your while loop. That loop won't read the whole of the output - it will just read snippets as they become available, and other things in your program that may consume serial bytes are getting in the way. Follow my instructions and read the output properly.

I changed the code like you said and it is working fine. I think Serial.print() is coming in way of reading Serial1.read() I first read output in array and then print and it shows fine.

authors: ابو زهراء العراقي

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


text:
Write char array containing new line to SD card
How do I a buffer (char array) containing new line character to SD card using SdFat?
I tried:
File myFile = SD.open("test.txt", FILE_WRITE)
myFile.write(buffer, BUFLEN)

but I get this instead:
0000 0000 0000 0000 0000 0000 0000 3337
3837 3838 3937 3035 2c20 2020 2031 2c20
2020 3531 0a33 3738 3738 3839 3730 352c
2020 2020 322c 2020 2035 310a 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000

If I use the normal method, then it seems that SdFat stop printing at the newline character:
myFile.print(buffer);
Note: the buffer containing data samples in fixed width csv format
3787889751,    1,   49
3787889752,   10,   49
3787889753,    1,   49

I think we'll need a minimal, complete, verifiable example of your code, because I don't think the problem is what you think it is: your stated output doesn't match your stated string, even before the newline.

File.print() stops printing at a NULL character (ASCII 0) not a new line.  You can stick as many new lines as you like in a string and it will print.  Try this example
void loop ()
{
  Serial.print ("Hello\nMultiline\nPrint\n");
  Serial.print ("Hello\0Multiline\0Print\n");
}

File.write() writes binary data to a file, it will write BUFLEN bytes, even if you don't give it that many bytes.
Looking at the output from you hex editor your string ends with ... 2020 2035 310a which would be 3 spaces (20), 51 (35 and 31) and a new line (0A).  There is also a null (00) after that, but I can't tell how many because you have 0s to pad the output (or fill the file).
If you look further back in the output (3rd col, 3rd row) you can see another newline (0a33) so that proves its not new lines that is stopping your output.
Without your code we can't say whats wrong, but I agree with Mark that its not what you think it is.
To write data to a CSV file I would write each row of data into a struct and then hold those structs within a list.  Then have a function that iterated through the list and printed each record to the file.  That way you wouldn't need a buffer.  If it didn't have to be a CSV then you could just call
myFile.write (currentRecord. sizeof(StructRecord));


text:
Calculate absolute time based on cycles and RTC
I'm developing a low power data logging device. It samples sensors at the frequency of 20Hz, and also has a real time clock for absolute time (the logged time need to be exact down to ms).
I think that querying time for every samples would be wasteful of energy. One solution is calculate time based on number of cycles, and after a fixed duration (10 minutes) query RTC to update the time.
Here is my attempt:
#define INTERVAL 12000 //10 minutes: 10*60*20 samples

int count = 0;
int checkPointMillis;
int checkPointRTC;

// timer interrupt at 20Hz
ISR() {
    int a = analogRead(A0);
    int time = millis() - checkPointMillis + checkPointRTC;

    // write data to a buffer

    if (count > INTERVAL) {
        count = 0;
        checkPointMillis = millis();
        checkPointRTC = getRTCTime();
    }
}

Is this a correct approach?

The problem is that getRTCTime only has 1sec resolution. So at the time of the request, it could be up to 999ms off. You could use the RTC to generate an interrupt every second, and connect that to an interrupt pin. Then in the pin-change interrupt check the difference between millis and a whole seconds counter. You can use that difference to get a calibrated millis. Not sure if this is the best solution.

In general, the idea is sound.  But there are problems with some of the details and tuning.
The most important detail:  Use the correct data type for storing and computing with time variables (like time, checkPointMillis and checkPointRTC).  The correct data type is unsigned long (or, equivalently, unsigned long int or uint32_t).
A second detail:  Rather than storing your calibration correction in two variables which you always use as a difference (in effect, checkPointRTC-checkPointMillis) just compute and store the difference.  For example:
...
unsigned long clockCorrection;
...
unsigned long time = millis() - clockCorrection;
...
clockCorrection = getRTCTime() - checkPointMillis;

This will save a few bytes of RAM and a few cycles of computation.
A third detail:  If outside of the ISR you will need to access any of the values computed in the ISR, declared their variables volatile.  Example:
volatile unsigned long time;

Fourth: If getRTCTime() or any of your sensor-reading code use interrupts, you will need to move such code out of the “timer interrupt at 20Hz” section, into (for example) loop(), triggered by a volatile variable going true.  [That's the model under which the balance of this answer was conceived; I overlooked, at first, the “timer interrupt at 20Hz” label.]  Note that millis() itself does not use interrupts.  But if your 20-Hz ISR runs longer than a millisecond, the millis() total will drop one millisecond per millisecond of additional ISR time.
By tuning, I refer to the number of measurement intervals to wait between recomputing the clock correction.  Under reasonable assumptions, the number of compute cycles is so closely the same with a one second interval versus a ten minute interval, that one probably should use only a second (or at the outside, a minute) interval between clock correction computes.
For example, suppose the total number of cycles awake per second is given by the following equation:

a = 20*s + 1000*t + k * r

where s is the number of cycles used per sensor-set reading and recording; t  is the number of cycles used per clock interrupt; k is the number of clock correction computes per second; and r is the number of cycles used per clock correction compute.
For example, if s is 2000, t is 100, and r is 200, the equation becomes

a = 20*2000 + 1000*100 + k * 200 = 140000 + k * 200

Now consider three cases: k equal to 20, or 1, or 1/600, corresponding to a clock correction compute 20 times per second, or once a second, or every 10 minutes:
   k           a
  20        144000
   1        144200
1/600       144000.3

As you can see, under the assumptions s is 2000, t is 100, and r is 200, there is no compelling reason to prefer 1/600 corrections per second to one  correction per second.
If your RTC can be read reliably and quickly, reading it either every time (ie 20 per second) or every second has other advantages:  you compensate more quickly for MCU clock drift (ie, every second, rather than every 10 minutes) and strongly decrease the risk of out-of-order times.
For example, if your MCU clock drifts 2 seconds fast per 10 minutes, readings taken during the first two seconds of each new 10-minute interval would show smaller times than those taken during the last two seconds of the previous interval.  With secondly corrections, no such non-monotonic readings will occur.
Here is a slightly more correct analysis of the 2 seconds fast per 10 minutes case:  2 seconds error in 600 seconds is 3.33 milliseconds per second.  With sensor readings 50 milliseconds apart, and corrected clock readings not more than 3.33 milliseconds out of whack, non-monotonicity won't occur.  However, this does not meet the “logged time needs to be exact down to ms” criterion.  To meet that, drift of more than a half millisecond must be prevented.  That requires drift correction at least 6.67 times per second.  You could accomplish that by making a  clock correction compute at every third sensor cycle.
It should be clear from the example calculations of awake cycles that the major contributor to the count is ISR cycles, here taken as 100*1000, or 100000 cycles per second.  You could set up timer 1 to interrupt 20 times per second and turn timer 0 off (which would disable millis() and require a different time = ... formula).  If each timer 1 interrupt took 1000 cycles, that would contribute 20000 cycles instead of 100000 per second.
Edit 4: As I noted in a comment to Edgar Bonet's answer, one can change the TOP value used for timer interrupts, to control interrupt rate with better resolution than can be obtained by merely subtracting base values.
According to Gerben's comment, “getRTCTime only has 1sec resolution”.  As I haven't seen any code for your getRTCTime() I don't know if that is true or not; but if so, here is another approach for time-rate correction:

• At some beginning point coincident with an RTC seconds-change, record millis() and an RTC reading, in eg millibase and RTCbase.
  • At some interval (eg, 10 seconds or a minute, in each case coincident with an RTC seconds-change) measure millis() and an RTC reading, in eg millinow and RTCnow.  Compute RTCdeltaK as the number of milliseconds from RTCbase to RTCnow.  Compute millidelta as millinow-millibase.
  • Whenever elapsed time in milliseconds is needed, compute elapsedms = ((millis()-millibase)*RTCdeltaK)/millidelta.

The above is an algorithm, and may need some adjustment before use as an implementation.  First, the elapsedms calculation can be arranged to avoid division, using a scaled multiplicative factor based on millidelta, RTCdeltaK, and some powers of 2.  Secondly, relatively constant clock drift is assumed.  If that assumption is incorrect, an average ratio with exponential decay could be used, instead of just a factor equivalent to RTCdeltaK/millidelta.

Yours is a classical problem of clock synchronization. You have a
software clock (your program's idea of the current time) which you want
to keep in sync with a reference hardware clock (the RTC). This is
typically achieved by using a phase-locked
loop, or PLL. It works
as follows:

you measure the difference between your software clock's time and the
reference time
you adjust your software clock based on this measurement.

This is essentially what you are already doing, except that you are
fixing your clock by stepping it abruptly, whereas a PLL would usually
slew the clock to get it in sync progressively.
Stepping the clock has some undesirable effects: it makes the time
discontinuous and, more annoyingly, it can make it non-monotonic. I
would thus recommend you try to slew your clock instead.
Here is the approach I would try if I were in your shoes. I am assuming
you are using an Arduino Uno, or a similar AVR-based board with a 16-bit
Timer 1:

configure Timer 1 in mode 4: CTC mode with TOP = OCR1A
set the prescaler to 64 and OCR1A = 12499 in order to get a period of
50 ms; TIMER1_COMPA_vect will be your data gathering interrupt
configure your RTC to generate a 1 Hz output, and route this
signal to the input capture pin ICP1 (pin 8 on the Uno)
run the PLL logic inside TIMER1_CAPT_vect.

Since the RTC's 1 Hz period is a multiple of the timer period, you
would expect the timer's input capture unit to always capture the same
value. The difference between two consecutive captured values is thus a
direct measure of your clock's drift in units of 4 ppm
(4 µs/s). The ISR would be basically along these lines:
ISR(TIMER1_CAPT_vect)
{
    static uint16_t last_capture;
    uint16_t this_capture = ICR1;
    int16_t drift = this_capture - last_capture;
    last_capture = this_capture;

    // Reduce the drift modulo 12500 into [-6250, +6250).
    if (drift >= 6250) drift -= 12500;
    if (drift < -6250) drift += 12500;

    tune_clock(drift);
}

where tune_clock() is your PLL algorithm responsible for slewing the
software clock.
Pay attention to the signedness of the variables. The subtraction of the
captured values should be done with unsigned numbers, then the result
should be made signed.

Edit: as suggested by James Waldby, I'll give here some suggestions
on the implementation of the PLL. It turns out it is not so simple:
measuring a clock drift is easy, predicting it is harder.
Let me restate the problem. You have a “good” clock: the RTC 1 Hz
signal, assumed to be perfect, but with a limited resolution of one
second. And you have a “bad” clock: Timer 1, which has a 4 µs resolution
but suffers from frequency inaccuracy, instability and sensitivity to
temperature and supply voltage. You want to combine
both clocks into a software clock which tracks the good clock yet has
the superior resolution of the bad clock.
I will use the following notations:

t is the time from the reference clock (the RTC), assumed to be also
the physical time
n = ⌊t⌋ is the integer part of t, which is also the time when we last
got an update from the RTC (a timer capture event)
t′ is the time from the local clock (the Arduino timers)
x = t′ − t is the local clock offset, measured by the ISR above at
integer values of t; the physical time is given by t = t′ − x
y = dx/dt is the local clock drift rate; it's a dimensionless quantity
and typically less than 10−3 (i.e. less than 1 ms/s)
xe(t) is the estimate, made by the software, of the offset x(t)
ye(t) = dxe/dt is the estimate of the drift rate y(t)
te = t′ − xe(te) is our software
clock: a self-consistent estimate of t

The simplest solution, which is equivalent to the one you have in your
question, is to assume x stays constant until it is updated. Thus
xe(t) = x(n)
te = t′ − x(n)
In other words, we are just correcting for the last known offset. The
problem is, as stated before, that this gives a discontinuous time
scale.
A better solution is to try to predict x(n+1), and linearly
interpolate between our previous and our current prediction, thus
building a continuous piecewise linear estimate of x:
xe(t) = xe(n) + (t−n)ye(n+½),
where ye(n+½) = xe(n+1) − xe(n)
From this, the estimated time can be solved for as:
te = n + (t′−xe(n)−n)/(1+ye(n+½))
≈ n + (t′−xe(n)−n)⋅(1−ye(n+½))
The factor 1/(1+ye(n+½)) ≈ (1−ye(n+½)) accounts
for the fact that the clock has drifted since the last update at t = n.
Now we are left with the problem of predicting x(n+1). There are
many possible approaches, and I will try to describe only a few.
Simple PLL
One simple approach is to simulate an analog PLL with a first order
low-pass filter. Here is the first illustration of the Wikipedia article
on phase-locked loop:

Some translation is needed between this analog picture and the digital
domain: The phase comparator takes the difference between the measured
offset x(n) and our previous prediction xe(n). The low pass
filter is implemented as an exponentially weighted moving average. The
output of the filter is our estimate of the drift rate: ye.
The VCO is the formula for estimating te, which has the
built-in drift rate −ye. This could be translated to C++
roughly along these lines:
struct {
    uint32_t n;  // time of last update
    float xe;    // estimate of offset at time n
    float ye;    // estimate of drift rate for t in [n ,n+1]
} clock;

const float tau = 60;  // low-pass filter time constant, in seconds
const float K = 1;     // DC gain of the filter
const float alpha = 1/(1+tau);

// Called by the ISR.
// y is (x[now] - x[1 second ago]) in units of 4 us.
void tune_clock(int16_t y)
{
    static float x;   // last known offset
    x += y * 4e-6;    // update known offset
    float xe = clock.xe + clock.ye;  // estimate of current offset

    // Update time.
    clock.n++;

    // Update our estimate of the drift rate.
    clock.ye += alpha*(K*(x-xe) - clock.ye);

    // Update or estimate of the offset.
    clock.xe = xe;
}

// Estimate the current time.
float time()
{
    float t_local = micros() * 1e-6;
    return clock.n + (t_local - clock.xe - clock.n) * (1 - clock.ye);
}

Note that the code above is only meant as a guide. A good implementation
should use fixed-point instead of floats and should also be
rollover-safe.
The time constant of the filter should be chosen large enough to smooth
out the jitter caused by the 4 µs resolution, yet short enough to
closely track the frequency variations of the local clock. Ideally, it
should be close to the Allan intercept of the x(n) time series.
This kind of PLL normally does a good job at tracking the reference
clock, but it has one drawback: it tends to carry a systematic offset.
Let's assume, for simplicity, that the drift rate is constant. Then it
can be easily seen that the steady state of the PLL carries an offset
error:
te − t = x − xe = y/K
where K is the DC gain of the filter. A large gain minimizes this error,
but it does so at the expense of stability. Too large a DC gain and the
PLL will spontaneously go into large oscillations.
I assume it should be possible to get rid of this systematic bias by
using more sophisticated filters, maybe something like a PID, but I
do not want to dive into the complexities of such filters.
Simple linear extrapolation
Another way of estimating x(n+1), which does not suffer from systematic
bias, is to linearly extrapolate from the two last known values:
xe(n+1) = 2 x(n) − x(n−1)
This means we assume that the drift rate is constant on this
short time scale. The problem with this method is that it tends to
amplify the fluctuations due to the jitter. Assuming for example an
(overoptimistic) drift rate of 2 ppm, the measured offset will
alternate between having zero and 4 µs increments. The
extrapolation will predict every zero increment to be followed by
another zero increment, and every 4 µs increment to be followed by
another 4 µs increment, and thus it will always be wrong. The time
evolution would look as follows:
t[s]    0   1   2   3   4   5   6   7   8   9  10
x[µs]   0   0   4   4   8   8  12  12  16  16  20
xₑ[µs]  0   0   0   8   4  12   8  16  12  20  16

Brown's linear exponential smoothing
Brown's method is one of many linear extrapolation methods
meant to smooth-out noise in the data. It is based on running twice
the same low-pass filter on the input data:
s1 = low_pass(x)   // first smoothing
s2 = low_pass(s1)  // second smoothing

If τ is the time constant of the filter, then s1 is an
average of data which has, on average the age τ, whereas s2
has the age 2τ. When can then, at time t, do a linear extrapolation by
running a straight line through the points (t−τ, s1) and
(t−2τ, s2). This gives the following algorithm for updating
the estimates of the offset and the drift rate:
static float s1, s2;      // x smoothed once and twice
s1 += alpha * (x - s1);   // update s1
s2 += alpha * (s1 - s2);  // update s2

// Update or estimate of the offset.
clock.xe = xe;

// Extrapolate to estimate next offset.
xe = s1 + (s1-s2)*(tau+1)/tau;

// Update our estimate of the drift rate.
clock.ye = xe - clock.xe;

Here again, the optimal time constant should be of the order of the
Allan intercept. Note that the limit τ → 0 gives the simple
extrapolation of the previous section.
The figure below shows the performance of this algorithm on simulated
data. The simulated clock has a drift rate oscillating between 1.7 and
2.3 ppm, and its measured offset is rounded to the closest multiple of
4 µs. The line labeled “predicted (τ = 0)” is the simple
extrapolation of the previous section:

Here, the large jitter of the simple extrapolation method is quite
obvious. On this simulated data, Brown's method works well with a time
constant on the order of 5 s. The frequency of a real clock would
change much more slowly, and a longer time constant would work better.
Now, all this is probably too general for your particular use case. I
didn't know when I started this edit it would lead me so far... If you
can tolerate more than, say, 10 µs of jitter, then the simple
extrapolation should be good enough. And if you only need the time at
t′-periodic intervals, this may enable some optimizations.

The approach of adjusting the drift count due to 6250+ deviation can keep time at perhaps one part per thousand.  However, adjusting the TOP value would allow correction in increments of about one part per 12500.   In other words,  the value loaded into OCR1A should slowly change, over a period of minutes or hours, to produce correct interrupt rate.

@JamesWaldby-jwpat7: I don't understand your comment “[...] can keep time at perhaps one part per thousand”. A properly implemented PLL has exactly zero long term drift (it keeps time at zero parts per million), with only short term variations (phase noise) which depend on the clocks and the PLL time constant. One part in 12500 is 80 ppm, very crude compared with the 4 ppm resolution you get using input capture.

EB, I misunderstood part of your answer and withdraw most of my comment.   It isn't clear to me what control the PLL will vary, what its resolution is, etc.  Perhaps in your answer you could show a typical PLL-corrected time = ... calculation.

@JamesWaldby-jwpat7: Added some options for the PLL algorithm. That was a looong digression...

EB, yes.  Great exposition; I'd upvote your answer again if I could.

If you are using a RTC a far better solution to use alarms.
I use TimeAlarms for this purpose
#include <Time.h>        //http://www.arduino.cc/playground/Code/Time
#include <Timezone.h>    //https://github.com/JChristensen/Timezone
#include <TimeAlarms.h> //  Time alarms for use with Time library
#include <DS1307RTC.h>   //http://www.arduino.cc/playground/Code/Time returns time as a time_t

then include code to do something. The following waits for the Minutes to rollover, then calls function Repeats every 30 seconds etc
const int SampleRate = 30;  // seconds >1

  Alarm.waitMinuteRollover();
  Alarm.timerRepeat(SampleRate, Repeats);           // timer for every SampleRate seconds
  Alarm.alarmRepeat(alarmTime, rolloverLogFile);    // alarm to rollover LogFile (daily)

TimeAlarms can run stuff at one-second-accuracy times, but not 20 times per second.  But perhaps you are referring to using an alarm just for the every-ten-minutes stuff?


text:
Sampling rate of analog read
I have a simple following analog reading code:
void setup()
{
  // initialize serial comms
  Serial.begin(9600);
}

void loop()
{
  // read A0
  int val0 = analogRead(0);
  int val1 = analogRead(1);
  int val2 = analogRead(2);
  // print to serial
  Serial.print(val0);
  Serial.print(" ");
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  // wait
  delay(50);
}

How do I determine the sampling rate? I understand for the serial print, it's 3*4 bytes (for val0,1,2) + 2 bytes for space and 1 bytes for \n, which is 15/9600.
How much time is spent on analogRead?

The sample rate will be somewhat inconsistent since the first few samples' print output will go into the print buffer with little delay. Once the buffer fills, subsequent samples' time spent in Serial.print() will vary somewhat depending on how long printing the currently printing character takes to finish, when Serial.print() is called. But the average sample rate will settle to about to about 64 Hz (1 sec / (15/960 lines/sec).
The printing time for one line is about 15.6 msec, much longer (140 times) than analogRead() takes, about 0.111 msec, according to this author's measurements.
Update:

So I could just use 50ms + 15.6 for the sampling rate, ignoring
  analogRead?

That would get you pretty close to the average sampling interval. If consistency is important to you, you'd need to measure that.
How many samples do you need at a time? Another way is to store the data in an array and print it later. Then the jitter in the sampling interval will be much smaller. You'd be limited to the number of samples you could fit in memory, though. Each 10-bit sample would need 2 bytes of storage.
If the range of your data is less than 256, you could subtract from each sample, the lowest value you expect to see; the difference will fit in 1 byte, doubling your storage capability. Don't forget to add back that lowest value to each one when you print them, though.
It would also be a good idea to test each sample against that lowest number and the lowest + 255, and if any sample is outside those limits, store the low or high limit value instead. Then when you plot your data,
you'll see it "clipping" and know that it exceeded your bounds. Otherwise you'll get overflows in the arithmetic and the out-of-bounds numbers will appear to suddenly take on high values when they really are low, and vice versa.

Thanks! So I could just use 50ms + 15.6 for the sampling rate, ignoring analogRead?

A single call to analogRead() typically takes anywhere between 106.4 and 114.5 µs depending on the phase of the ADC clock prescaler at the time of the call. It can take up to 120.4 µs if it gets interrupted by the timer 0 overflow ISR.


text:
Avoid blocking from bluetooth callbacks
I'm developing a wearable data logging device. Sensors are sampled at 20Hz, and written to a SD card through a buffer. There is an Android app that could query the status of data collection (size of written files, latest timestamp etc) through bluetooth LE.
// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffer.push(a);
}

void loop(){
    if buffer.isFull() {
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffer.getData());
        myFile.close();
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    int freeSpace = SD.vwd()->fileSize();
    // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace);
}

I am worried that long operations inside RFduino callback function might block the data collection process. (freeSpace is an example, I am planning for other useful data for monitoring process). Also, one could repeatedly try to connect to get updated status data.
What is the recommended technique to make sure that data collection process will not be affected?
UPDATE:
The actual usage is that RFduinoBLE_onConnect will be called every hour or on demand only. On the other hand, I am trying to deal with worst case of someone trying to call onConnect repeatedly. Is there any way to see that if data collection is busy then reject the RFduinoBLE_onConnect requests?

Well, one easy, but effective improvement is to use 2 buffers for writing data - while you are writing the one full to file, your interrupt can safely push values to the other and then after the other is full, your ISR would go to first one, while the second will be written. So even long open/seek/write/close loop does not get hit by new data arrival.
Then the main problem - RF - I would bet, that the on_connect() is called from interrupt too, as it is not mentioned anywhere in the loop(). In that case you would like to have it as small and fast as possible. So if you are only providing data, I would collect all the data in the main loop() in some variable (structure, class, what you need), get it thread safe as much as possible (atomic operations, or have two instancies, one actually enabled for the callback, the other opened for filling new data, then pointers to point which is which and just reassigning those pointers in atomic way (means disable interrupts, swich two pointers, enable interrupts - interrupts can wait for time need to two pointers be changed - on other hand you have no chance do anything in main loop (as disabling interrupts), while interrupt is actually running)
So (I know, it is just example, but) you know, that fileSize() is changed only after file is written - so save its value to some (volatile, of course) variable each time you write to the file and use that variable in onConnect.
So more like this (did not tested it, just idea):
volatile buffs[2];
volatile actBuff;
// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffs[actBuff].push(a);
}

volatile int freeSpace;
void loop(){
    if buffs[actBuff].isFull() {
        int fullBuff=actBuff;
        cli();             // disable global interrupts
        actBuff = 1 - actBuff; // switch actual Buffer between 0 and 1
        sei();// enable global interrupts
        // ISR have nice free buffer to fill, we will write and empty the old one
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffs[fullBuff].getData());
        myFile.close();
        buffs[fullBuff].empty()
        int tempval = SD.vwd()->fileSize();
        cli();             // disable global interrupts
        freeSpace = tempval;
        sei();// enable global interrupts:
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    // int freeSpace = SD.vwd()->fileSize();
    // do the same trick here // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace); // use the value from loop
}

authors: владимир стасев

authors: саня ермоленко


text:
Wiring up an ESP 01 to Nano
I've been at this for over a week now and still cant get things working. Im attempting to wire up an ESP-01 chip to a Nano to send AT commands over Serial. I've followed many different tutorials, but the best (and my current) setup seems to be this one:
https://www.youtube.com/watch?v=YKn2ZXYb_EI (Wiring)
https://www.electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html (Wiring & Code)
My breadboard has that exact wiring as shown in the video and the website. I understand that the 3.3v pin doesnt provide enough power, so I've used a DC Voltage regulator to step the 5v pin down to 3.3v, and I'm using that as my main power line.
When I plug the Arduino in, I get a quick couple of flashes from the blue light on the ESP, as well as a solid bright red light. The light is brighter than when it is directly from the 3.3v, so I'm pretty sure it's powered enough.
I then open Serial monitor and get no response when I type AT:

I have tried at both 9600 and 115200 baud, and tried many different wiring setups, all to no avail.
If someone could help with this I'd be forever appreciative

After taking some readings with my multimeter - I see the output of my regulated 3.3 rail drops to 2.55 with the ESP plugged in... Do I want to bring this up even more so it's 3.3 WITH the ESP plugged in?

I don't think the above edits suggestion will work since I've also wired the chip to a 3.3 breadboard power supply powered by a barrel jack - still no avail

I understand I can write firmware directly to the ESP-01, this is not my goal here. I require it as an add-on to the Nano, since I need its analog pins, amongst other things'

Wowwww i finally figured it out after a week of messing around, and 20 mins after posting my question.
To anyone else who stumbles across this: Please understand if you're following this tutorial here or here. There is a bug in the code:
SoftwareSerial softSerial(3, 2); // RX, TX

should be
SoftwareSerial softSerial(2, 3); // RX, TX

Also the suggested baud rate of 9600 doesnt seem to work, adjust to 115200 and go from there. Once you get a receiving signal, run the following to adjust the 01's baud to 9600:
AT+UART_DEF=9600,8,1,0,0

After this, reflash your nano with serial bauds set to 9600 and you should be able to send AT commands over your Nano to the ESP-01 via 9600 baud
In addition to this. You will read online that you might be able to get away with stepping the Nano's 5v pin down to 3.3 to power the module. This didnt work for me, and i suggest you get a breadboard power supply
Good luck to all!


text:
Arduino cant send DHT11 data to Firebase
I have a problem with my project, the problem is that my Firebase can't detect my DHT11 temperature and humidity sensor from the Arduino.
The code runs without an error but the Firebase can't read my sensor.
Here is my code
#include <FirebaseArduino.h>
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#include <DHT.h>

#define FIREBASE_HOST "*****-default-rtdb.firebaseio.com"
#define FIREBASE_AUTH "WE7YUKBpSMo07nUT8ZWYS*****"

#define WIFI_SSID "***"
#define WIFI_PASSWORD "****"

#define DHTPIN D5
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

bool light;
bool fan;

unsigned long previousMillis = 0;
const long interval = 10000;

void setup() {
  pinMode(D1, OUTPUT);
  Serial.begin(115200);
  delay(500);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.println("Connecting..");

  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("Connected ");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  dht.begin();

  delay(2000);

  if (Firebase.failed()) {
  Serial.print("Firebase connection failed: ");
  Serial.println(Firebase.error());
  return;
  }

}

void readDatas(){
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  Serial.println(t);
  Serial.println(h);
  Firebase.setFloat("Data/Temperature:", t);
  Firebase.setFloat("Data/Humidity:", h);
}

void loop() {
  light = Firebase.getBool("LightStates/switch");
  Serial.println(light);
  if (light == true){
    digitalWrite(D6, HIGH);
  }
  if (light == false){
    digitalWrite(D6, LOW);
  }

  fan = Firebase.getBool("FanStates/switch");
  Serial.println(fan);
  if (fan == true){
    digitalWrite(D7, HIGH);
  }
  if (fan == false){
    digitalWrite(D7, LOW);
  }

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval){
    readDatas();
    previousMillis = currentMillis;
  }
}

Here is the screenshot of my Firebase for better understanding:

Temporarily, I am using dummy data for the temperature and humidity. Please if you guys know how to fix it, let me know. it will mean so much to me.

Which Arduino are you using.  Actually, better question, are you trying to run this sensor at 3 Volts?  I recall some say it runs better (more dependably) at 5 Volts.

What does your code output to Serial?

@st2000 i use it in 5 volts

@StarCat it says connected and print the temp&humidity

@jsotola yes its my bad, i have edited my question

Well, I wanted to install my temp/humidity sensor in a hard to reach location.  After some problems on the bench w/the DHT part, I bought a batch of Si7021 (not this board, but same chip) and left the DHT's in the parts bin.


text:
Sending values with pyserial does not function if there is also sensing on Arduino Due
I'm using an Arduino Due to make a feedback loop using python, but this does not seem to function. The python code I'm using is the following:
from serial import Serial
board = Serial('COM11',9600)
board.write('100'.encode()) # 100 is taken as an example

In fact, if I just use Arduino to measure the sensor voltage, it succeeds. It's the same if the voltage is sent without measuring the sensor. But, as soon as I put both simultaneously, the sensor is good but nothing is read by the Arduino.
However, if I send the voltage not using Python but using the Arduino IDE, everything is okay.
It seems that the Arduino can't do the two operations at the same time, but this is weird. Here is my Arduino code:
int const controller = DAC0; // Set the controller output pin
int const sensor = A1; // Set the sensor pin
double MeanNumber = 500;

void setup() {
  Serial.begin(9600);
  pinMode(controller, OUTPUT);
  analogReadResolution(12);
}

double get_voltage(int Measure)
{
  double voltage;
  voltage = Measure * 3.3 / 4095.0;
  return voltage;
}

void loop() {
  double Measure = 0;

  double voltage;
  for (int i = 0; i < int(MeanNumber); i++) // Realize an average each MeanNumber value
  {
    Measure = Measure + analogRead(sensor) / MeanNumber;
    delay(1);
  }

  // Send the averaged measure to python
  voltage = get_voltage(Measure);
  Serial.println(voltage,4);

  // Get the feedback from python
  if (Serial.available() > 0)
  {// Verify if data are available
    String receivedData = Serial.readString(); // Read the voltage value from bytes to string
    float value = receivedData.toFloat(); // Convert the voltage into float
    analogWrite(controller,value); // Send the signal via the Arduino
  }

}

Do you have an idea of what is wrong with my job?

Whenever Python opens a port, the Arduino will get reset. What usually helps is right after you open a port in Python, sleep for a couple of seconds (time.sleep(3)).

Opening a Serial connection will reset the Arduino.  The python code may be doing that when it creates the port.  Put a Serial.print("Starting") line in your setup function to see if that's what is happening.


text:
Making a servo work for just once after a specific time period without hindering the sensors that are reading the data in a loop
I am making a cansat which will be launched on a sugar rocket. The cansat's Arduino nano will be operating sensors which will read the data and store it in an sd card and also a servo to deploy the parachute.
The problem is that I am not able to make code where I want all the sensors to be logging data in the sd card in a loop and a mini servo should perform a sweep angle of 90 degrees after 2 minutes of power supply to the Arduino.
I have made the code for sensors inputting data into sd card but the servo part is confusing me due to no possibility of putting servo code in void setup as the setup will first do the servo sweep after 2 minutes and then record data, neither can I put it in the loop as that also records the data after 2 minutes and I tried to put that into a new function but that's also not working.
Please give me a solution for this.
The code that I have made is below : ( just for sensors logging data in sd card )
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <DHT.h>
#include <SD.h>

#define DHTPIN 10
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

const int MQ2 = A0;

File dataFile;

void setup() {
  Serial.begin(9600);
  dht.begin();
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  if (!SD.begin(4)) {
    Serial.println("SD card initialization failed!");
    while (1) {}
  }
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println("Temperature, Humidity, Pressure, Gas");
    dataFile.close();
  } else {
    Serial.println("Error opening data file!");
  }
}

void loop() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  sensors_event_t event;
  bmp.getEvent(&event);
  float pressure = event.pressure;
  float gas = analogRead(MQ2);
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.print(temperature);
    dataFile.print(",");
    dataFile.print(humidity);
    dataFile.print(",");
    dataFile.print(pressure);
    dataFile.print(",");
    dataFile.println(gas);
    dataFile.close();
  } else {
    Serial.println("Error opening data file!");
  }
  delay(1000);
}

For a parachute I wouldn't code a sweep, I'd just write the servo to 90 so it moves as quickly as possible.  Releasing a parachute is not usually a gradual process.   As far as how, just test millis() in your program to see how long it has been since launch and at 120 seconds write the servo to 90 degrees.

examine the blinkWithoutDelay example sketch in the Arduino IDE

I assumed you would want to collect the data after you opened the parachute. And as Delta_G suggested, you would want to open the parachute as fast as possible and not gradually.
I also assumed you want to collect the data every second, based on your provided code, because it has a 1000-millisecond delay. With all that here is a code that might work: (I haven't tested it, but it should give an idea of how to get going)
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <DHT.h>
#include <SD.h>

#define DHTPIN 10
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

const int MQ2 = A0;
const long parachute_timeout_ms = 2 * 60 * 1000;   // Open parachute after two minutes.
bool parachute_opened = false;

const long data_collection_interval_ms = 1 * 1000; // Collect data every second.
bool start_collecting_data = false;
unsigned long previous_ms = 0;

File dataFile;

void setup()
{
  Serial.begin(9600);
  dht.begin();
  if (!bmp.begin())
  {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  if (!SD.begin(4))
  {
    Serial.println("SD card initialization failed!");
    while (1) {}
  }
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile)
  {
    dataFile.println("Temperature, Humidity, Pressure, Gas");
    dataFile.close();
  }
  else
  {
    Serial.println("Error opening data file!");
  }

  previous_ms = millis();
}

void loop()
{

  // Check to see if it's time to open the parachute.
  unsigned long current_ms = millis();

  if ((parachute_opened == false) && (current_ms - previous_ms >= parachute_timeout_ms))
  {
    // Your code to open the parachute
    // ... ... ..

    // Make sure this code doesn't execute again.
    parachute_opened = true;

    //...and then set the flag that tells the other part of the code
    // that it should start collecting data.
    start_collecting_data = true;
  }

  if ((start_collecting_data) && (current_ms - previous_ms >= parachute_timeout_ms))
  {
    collect_data();
    previous_ms = current_ms;
  }
}

void collect_data()
{
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  sensors_event_t event;
  bmp.getEvent(&event);
  float pressure = event.pressure;
  float gas = analogRead(MQ2);
  dataFile = SD.open("data.txt", FILE_WRITE);
  if (dataFile)
  {
    dataFile.print(temperature);
    dataFile.print(",");
    dataFile.print(humidity);
    dataFile.print(",");
    dataFile.print(pressure);
    dataFile.print(",");
    dataFile.println(gas);
    dataFile.close();
  }
  else
  {
    Serial.println("Error opening data file!");
  }
}


text:
Best way to send a boolean (1/0) to a windows application in real time?
I have an arduino mega connected to a light sensor that reads the status of a machine's indicator light. I have a C++ application that controls the machine, and I would like the arduino to send the application the status of the indicator light in real-time so that the application can control the machine.
Essentially, I just want to constantly send a "1" or "0" through the serial monitor to a C++ application. What would the best way to do this be? I am confused as to the difference between serial.Write() and serial.Print(), what is more optimal for this application?

what amount of delay is acceptable?

I just want to constantly send a "1" or "0" ... it makes more sense to send data when transition occurs and send a heartbeat data the rest of the time

you have to define best before the question   an be answered

Since "optimal" is already a superlative, there is no "more optimal". :-D

It might sound like a good idea to send "0" or "1" in real time, for a fast response, but that might be counter-productive.
For one thing, you are spamming serial data which could slow down the receiving machine slightly. For another, if the sampling rate is faster than the baud rate, then the sending buffer will fill up, and the data being sent will be "old". Say the buffer size is 64 bytes, then the data being sent (and therefore received by windows) could be 64 bytes ago, and not real time.
I would suggest sending a "1" (with Print rather than Write) when the light is on, and then nothing until you detect that the light is off, then send a "0". And ditto for the transition back to being on. Thus the serial data flow merely indicates transitions and not the current state. This greatly reduces the amount of data, and makes it much less likely you will lose some or it will be out of date.
And just in case, send the current state (0 or 1) every second or so, just in case the listening end has only just been turned on.

That makes sense, I only care when the light turns on so I only need to tell the application that the light is on, the default is that the light is off. Thanks!

I agree with both previous answers. Nick Gammon gives excellent advise
on how to handle this situation, and Rohit Gupta gives you the gist of
write() v.s. print(). I would like to elaborate on this write() /
print() distinction though.
These methods of the Arduino API can be confusing, as they have many
different signatures.
write()
Let's look at write() first, as it is the simplest of them:
size_t write(uint8_t);
size_t write(const uint8_t *buffer, size_t size);

These are meant to send a single byte and an array of bytes
respectively. You can send arbitrary bytes, which is usually termed
“binary data”. Note that any data, including text, is binary data: the
term binary here simply means that there is no restriction on the
bytes you can send.
size_t write(const char *buffer, size_t size);

This is the same as the previous one, for the case when the buffer is of
type “array of char”. It can still send arbitrary data.
size_t write(const char *str);

This is a version for sending C-strings, i.e. NUL-terminated buffers.
This one cannot send a zero byte, as that byte is interpreted as a
string terminator. It is thus inappropriate for sending binary (in the
sense of “arbitrary”) data. For this reason, I believe the inclusion of
this overload is a mistake made by the designers of the API, and I would
avoid it in preference of print() which, for this type of argument,
does exactly the same thing.
Note that, in every instance, write() takes the data you give it and
sends it as-is. There is no attempt at formatting it in any manner.
print()
As stated by Rohit Gupta, print() is meant for sending text. If you
have some data to send that is text to start with (like a literal
string), print() sends it as-is, and is thus quite similar to
write(). This is the case for the following overloads:
size_t print(const String &);  // sends a String object
size_t print(const char[]);    // sends a C-string
size_t print(char);            // sends a single character

Then you have some overloads for printing various kinds of numbers. All
of these involve a binary-to-text conversion. The two remaining
overloads, which involve __FlashStringHelper and Printable, are a
bit too technical and I will not discuss them here.
Comparison
All the statements below do the same thing, they send "A" through the
serial port:
Serial.write(65);        // sends a byte with binary value 65
Serial.write('A');       // the ASCII code of 'A' is 65
Serial.print('A');       // a char is print()ed by sending it as-is
Serial.print(char(65));  // 'A' is a shortcut for char(65)
Serial.print("A");       // a one-character string

All the statements below send "65" through the serial port:
Serial.write(54); Serial.write(53);    // send two binary values
Serial.write('6'); Serial.write('5');  // ASCII('6') = 54...
Serial.write("65");       // sends text in a pre-formatted buffer
Serial.print("65");       // same
Serial.print(65);         // print() does the number-to-text conversion
Serial.print(int('A'));   // same

As a general rule, I recommend to always use print() for sending text,
and use write() only for sending data that is not (reliably known to
be) text.

Yes, excellent. I struggle to explain exactly the difference between binary and non-binary. For example "00110001" is arguably binary, however it is an ASCII string with binary digits in it. However (in C++) 0b00110001 is binary in a different sense.

Serial.write sends binary data, whereas Serial.print sends ASCII data.  So it depends on whether you want Windows to receive ASCII 0 and 1 or binary 0 and 1.
I would suggest that you use print and send ASCII data.