body:
(I'm sorry for my bad English, but I will do my best)

I have a Chinese MUC which already programmed. It communicates with a LED driver chip using three wires (STB,CLK,DIN).
(LED driver controls 16 digit 7 Segment display)

After some research, I found that it can be talk to LED driver using shiftout function.

Now the main coal is to connect these
 3 pins(STB,clk,din) to Arduino and read the incoming data and convert the data to numbers.

To test if this idea is working or not,
I came with two arduino (uno to send shiftout function  and mega to read it) after connect pin 2 of uno to pin 2 of mega and same 3 to 3, 4 to 4 and also Gnd of uno to Gnd of mega.
I wrote these codes:

arduino UNO side (to send shiftOut function)
```

    #define STB  4
#define clockPin  5
#define dataPin  6

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

  pinMode(STB, OUTPUT);
  pinMode(clockPin,  OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
 digitalWrite(STB, LOW);
    shiftOut(dataPin, clockPin, LSBFIRST, 0b10101010 ); // 1st digit
   digitalWrite(STB, HIGH);
}

```
arduino mega side (to read shiftOut function)

```

    #define STB 4
#define clockPin  5
#define dataPin  6

 int R_STB[8];
 int R_clockPin ;
 int R_dataPin ;
void setup() {
   Serial.begin(115200);

  pinMode(STB, INPUT);
  pinMode(clockPin,  INPUT);
  pinMode(dataPin, INPUT);
}

void loop() {

 R_STB = digitalRead(STB);
 R_clockPin = digitalRead(clockPin);
 R_dataPin = digitalRead(dataPin);

   for(int i=0 ; i<8;i++){
  Serial.print(R_STB[i]-2);

  Serial.print(" ");
  Serial.print (R_clockPin[i]);

 Serial.print(" ");
  Serial.print(R_dataPin[i]+2);
Serial.println(" ");
   }
 }

```

But the digital read at arduino mega side can't read all data due to it fast switching between High LOW statement maybe? and I am stuck here.

Please any one has any ideas?

title: How to read shiftOut function using arduino

Answers: 1

body:
You are right that you can't read the data fast enough with your method there. What you really need is the opposite of "shiftOut" - which happens to be called "shiftIn".  You use it just like shiftOut, but instead of you sending it a value to send it instead returns a value that it reads.

You trigger it using the "STB" pin:

    if (digitalRead(STB) == LOW) {
        uint8_t val = shiftIn(dataPin, clockPin, LSBFIRST);
        Serial.println(val, HEX);
    }

But the protocol you describe is simply SPI.  There is hardware within the Arduino to handle it for you.  A little harder to work with, but it's capable of working at much higher speeds and is more likely to be able to read your incoming data fast enough.

Resources:

* https://www.arduino.cc/en/reference/SPI
* http://www.gammon.com.au/spi

The latter includes how to configure an SPI "Slave" which is used for receiving data that is sent out from elsewhere.


body:
In my project I need to connect RFID reader (RC522) on top of the Ethernet shield because of it's capability of reading and editing SD card. When I connect only RFID sensor on Arduino, it works. Same goes to Ethernet shield. But when I use both together, It simply doesn't work. I can compile it and upload it, but I don't get anything in the serial monitor. I think it's because both Ethernet shield and RFID reader use the same pins for SPI like MOSI, MISO and SCK. My question is, if that is the problem, how to connect multiple SPI devices on Arduino, or at least on Ethernet shield.

Here is my code, although I think there's nothing wrong with it. I just merged code for RFID and Ethernet shield with copy-pasting. Sorry for bad formatting, I need it just for test, I'll later make the real code.

```arduino
#include <SPI.h>
#include <MFRC522.h>
#include <SD.h>

#define RST_PIN         6          // Configurable, see typical pin layout above
#define SS_PIN          7

MFRC522 mfrc522(SS_PIN, RST_PIN);

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
// MKRZero SD: SDCARD_SS_PIN
const int chipSelect = 4;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(("Scan PICC to see UID, SAK, type, and data blocks..."));

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.println();
  Serial.print("Card type:         ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    while (1);
  }

  Serial.print("Clusters:          ");
  Serial.println(volume.clusterCount());
  Serial.print("Blocks x Cluster:  ");
  Serial.println(volume.blocksPerCluster());

  Serial.print("Total Blocks:      ");
  Serial.println(volume.blocksPerCluster() * volume.clusterCount());
  Serial.println();

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("Volume type is:    FAT");
  Serial.println(volume.fatType(), DEC);

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize /= 2;                           // SD card blocks are always 512 bytes (2 blocks are 1KB)
  Serial.print("Volume size (Kb):  ");
  Serial.println(volumesize);
  Serial.print("Volume size (Mb):  ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Gb):  ");
  Serial.println((float)volumesize / 1024.0);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
  }
}

void loop() {
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  // Dump debug info about the card; PICC_HaltA() is automatically called
  mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
```

title: How to connect SPI device on Etherntet shield on Arduino Uno

Answers: 1

body: The two devices should share SCK, MISO, and MOSI, but SS (or CS as it's sometimes called) will have to be different and both shields are probably trying to use pin 10 for SS.  Let the ethernet shield have pin 10 for SS.  On the other shield, take that pin and bend it out so it doens't go down into the header when you stack them and then solder a wire to it and take it to another pin.  Go into the code and modify the code for that shield to use the new pin as SS instead of pin 10.


body:
 have main board which has motor control circuit and has row and column to control the row and column of the vending machine.

I have made changes in motor in two ways:

A. I have attached an image for circuit diagram
[![enter image description here][1]][1]

In this design I have some pros and cons

PROS: 1. It stops at its home position after one rotation
2. It detects row and column of the machine

CONS: 1. Sometime it does not stop at its home position or take more than 1 rotation

B. I have attached an image of other diagram

[![enter image description here][2]][2]
In this design also I have some pros and cons

PROS: 1. It stops perfectly at its home position after one rotation.

CONS: 1. It does not detect ROW

Please suggest What should I follow and what should I made changes in the circuit.

Here is the video

https://drive.google.com/open?id=1N7ItjeU84JiDAOquAD6SGHkVWufDT40K

https://drive.google.com/open?id=1VX9yncrm6pcr1IBQsNvVZ1yR0UMflJKA

  [1]: https://i.stack.imgur.com/WhUb2.jpg
  [2]: https://i.stack.imgur.com/OuDuu.jpg

title: My 12V DC Vending Machine motor rotates 1 extra 360 degree rotation sometimes. What could be the reasons?

Answers: 1

body:
> "It rotates little bit forward like 10% extra with 3.1 sec delay,"
>
> "I just want to rotate the motor from the home location to the home location when I give signal one time. But i do not know what time delay should I use?"

More than 2.0 and less than 3.1! If 3.1 sec gives 110% rotation, then you need
(100/110)*3.1 = 2.818sec to get 100%.

I realize that your 10% extra is an estimate and not accurate to 3 decimals, but I'd use 2.82 as a starting point and tweak it up or down until you get the amount of rotation you want.

Remember that timing a motor to get distance will inherently be inaccurate due to inconsistencies in the motor acceleration rate and rotation speeds, due to variations in its temperature and the power supply voltage, and load, but this should get you started. For long term accuracy, i.e., if you need it to always come back to a fixed position, you'll need some position feedback, which may be as simple as flag on the motor shaft interrupting a photocell. And even that will have *some* degree of inconsistency due to coasting speed when you shut the power off, but at least those error won't accumulate.

Update:

>  2.82, My motor rotates 10% less every time and change its location in every rotation

Right - 2.82 was a first approximation. If that is too small, try splitting the difference between 2.81 and 3.1. If that ends up too small, then split the difference between it and 3.1; or if it was too big, try splitting the difference between 2.1 and it. Do that a few more times until you have an acceptably close value.

Then read what I said about accumulating errors. The Arduino doesn't ever know what the motor position is so it can't correct for any overshoot or undershoot. If you need accuracy and repeatability, you'll have to add some kind of position sensing, or switch to using a stepper motor and drive the number of steps that makes one full rotation (and it would still have to be started from a known position).


body:
I have created a Bluetooth based smartphone controlled robot (a 4 wheel car) earlier using Arduino and an obstacle avoidance robot.
Now, I wanted to combine both of them. So, I combined their functions and codes in such a manner that felt right to me. But, it kinda seems wrong to my robot.
My Bluetooth Controlled robot was running smoothly. My obstacle avoiding robot was running flawless. But, when I tried to join them, both of them started crying.

I tried to change orders of the functions, adding some functions twice or thrice removing them from some places that didn't feel right then. Nothing was worthy.

I need to upload whole code because I'm not sure where am I doing it wrong

```#define REMOTEXY_MODE__SOFTSERIAL
#include <SoftwareSerial.h>

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL_RX A2
#define REMOTEXY_SERIAL_TX A3
#define REMOTEXY_SERIAL_SPEED 9600

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,8,0,54,0,176,0,8,228,4,
  5,48,44,26,30,30,0,31,8,1,
  6,0,-84,-142,20,20,0,2,26,129,
  0,6,37,23,8,0,64,78,97,118,
  101,100,0,131,3,51,1,20,5,1,
  2,31,82,111,98,111,116,32,67,97,
  114,0,131,0,62,5,19,5,2,2,
  31,67,111,110,116,114,111,108,108,101,
  114,0,129,0,10,45,13,7,0,16,
  84,72,69,0,129,0,5,52,25,8,
  0,136,83,104,101,105,107,104,0,1,
  0,-34,-111,12,12,1,2,31,88,0,
  1,4,79,44,12,12,0,37,151,240,
  159,147,162,0,65,4,87,9,7,7,
  0,65,1,87,17,7,7,0,65,2,
  87,25,7,7,0,67,5,3,3,25,
  14,0,94,24,51,2,0,86,1,11,
  5,0,135,26,31,31,79,78,0,79,
  70,70,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  int8_t joystick_1_x; // =-100..100 x-coordinate joystick position
  int8_t joystick_1_y; // =-100..100 y-coordinate joystick position
  uint8_t rgb_1_r; // =0..255 Red color value
  uint8_t rgb_1_g; // =0..255 Green color value
  uint8_t rgb_1_b; // =0..255 Blue color value
  uint8_t button_1; // =1 if button pressed, else =0
  uint8_t button_2; // =1 if button pressed, else =0
  uint8_t switch_1; // =1 if switch ON and =0 if OFF

    // output variable
  uint8_t red_led_r; // =0..255 LED Red brightness
  uint8_t blue_led_b; // =0..255 LED Blue brightness
  uint8_t green_led_g; // =0..255 LED Green brightness
  char text_indicator[51];  // string UTF8 end zero

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_BUTTON_2 A4
#define PIN_SWITCH_1 A5

#include<AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 250
//#define MAX_SPEED 150 // sets speed of DC  motors
//#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor left_motor_A(1, MOTOR12_64KHZ);
AF_DCMotor left_motor_B(2, MOTOR12_64KHZ);
AF_DCMotor right_motor_A(3, MOTOR34_64KHZ);
AF_DCMotor right_motor_B(4, MOTOR34_64KHZ);
Servo myservo;

int distance = 100;

int right_motor_speed = 0;
int left_motor_speed = 0;
//define two arrays with a list of pins for each motor
AF_DCMotor RightMotor[2] = {right_motor_A, right_motor_B};
AF_DCMotor LeftMotor[2] = {left_motor_A, left_motor_B};

//speed control of motors
void Wheel (AF_DCMotor * motor, int v) // v = motor speed, motor = pointer to an array of pins
{
  if (v > 100) v=100;
  if (v < -100) v=-100;
  if (v > 0){

    motor[0].run(FORWARD);
    motor[1].run(FORWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
  }
  else if ( v<0 ){

    motor[0].run(BACKWARD);
    motor[1].run(BACKWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
/*    //digitalWrite (motor [1], FORWARD);
    analogWrite (motor [2], (v) * 0.75);
    //analogWrite (motor [2], (-v) * 0.75); */
  }
  else{
    motor[0].run(RELEASE);
    motor[1].run(RELEASE);
    motor[0].setSpeed(0);
    motor[1].setSpeed(0);
  }
}

 int lookRight()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE RIGHT SIDE.");
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
 }

 int lookLeft()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE LEFT SIDE.");
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
 }

 int readPing()
 {
  delay(100);
  int cm = sonar.ping_cm();
   if(cm==0)
  {
    cm = MAX_DISTANCE ;
  }
  return cm;
 }

 void moveStop()
 {
  left_motor_A.run(RELEASE);
  left_motor_B.run(RELEASE);
  right_motor_A.run(RELEASE);
  right_motor_B.run(RELEASE);

 }

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_BUTTON_2, OUTPUT);
  pinMode (PIN_SWITCH_1, OUTPUT);

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_BUTTON_2, (RemoteXY.button_2==0)?LOW:HIGH);
  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);

    int distanceR = 0;
    int distanceL =  0;
    delay(40);

    if(distance<=27)
    {
      moveStop();
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 255;
      RemoteXY.green_led_g = 0;
      sprintf(RemoteXY.text_indicator, "AN OBSTACLE HAS COME IN FRONT OF YOUR ROBOT!!!");
      digitalWrite(PIN_BUTTON_2, HIGH);
      delay(1500);
      distanceR = lookRight();
      delay(250);
      distanceL = lookLeft();
      delay(250);

      if(distanceR>=distanceL)
      {
        RemoteXY.blue_led_b = 255;
        RemoteXY.red_led_r = 0;
        RemoteXY.green_led_g = 0;

        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE RIGHT SIDE.");
      }

      else
      {
        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE LEFT SIDE.");
      }
    }
    else
    {
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 0;
      RemoteXY.green_led_g = 255;
      //manage the right motor
      Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
      Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

    }
    distance = readPing();

    //manage the right motor
    //Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
    //Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

  }
```

I want my Robot to work on my directions and when he senses something on its front end then he should stop there and tell me through a RemoteXY.text_string and then check for obstacles at the left and right side and tell me on which side it is available to go. After that, it should again take my orders via my mobile phone.

Firstly, it became impossible to connect the robot to the Smartphone using Bluetooth because the robot was very busy in doing some other stuffs (only he knows what was he doing). Then, I applied a "RemoteXY Button" on my code (that is not in the code that I'm posting here) with an "if" block; such that if this switch is pressed via the Smartphone, only then the robot will start moving. So, doing this thing helped me to connect my robot to my smartphone via Bluetooth but, when I was connection then the Servo Motor was regularly spinning (again, I don't know why) after secure connection, when I turned that switch on, then my robot took only my first order (which is usually moving forward) and it performed on my first order for almost first 3 to 5 seconds and then the Robot got his system hanged and my smartphone was automatically disconnected from the robot.

I am unable to figure out where is the filth in my code or my code is itself fully filthy. This is the matter, where I need you guys' help

Other information that you might need for better Support/help, I am using:
1). RemoteXY app for Android to Robot Communication
2). Arduino UNO as Microcontroller
3). Arduino IDE for Programming Arduino
4). One SG 90 Servo Motor.
5). Four Geared DC- Motors.
6). L293D Motor Driver Shield for driving Dc motors and the Servo
7). HC SR-04 ultrasonic sensor for obstacle sensing
8). A 12V battery
9). HC-05 Module for Bluetooth Communication
10). A buzzer for external indicator/horn. At pin A4
11). A filthy code for Arduino Programming .

Any help with the code will be appreciated.

Thank You So Much in advance. ❤

title: Why is my Arduino code for running a Bluetooth controlled robot with obstacle sensor not working as it should be?

Answers: 1

body:
My guess is, that the function `RemoteXY_Handler()` has to be called very regularly (without long pauses in between) to communicate with the app on your smartphone, or the app will think, that the communication is lost, and disconnect from the robot. This means, that you cannot use long `delay()` calls in your code, since that is just busy waiting. In your code in case of an obstacle in front of the robot, you wait 3.6s in total. That is too much. The robot is doing nothing in this time. Instead you should use a non-blocking coding style. That means, that the code will not block, waiting (and doing nothing) until an event happends (for example a specific amount of time passed), but instead will execute other functions, until the event occurs. That is a generally better way to program a microcontroller, since it enables you to add more functionalities easily without disturbing the program flow.

Here you try to do timed things with `delay()`. Instead you should use a coding style, like the one found in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It is explained various times throughout the internet and this site. Basically it is like regularily looking at your watch (the `millis()` function here) and only doing things, when the time has come. You should look at the example and maybe go through some of the tutorials about this, so that you really understand, what happens there. Then you can start to rewrite your code and eliminate all `delay()` calls. That will need some restructuring of the code.

---

The `BlinkWithoutDelay` example is an easy structure, since it contains only few logic. Your goal is a bit more complex. So I suggest, that you use a Finite State Machine (FSM). It is rather easy to implement and a powerful tool to structure your code. It's definitely worth learning for every programmer.

A FSM consists of multiple states, that are connected by transitions. In each state there can be code executed. Also there might be code, that is only executed on transitions. First you have to model your project into states. One state here could be `REMOTE_CONTROLLED`, which would just execute the commands coming from the app. Based on input from sensors and the app you can then transition between the states. If you see, that you might need a `delay()` inside a state, that might be a hint, that you can further divide the state into substates. For example I would make an extra state, which gives the servo the time to move. I would suggest, that you really draw a graph for your project with all your states (state name in a bubble). Then draw arrows as state transitions between them. This will give you a good overview of the structure to implement.

In code this is often implemented with a `switch()` `case` structure and a state variable:

    int state=0;
    int distance = 100;

    void loop(){
        RemoteXY_Handler ();
        distance = readPing();

        switch(state){
            case 0:
                // Do whatever the remote demands here
                if(distance <= 27){
                    // Execute code, that should happen once at transition here
                    state = 1; // This makes the transition to the next state
                }
            case 1:
                // Code of the next state
        }
    }

With this structure at every time only the code of the current state will be executed. The transitions are made simply by setting the state variable to the next desired state. To make the states more speaking in the code, you can use an `enum`, so that every state can be referenced with an `enum` name. The remote handler and the reading of the distance is done outside the FSM here, since you always need the input from those. Based on them, you can do state transitions.

To do timed things in an FSM, you can put the `millis()` code (like in the `BlinkWithoutDelay` example) into the corresponding state.

---

Note, that this is only one way to implement a FSM. The video, that you linked, does this a bit different by using functions pointers (the `state()` function pointer is the state variable here). The principle is the same, only the programming structure is different. You can decide yourself, what works better for you, and what you understand better (pointers can be a bit difficult to understand for beginners).


body:
I have 2 Arduino Mega 2560 connected via USB to my Ubuntu 18.04 machine. When I boot, one connects to `/dev/ttyACM0` and the other connects to `/dev/ttyACM1`.

Communication works perfectly. However, randomly on boot, the Arduino boards connect to the opposite port of what is coded into the script. I use Python 3.6 to communicate with the boards.

Is there any way to force these boards to always connect to the same port? Or is there a way for Python to detect the board that it's talking to?

title: Multiple arduino connections problem

Answers: 0


body:
I am wondering if this Arduino UNO R3 clone is clocked at 12 MHz instead of the standard 16 MHz? On the board, you can see there is 12.000 written on the crystal oscillator.
[![clone1][1]][1]

But maybe it's not the MCU clock speed? I found this other clone, which has 2 crystal oscillators?! One is 12 MHz and the other one is 16 MHz.
[![clone2][2]][2]

I can't figure out what's happening with these boards... Are these sporting faster or slower speeds? The original Arduino UNO R3 has only one 16 MHz crystal oscillator.

  [1]: https://i.stack.imgur.com/9It2Q.png
  [2]: https://i.stack.imgur.com/awZyF.png

title: Is this Arduino UNO running at 12 MHz?

Answers: 2

body:
The 12MHz crystal is for the USB interface.

The main MCU uses a very small 16MHz resonator, which you can see between C5 and C6.

body:
The 16 MHz resonator, a 3-pin part, can be seen between C5 and C6 in the first picture.

The 12 MHz is for the CH340 as noted.

So it's not an Uno, but a clone ripoff, as an Uno would have a Atmega16U2 for the USB.


body:
I have a simple flashing led program that I want to upload on my pro micro (see image) but it doesnt work (see image: no port available, Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.)

I have successfully uploaded this program on my arduino uno.

Ive followed this guide for the drivers and more.
[https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows][1]

Thanks for help

[![enter image description here][2]][2]

[![enter image description here][3]][3]

[![o][4]][4]

  [1]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows
  [2]: https://i.stack.imgur.com/c3e6g.jpg
  [3]: https://i.stack.imgur.com/2XcV7.jpg
  [4]: https://i.stack.imgur.com/LBzgF.jpg

title: Pro Micro ATMEGA32U4 unable to upload

Answers: 2

body:
Your board will only present a serial port if the sketch that is running on it is programmed to present a serial port. The board does not have an actual serial port for communication with the PC - only what the sketch provides.

If the sketch doesn't provide one, or if the sketch isn't running (for example if it was compiled for the wrong board by accident) then you will never see a serial port.

Since the "normal" way of resetting the board to enter the bootloader (which *does* present its own serial port) is to open the serial port at 1200 baud, since you don't have one to open it's kind of hard to get to the bootloader. However, depending on *what* bootloader you have installed there are a number of options that can help you:

1. Briefly connecting RST to GND just before uploading may activate the bootloader for a few seconds.
2. Doing the above *twice* in rapid succession may activate the bootloader for longer (depending on the bootloader version)

Erasing the chip and reinstalling the bootloader is the only real way that is guaranteed to work, though. But that said, I have seen boards come out of China *without any bootloader at all* - so reinstalling the bootloader is always a good first option with cheap boards.  You can use your Arduino UNO as an ISP programmer (using the ArduinoISP sketch and treating it like you're making a breadboard Arduino).

body:
I have also problem with China boards, after 3 days of googling and trying get boards to work, I found out, that chip it self have difference.one chip is for bootloader from arduino micro, and one from lilypad arduino USB, it is about chip ID when arduino IDE is calling for upload sketch, thers are two 4bit id when it cals. And one is chip with cristal 16MHz lilypad arduino USB, and another version 8MHz Arduino micro, but board is it self looks like Arduino pro micro, Chip type have only few letters difference, if I will never find out that solution, if I will not have two chip comparisions .[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Y6udh.jpg

Last row of numbers makes chip type difference and vendor id depends to what chip type we have. And what clock speed is using. And I see on the veb that many peoples have this problem to not be able to upload simple sketch because of that chip model.


body:
I want to write a c++ program that does something with the data from one of the input analog pins as the program runs, but I want to know how to get the value from the arduino uno though the USB port (that I am also using to power the uno) and into my laptop for using. IS there any documentation I should read?

My laptop runs Ubuntu 18.04 if that matters.

EDIT: I am not talking about the Serial monitor by the way

title: How To Get Data From Arduino Uno Onto My Laptop Through The USB

Answers: 1

body:
The "Serial Monitor" is merely a window to the Arduino's serial port. You don't have to use it to use Serial. It's just a (very simple) built in way of seeing the data.

You can use the Serial interface with your own software, or with third party software. It's not tied to the Serial Monitor in any way at all.

So:

* Use `Serial.print()` etc to send data to the PC
* Write your own PC software in your language of choice to process that data, or
* Use some third party application to read and process the serial data


body:
Sorry for the newbie question (just started learning electronics).

I just saw a tutorial that says that the 5V output pin on the Arduino delivers more amps (if needed) when connecting more voltage to the board (connecting to the 9 - 12V instead of 5V).
Does that mean that the 5V pin then delivers more than 5V as well?

title: 5V pin output on arduino

Answers: 1

body:
Time for a crash course in electronics and power:

The 5V pin only ever provides 5V. That's why it's the "5V" pin. (assuming, of course, that you give the board *more* than 5V).

In simple linear electronics you have three values:

* The voltage
* The current
* The load

Generally two of the three are either "fixed" or "known" and the third changes depending on the other two. For simple resistive circuits (where the load is a simple resistor) this relationship is Ohm's Law.

* If the voltage is fixed, and
* If the load changes, then
* The current will also change to keep the relationship stable.

A "power supply" (any device which provides power to some other device) generally has two parameters: Voltage and Current.  One of those is always fixed. The other is always variable, and quoted as a maximum that the supply can give.

For the Arduino's 5V pin the parameters are:

* Voltage: 5V
* Current: 800mA Maximum

That means that the 5V pin has a fixed voltage of 5V, but the current is free to change depending on the load *up to a maximum of 800mA* (or a lower limit if you are providing the input power from a source with a lower current. There is also heat to consider with the Arduino - see below).

The two values, voltage and current, combine together to give the "power" of the power supply, through simple multiplication. So the Arduino's 5V pin is 5V × 0.8A = 4 watts maximum.

When you provide power to the Arduino through the barrel jack it first goes through a *linear voltage regulator*.  This is the device which takes the incoming voltage and reduces it to 5V. Since energy can neither be created nor destroyed it does that reduction in energy by converting some of it to heat.

Say you connect something up that needs 100mA and you plug in a 9V power supply to the board. Let's also assume that the Arduino itself needs 50mA (I like nice round numbers).

* That's 150mA in total for the "load".
* The incoming voltage is 9V
* The outgoing voltage is 5V

The power of the input is thus 9V × 0.15A = 1.35W
The power of the output is then 5V × 0.15A = 0.75W

The power difference is 0.6W

That 0.6W is converted from electrical energy to heat energy by the voltage regulator and "thrown away".

So the "heavier" your load (the more current you demand from the 5V pin) the greater the heat that is generated by the voltage regulator.

When the regulator gets too hot one of two things happen:

1. A good quality regulator will shut down and you will lose power to the board
2. A cheap Chinese regulator will likely "fail short" and feed your 9V direct into the Arduino causing components to release their Magic Smoke™ and stop working


body:
I'm using an OLED display connected to a push button.  I am trying to get my display to show two different values independently  by using the push button to switch between them. Here is a snap of my code from the loop function:

        if (buttonState == HIGH) {
        x=x+1;
      }
      if (x == 1) {
      display.setTextColor(WHITE);
      display.setCursor(0, 0);
      display.setTextSize(2);
      display.print(T);
      display.print(" degree");
      display.display();
      display.print(x);

    }
        else if (x == 2) {
      display.setTextColor(WHITE);
      display.setCursor(0, 0);
      display.setTextSize(2);
      display.print(perventage);
      display.print(" %");
      display.display();
      display.print(x);
    }
        else  {
          x=1;
          }

      delay(10);
    }

 x is defined as 1 initially out side the loop.
What happens is that when the circuit is turned on, the screen displays the value of T then what should happen is when I push the button it switches to the second value which is percentage, and I push again to go back to T. My issue is that the Arduino doesn't response to the push button all of the time sometimes it takes 1 click and other times it takes 6 or 8 fast clicks to switch between them and it doesn't stick to a specific number of pushes to switch.
What would you suggest me to change to fix it.

Edit: here is pic of my wiring diagram
[![Wiring diagram][1]][1]

  [1]: https://i.stack.imgur.com/Z9wr9.png

title: My push button code doesn't work properly

Answers: 2

body:
You are reading the raw button state without debouncing it, so you may be getting 2 (or 4, or ...) pulses so quickly - off the same button-push - that the display or your eye can't respond that quickly. Here is [Nick Gammon's tutorial on switches and buttons][1], including debouncing.

Also make sure you use a pull-down resistor on the button input-pin. Floating inputs are noise and will give you a lot of false signals.

  [1]: http://www.gammon.com.au/switches

body:
One core problem is that you have a simple "If the button is HIGH then cycle through the numbers". The longer you hold the button the more times it will cycle through the numbers.  It's pure 50/50 chance that you happen to release the button on a different number to the one it started on.

Instead you need to look for a *change* in the state of the button. Has it changed from LOW to HIGH:

    static uint8_t oldState = LOW;

    uint8_t buttonState = digitalRead(BUTTON_PIN);
    if (buttonState != oldState) {
        oldState = buttonState;

        if (buttonState == HIGH) {
            // This only runs once at the moment of pressing
            // the button - not continuously while you're
            // holding the button in.
            // Cycle through your displays here.
        }
    }


body:
I am trying to set up my Arduino Uno to receive information from the internet, but I am having a very hard time finding proper guides online. I am using an Arduino Uno and ESP8266-01. I am trying to use the "WebClientRepeating" example from this library:
https://github.com/bportaluri/WiFiEsp

Here is the code I am running (updated the SSID and password):

    /*
     WiFiEsp example: WebClientRepeating

     This sketch connects to a web server and makes an HTTP request
     using an Arduino ESP8266 module.
     It repeats the HTTP call each 10 seconds.

     For more details see: http://yaab-arduino.blogspot.com/p/wifiesp.html
    */

    #include "WiFiEsp.h"

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

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

    char server[] = "arduino.cc";

    unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds

    // Initialize the Ethernet client object
    WiFiEspClient client;

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

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

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

      Serial.println("You're connected to the network");

      printWifiStatus();
    }

    void loop()
    {
      // if there's incoming data from the net connection send it out the serial port
      // this is for debugging purposes only
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }

      // if 10 seconds have passed since your last connection,
      // then connect again and send data
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();
      }
    }

    // this method makes a HTTP connection to the server
    void httpRequest()
    {
      Serial.println();

      // close any connection before send a new request
      // this will free the socket on the WiFi shield
      client.stop();

      // if there's a successful connection
      if (client.connect(server, 80)) {
        Serial.println("Connecting...");

        // send the HTTP PUT request
        client.println(F("GET /asciilogo.txt HTTP/1.1"));
        client.println(F("Host: arduino.cc"));
        client.println("Connection: close");
        client.println();

        // note the time that the connection was made
        lastConnectionTime = millis();
      }
      else {
        // if you couldn't make a connection
        Serial.println("Connection failed");
      }
    }

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

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

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

My wiring is as follows:

 - ESP8266 RX - Uno Pin 7
 - ESP8266 TX - Uno Pin 6
 - ESP8266 VCC - 3.3V power source (not from Uno)
 - ESP8266 GND - Uno GND
 - ESP8266 CH_PD - 3.3V power source (not from Uno)

I also connected the GND of the 3.3V power source to the other GNDs.

When I go to run the WebClientRepeating example, my Serial output says:

    11:05:04.764 -> [WiFiEsp] Initializing ESP module
    11:05:05.760 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:07.785 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:09.758 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:11.780 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:13.803 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:14.794 -> [WiFiEsp] Cannot initialize ESP module
    11:05:20.794 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:20.794 -> [WiFiEsp] No tag found
    11:05:20.830 -> WiFi shield not present

The tutorial specifies that it uses a "ESP WiFi shield" but I am using a ESP8266 card only - could that be part of the problem? If that is a problem, are there any simple guides out there for how to connect the Arduino Uno to the internet to read information? I am frustrated with the lack of good documentation, and would really appreciate some help.

title: TIMEOUT error when connecting ESP8266 to Arduino Uno

Answers: 1

body:
It means that your ESP8266 is not detected

Because of you connect RX and TX (6 and 7) to secondary pin.
Use your standart RX TX pin to solve the problem


body:
I bought an Arduino Mega 2650 alongside a couple of ESP8266 chips hoping to make a wireless project take off.

Using the basic serial passthrough code

    void setup() {
        Serial.begin(9600);
        Serial1.begin(115200);
        Serial.write("Starting");
    }

    void loop() {
        if (Serial.available()) {      // If anything comes in Serial (USB),
           Serial1.write(Serial.read());   // read it and send it out Serial1 (pins 0 & 1)
        }

        if (Serial1.available()) {     // If anything comes in Serial1 (pins 0 & 1)
           Serial.write(Serial1.read());   // read it and send it out Serial (USB)
        }
    }

updated to use a 115200 baud rate which it seems my version of the 8266 is programmed to use, I encounter this problem when trying to issue it commands:

    Starting
    AT

    ERROR

[Looking around][1] [I found][2] that this could be caused by the chip not getting enough power. So I hooked it up to a small power breakout board [![breakout board][3]][3]
 with a small 12 power supply I used to have connected to something else. After doing that all it does is spit out question marks even when I dont send anything. Weird part is the TX pin on the arduino thats going crazy? As if I am sending it to myself without a prompt from the ESP board. This only happens when I'm connected to that breakout supply.

[![nothing][4]][4]

Other oddity:
If I have all my wires except for VCC/CH_PD connected everything is fine, but the second I connect them to that power supply everything goes crazy and my TX pin starts flashing up a storm (can it be a voltage issue that also transfers to my Arduino board as well?)

  [1]: https://www.quora.com/Why-does-ESP8266-give-error-message-on-AT-command
  [2]: https://arduino.stackexchange.com/questions/21172/esp8266-01-at-commands-returns-random-chars-and-or-error
  [3]: https://i.stack.imgur.com/jdGOm.png
  [4]: https://i.stack.imgur.com/z9n1Y.png

title: Arduino with ESP8266 via serial pass through

Answers: 0


body:
I'm currently working on an IOT project with my esp32, ill need it to run on batteries, I will only be needing "active mode" with wifi once per hour to upload some data to a database and then go back to deep sleep (need to save data cant use hibernation).

[THIS][1] website explain pretty well how much energy the esp needs, but it says e.g. 30mA - 60mA, but on batteries it says mAh, so is the mA just mAh or how do I calculate the power usage?

.

ps.

currently, I'm thinking of using 2 cr2032 batteries, good recommendations on batteries are welcome

  [1]: https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/

title: power consumption of esp32

Answers: 1

body:
There's a number of things to consider when choosing batteries.

First is the capacity. In broad terms, the capacity is, mAh, means "This battery can supply X mA for one hour". So a battery of 1000mAh could supply around 1A (1000mA) for one hour before it goes flat.  Simply divide the mAh by your device's mA and you get the time it will run for before it goes flat. So a 50mA device would run for about (1000 / 50) 20 hours before running flat.  That is only a "ball park" figure though, since the capacity is somewhat dependent on the amount of current you draw.

Then there is the question of the internal resistance of the battery. This determines the maximum current that you can draw from the battery before the voltage drops below a usable level.  Different battery chemistries have different internal resistances.

Small button cells like the CR2032 have a high internal resistance and a low capacity.  A [typical cheap CR2032](http://www.farnell.com/datasheets/1671733.pdf) has around 200mAh capacity. At 50mA that would last 4 hours. But drawing 50mA from a CR2032 is not really on.  Looking at the graphs in the datasheet linked to above you can infer that, with a nominal voltage of 3V, with a 1kΩ load the output drops to 2.6V. That means that 1kΩ is drawing (2.6/1000) 0.0026A (2.6mA).  The internal resistance is dropping (3 - 2.6) 0.4V, therefore the internal resistance must be (0.4 / 0.0026) 154Ω.

Drawing 50mA from the battery would mean the internal resistance would drop (154 * 0.05) 7V. Since you can't get below 3V, that means the battery simply can't support that kind of current drain.  Indeed, in the datasheet I link to the "Standard Current Drain" (the current it's rated for as "normal" usage) is a mere 0.1mA.

So to work out what battery you need, you want:

* The average current draw over the period of an hour
* The peak current draw the device will draw
* The length of time you need the device to run for between battery changes / recharges

For the ESP32 the current can peak at hundreds of mA depending on what you are doing (WiFi uses a lot of power in short bursts). The average will be based on the ratio of the "running" time to the "sleeping" time, and the current draw for both those states.


body:
I am very new to all this, but have programmed in other languages using several IDEs. Last night when returning to a coding session, I noticed that the background of the sketch window had gone from white to gray. Then when I tried to continue editing the sketch, I found that I could not make any changes. At all. Clicking anywhere on the screen is futile; the cursor never appears. Text can be highlighted but not copied or pasted. In short, I can’t go on from here at all.
What have I done?

title: Arduino IDE: sketch window has become unresponsive

Answers: 0


body:
I have a little and common application in which a sc-28 moisture sensor reads humidity levels and turns a servo (which drives a little faucet) if the soil needs water. Arduino nano is the brain.

All of them is tested and working fine on the proto board. Soil sensor is powered by 5v rail of arduino and everything seems fine even with the servo pulling from 5v rail too.

With all working, I try to translate that to a perfboard. The only difference in circuits are how they are powered.

While the prototype is powered via usb, the definitive one is powered through a 24v psu, leveling the voltage with a lm2596 module down to 5v.

Then this 5v feeds the nano (vin pin) and servo, while the soil sensor still pulls from 5v rail of the arduino to avoid vref problems.

And then, the sensor does not work. No led indicating power or data. This were my steps trying to debug it:

 - **Triple check every connection on the board.** While I am a decent programmer, my solder skills are kind of lacking. But everything looks fine, nothing shorted or loose.

 - **measure voltage**. On the perfboard, voltage between vcc and gnd connector pins spits 4.78v, which is supposed to be in range for the sensor to work.

 - **Power the board through usb** I tried this too, and is not working. Lm module and arduino lights up, code can be executed. I can't explain why the lm2596 module lights up too, and I'm thinking is part of the problem but I do not know. Voltage at soil sensor is still 4.78

And then I'm done. I dont know what could be happening and I only can make wild guesses. It's obviously a board problem, and i am aware I am doing something wrong but I can't see it.

Below, my horror soldering skills and the board. Soil sensor is the 4pin females at the bottom left and servo the 3pin males at the bottom right.

 [![image 1][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/UcjJV.jpg
  [2]: https://i.stack.imgur.com/Mjd3D.jpg

title: Soil moisture sensor not working in "pcb"

Answers: 2

body:
>Then this 5v feeds the nano (vin pin)

Can't feed 5V into Vin and get 5V out. Connect 5V to the 5V pin.

body:
The answer was, in fact, my poor experience with these boards and how they work.

As you can see in the pictures, wire and connectors are on opposite sides of the board. I was assuming that pads were connected on both sides, which is not true. Therefore, connectors were simply dead.

Soldered again at the wire side and it works like a charm. Thank you all for every suggestion, and the learning experience.


body:
I´m building a system that has two arduinos (like the image on the botton) linked via `ICSP`. The "Programer"  programs the second one, called "Worker"( with a .hex file in the SD card of the Programer).

The Worker controls a `LCD 16x4` and displays messages to the user.

What I´m tring to do is when the Programmer is programming the Worker it also displays a message like "Programming, wait" in the Worker LCD. But in code, just telling to the Worker displays a message is not going to happen because when it has been programmed it displays garbage in the LCD.

**Q** So is it possible the the Programmer takes control of the LCD before it begin to program the worker and displays its message?

The LCD works with normal 4-bit mode comunication and I would rather not converte it to I2C if it´s possible.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/IdFMD.png

title: Two Arduino Control a LCD Display

Answers: 1

body:
There are two solutions that come to my mind, one more HW based and another more SW based.

## Solution 1 ##

The HW way is to let the programmer control the LCD through 2:1 multiplexer(s). You will need to connect the LCD pins to the common pin of the multiplexer, the Programmer's ones to one of the two inputs and the Worker's to the other. Then the programmer can choose who controls the LCD through the additional pin. An example of the multiplexer you can choose is the 74LS157, but there are virtually infinite part numbers. The disadvantage of this approach is that you need to write the whole LCD control stack in the Programmer.

## Solution 2 ##

An alternative, more relying on the SW, is implementing a way to let the slave know that you want to program it. For instance, when a programming is needed the Programmer raises a pin; the Worker writes the string on the LCD, then stops working, raises another pin and waits to be cleared. The programmer then proceeds to flash the Worker, and the message will remain on the LCD. It may happen that garbage exits from the Worker's pins when being programmed. If so, change the enable pin or find a way to temporarily detach it from the Worker to avoid signals reaching the LCD. This schematic illustrates this concept:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/1dhpY.png)

<!-- End schematic -->

When the Programmer wants to program the unit, it sets the DL_Req pin to high. The Worker sees this, and performs accordingly. I think pins are not moved then, but if for instance some noise appears on the signals during programming (and the LCD displays this noise as weird chars), try changing the pin associated to the enable pins (LCD2 in the example above) or put something to prevent noise on that wire only, so that LCD content is not modified.

Personally I'd go with the second solution, but this depends on how much you can change the behavior of the worker and programmer


body:
I'm using Arduino Mega 2560, A4988 motor driver for 5 stepper motors. There are X1, X2, Y, Z, A axis, and if I control Y and Z at once, it works. But when I just change axis from Y&Z to X1&X2, only X1 stepper motor spins. X1&X2 need to move at once(simultaneously) due to they are connected in single bar.

My Arduino IDE code is,

==============================

```
const int X2step = 5;

const int X2dir = 4;

const int X1step = 3;

const int X1dir = 2;

void setup() {

    pinMode(X1step,OUTPUT);

    pinMode(X1dir,OUTPUT);

    pinMode(X2step,OUTPUT);

    pinMode(X2dir,OUTPUT);

}

void loop() {

    digitalWrite(X1dir,HIGH);

    digitalWrite(X2dir,HIGH);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    delay(1000);

    digitalWrite(X1dir,LOW);

    digitalWrite(X2dir,LOW);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    exit(0);
```
=================================================

Any suggestion would be helpful for me. Thanks.

title: Control two stepper motors simulatenously?

Answers: 1

body:
You likely have other issues to boot based on what you said about only X1 moving, but first I suggest resolving the bug in your code.  It appears to be that you have delays between your digital writes to x1, x2. And set their directions to the same.

At the very least you should be writing to X2 step every time you write to X1 step.  If your wiring is *identical* and the motors are essentially attached *mirrored* on opposite sides of a shaft, don't forget to set the directions opposite before you start sending steps. (If they are on opposite sides of the shaft, one spinning counterclockwise means the other spins clockwise.  You can also play wiring tricks with what coil goes where and how, but identical is simpler.)

    digitalWrite(X1dir,HIGH);
    digitalWrite(X2dir,LOW);

Or

    digitalWrite(X1dir,LOW);
    digitalWrite(X2dir,HIGH);

Then step it like

    digitalWrite(X1step,HIGH);
    digitalWrite(X2step,HIGH);

    delayMicroseconds(2000);

    digitalWrite(X1step,LOW);
    digitalWrite(X2step,LOW);

    delayMicroseconds(2000);
    ...


body:
I am considering using an arduino over the raspberry pi for a new project. However, I am not sure what arduino I should buy so that it is compatible with the below add-on.

![add-on board](https://i.stack.imgur.com/DAnCc.jpg)

Are all Arduinos compatible?

TIA.

Edit:

Link to product- https://www.adafruit.com/product/3387

My goal is to use an arduino with the above product to move a 3D model in Unity 3D.

title: What Arduino boards would be compatible?

Answers: 1

body:
As one can see from the pinout description page (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/pinouts):

[![][1]][1]

So this board is literally designed to be powered by 3.3V and 5V and have compatible logic levels for both these voltage ranges, which is what every Arduino known to me and the Raspberry Pi use.

Furthermore, there is also Arduino Code (https://github.com/adafruit/Adafruit_LSM9DS1)  which is compatible with pretty much every Arduino Core and Raspberry Pi Python code (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/python-circuitpython).

So by means of voltage levels and platforms, this board is highly compatible with everything out there that is either 3.3V or 5V powered and has a SPI or I2C peripheral.

  [1]: https://i.stack.imgur.com/ZxU8u.png


body:
I am running into buffer issues when running the Firmware.ino example [here][1].

The output from my Arduino serial log on baudrate 115200 (I put the ESP on baudrate 9600):

    Begin
    01:17:15.538 -> Baudrate set success
    01:17:15.585 -> Station + softAP - OK
    01:17:18.631 -> Joining AP successful, IP: 192.168 r⸮+@⸮
    01:17:18.991 -> Single Mode OK
    01:17:18.991 -> Sending Request to www.google.com
    01:17:19.084 -> create tcp - OK
    01:17:19.710 -> not sentbuffer is full!
    01:17:20.022 -> HZiw93GUFmVJYFz-yRmahGURP_UBbRb4EF0Ahwzx8MJ1GOyC5Z0dns8UD41G8kUqnL0oxNPxa6xF9nAqNF3X3B_hKW11zoyaBPn8trvUNt-69qbFCNOZwNjgoaloKbOQs7NN-B3tpmwFKpHfKsfKyZfiMdhulN3SgZMhewYBg9c; expires=Wed, 05-Feb-2020 05:17:18 GMT; path=/; domain=.google.com; HttpOnly
    01:17:20.162 -> Accept-Ranges: none
    01:17:20.162 -> Vary: Accept-Encoding
    01:17:20.209 -> ConnecS,
    01:17:24.179 -> Sending Request to www.google.com
    01:17:24.774 -> create tcp - ERROR
    01:17:28.759 -> Sending Request to www.google.com
    01:17:29.432 -> create tcp - ERROR
    01:17:33.402 -> Sending Request to www.google.com
    01:17:34.021 -> create tcp - ERROR
    01:17:38.028 -> Sending Request to www.google.com
    01:17:38.669 -> create tcp - ERROR
    01:17:42.681 -> Sending Request to www.google.com
    01:17:43.294 -> create tcp - ERROR
    01:17:47.298 -> Sending Request to www.google.com
    01:17:47.954 -> create tcp - ERROR
    01:17:51.925 -> Sending Request to www.google.com
    01:17:52.595 -> create tcp - ERROR
    01:17:56.563 -> Sending Request to www.google.com
    01:17:57.204 -> create tcp - ERROR
    01:18:01.222 -> Sending Request to www.google.com
    01:18:01.871 -> create tcp - ERROR
    01:18:05.839 -> Sending Request to www.google.com
    01:18:06.460 -> create tcp - ERROR
    01:18:10.456 -> Sending Request to www.google.com
    01:18:10.596 -> create tcp - OK
    01:18:11.049 -> buffer is full!
    01:18:11.049 ->
    01:18:11.049 ->
    01:18:11.049 -> +IPD,1430:HTTP/1.1 200 OK
    01:18:11.096 -> Date: Tue, 06 Aug 2019 05:18:09 GMT
    01:18:11.096 -> Expires: -1
    01:18:11.096 -> Cache-Control: private, max-age=0
    01:18:11.143 -> Content-Type: text/ht
    l; charset=ISO-8859-1
    01:18:11.143 -> P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
    01:18:11.190 -> Server: gws
    01:18:11.190 -> X-XSS-Protection: 0
    01:18:11.190 -> X-Frame-Options: SAMEORIGIN
    01:18:11.224 -> Set-CooS,
    01:18:15.192 -> Sending Request to www.google.com
    01:18:15.822 -> create tcp - ERROR
    01:18:19.849 -> Sending Request to www.google.com
    01:18:20.473 -> create tcp - ERROR

As you can see, at first it starts ok, gives a buffer error, runs in error for a while, then runs OK again. This happens a couple times, then it runs only in error. I imagine this is some issue with the buffer of the ESP or the Arduino, but I'm not sure how to diagnose it further.

Things I have tried to fix the error:
 - As mentioned in the Firmware.ino example comments, I uncommented #define ESP8266_USE_SOFTWARE_SERIAL
 - Also as mentioned in the comment, I changed line 42 from 64 to 256. It didn't work either time.
 - There is a MAX_BUFFER_SIZE in the included ESP8266.h library that I also changed, from 300 to 256, because I thought that might help, but the error persisted.

  [1]: https://github.com/Circuito-io/ESP8266_SoftwareSerial/blob/master/examples/Firmware/Firmware.ino

title: Buffer overflow error in ESP8266_SoftwareSerial library

Answers: 1

body:
There's some heavy `String` usage in that library, would not recommend it for anything you want to be stable, especially with an Uno.

The library seems to create a connection by first clearing the `SoftwareSerial` buffer and then issuing the right AT command. It waits for 500ms for a response before giving up. I suspect the wait interval is sometimes not long enough for the module to receive, parse and handle the command before responding. So you should try increasing it to 2000 ms at line 773.

The `buffer is full` message just refers to the library's own buffer for holding received data, which is 300 bytes by default. The buffer's getting filled so quickly (and the `SoftwareSerial` internal buffer likely overrun too) because you're loading a webpage like Google's which has more than 300 bytes in the response header alone. It's even possible that by the time the next request commences with another AT command, the ESP8266 is still dumping the response from the previous request, and so the command's response is still way down the queue and so doesn't get read before the timeout.

Instead, try loading a simple webpage like `httpbin.org/ip`. That is, at lines 952, 954:

    char* request =  "GET /ip HTTP/1.1\r\nHost: www.httpbin.org\r\nConnection: close\r\n\r\n";

    if (createTCP("www.httpbin.org", 80))


body:
I am using Nodemcu ESP8266. I want to know how much my ESP board consume the battery during sleep mode.
as the Mannual said it spend about micro-ampere, but my multi meter said it spend 10 mili-ampere, I cannot believe the result.

so please see My arrangement is right and give some advice

[arrangement image][1]

[![enter image description here][2]][2]

red line is for vin, black line is for GND.
black pin is COM, red pin is mA.

I set multimeter on 20mA, 200mA, it said it is 10mA.
when I change multimeter to 10mA, 1mA, microAmpere, number was overflowed.

I already connected to RST - D0, so It is properly sleep & wake up automatically. and here is my running code in the board

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

void setup() {

}

void loop() {
  // put your main code here, to run repeatedly:

ESP.deepSleep(60e6);

}
```

  [1]: https://i.stack.imgur.com/gTVLQ.jpg
  [2]: https://i.stack.imgur.com/mvWGD.jpg

title: ESP8266 spend 10mA, even though It is in the deep sleep mode

Answers: 2

body: `ESP.deepSleep(60e6, WAKE_RF_DEFAULT);` Try this code, it should decrease it a bit.

body: The Board you are using contains an ESP-12F Module, along with other chips that make it easy/possible to connect to UART over USB and thus flash the chip. This USB-to-UART converter chip isn't related to the ESP-12F Module, so is unaffected when the ESP goes to sleep, so the converter continues to draw about 10mA. You can't do anything about this unless you desolder it, or use a pure ESP-12F Module.


body:
I am working on a clock movement that is powered using a stepper motor and the GSM2 driver board. The delay between steps needed to achieve 1 rpm on the second hand works out to 25 ms. In my current setup, I am sending pulses to the driver board using the delay() function. This works reasonably well, although it is not accurate enough for me. To remedy this problem, I ordered a DS3231 RTC module, thinking I could use that to replace delay()/millis(). However, I can't figure out how to achieve millisecond resolution using the RTC. It seems like it should be strait forward given the oscillator on board the RTC is 32kHz. I am new to arduino programming and am out of my comfort zone with this one.

Does anyone know of a way to achieve the 25 ms pulses we need while still retaining the accuracy of the RTC? Is it possible to use the RTC to correct the output produced by the built in delay()/millis() function? How would you then translate that output to pulses sent to the stepper motor driver board?

Internet research produces some mixed results on whether or not this is possible. I have yet to see an example of a clock with millisecond resolution. The theory behind it makes sense, but I don't know where to start.

title: Stepper motor based clock movement with DS3231

Answers: 2

body:
It is unclear, why you need the high accuracy, and you didn't include your code. So my explanations will be as broad as your question.

"millisecond resolution" is a broad term. Generally you have to consider 2 different errors.

1. The jitter for every `millis()` value
2. clock drifting over time

You can eliminate the second point quite easily using the RTC with the [Time library][1]. It uses the RTC as a reference, so that you don't have the clock drifting this much. Though, you would have to use the libraries functions for all time related things, since it does not change the value of `millis()` or it's siblings.

Also, for low differences in the range of a few milliseconds, you should better use `micros()` instead of `millis()` (if you are not using the RTCs functions).

---

> How would you then translate that output to pulses sent to the stepper motor driver board?

It is unclear, why exactly you need "millisecond resolution", and you didn't show us your code. But there are multiple Stepper libraries on the web, for example the standard [Stepper][2] library or the [AccelStepper][3] library (Accelstepper is more capable, don't know, if you need it). With the AccelStepper libraries you can set a certain speed and target position and then you simply call then `run()` method (haven't looked up the name, but there is definitely a function like that) until the desired position is reached. The method itself will only pulse the stepper, if it is time to do so. So you are freed from doing all the stuff with `millis()`, since the library is doing that for you.

Though the libraries are using the Arduinos internal time: `millis()` and siblings. To change that, you would have to change the library.

  [1]: https://github.com/PaulStoffregen/Time
  [2]: https://github.com/arduino-libraries/Stepper
  [3]: https://github.com/adafruit/AccelStepper

body:
Consider a Phase Locked Loop (PLL) to synchronize your 40x 25ms pulses with your 1pps RTC.

If you need 25ms/pulse to get 1rpm, that's 2400ppm or 1pulse/0.025ms=40pps.  If you get a 1pps pulse out of the RTC, you can use it to discipline your timing.  https://www.romanblack.com/one_sec.htm is a good reference.

The basic trick is to keep track of the mismatch and run faster when it is slow, and run slower when it is too fast.

Try something like the below, but replace the LED pulse stuff with your stepper code.

    // pps_pll.ino for https://arduino.stackexchange.com/questions/67699/stepper-motor-based-clock-movement-with-ds3231
    //
    // Adapting code from https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
    // to do a PPS PLL per https://www.romanblack.com/one_sec.htm

    const int pps = 40;
    const int pulse_us = 1;
    const int pulse_interval = (1000L / pps);
    int count = 0; //
    int count_at_sync = 0; //
    unsigned long next_pulse = 0; //
    unsigned long pulse_off = 0;

    const byte led_pin = LED_BUILTIN;
    const byte interrupt_pin = 2; // Choose pin per https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
    volatile byte state = LOW;

    void setup() {
      pinMode(led_pin, OUTPUT);
      pinMode(interrupt_pin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interrupt_pin), sync_ISR, RISING);
    }

    void loop() {
      unsigned long loop_micros = micros();  // capture start of loop time
      if (loop_micros >= next_pulse) {
        // Schedule pulse
        digitalWrite(led_pin, HIGH);
        next_pulse += pulse_interval ;
        pulse_off = loop_micros + pulse_us; // schedule off time
        // PLL accounting
        count++;
        if (count_at_sync > 0) next_pulse++; // too fast: slow down
        else if (count_at_sync < 0) next_pulse--; // too slow: speed up
      }
      if (state == HIGH && loop_micros >= pulse_off) {
        state = LOW;
      }
      digitalWrite(led_pin, state);
    }

    void sync_ISR() { // called by 1pps interrupt
      count_at_sync = (count -= pps); // PLL accounting and record synchronization state
    }


body:
I am using Arduino UNO to Read 8-channel, 24-bits resolution Analog signals using ADS1299 Analog-fornt-end. ADS1299 use SPI interface to talk with Arduino. Currently, I can record the analog signal with arduino based on the SPI protocol and send the data via serial port to the PC.

The ADS1299 has 8 channels with 24-bits resolutions. The sampling rate can be defined from 250s/s to 16Ks/s. As you can see in the below code, when the data is ready I put the device in reading data mode and store 8-bits (1-byte) in each run and concatenate 3 bytes to make a full sample. I repeat these procedures to obtain the whole samples of all channels. At the end I have sent a sample of one channel to the serial port using serial.print command.

Here is my problem: If I want to increase the sampling rate of device to e.g 10 Ks/s the arduino fails to provide this sampling rate due to  delay produced by Serial.println command. Is is possible to store the data into a big array and then send the whole array via serial port?  Is it possible that other types of microcontroller such as ARM types handle this issue? Generally how it is possible to avoid the delay of serial print?

        #include <SPI.h>
        #define WAKEUP 0x02
        #define STANDBY 0x04
        #define RESET 0x06
        #define START 0x08
        #define STOP 0x0a
        #define RDATAC 0x10
        #define SDATAC 0x11
        #define RDATA 0x12
        #define TESTaa 0xaa
        #define TEST55 0x55

        #define CONFIG1 0x01
        #define CONFIG2 0x02
        #define CONFIG3 0x03
        #define CH1SET 0x05
        #define CH2SET 0x06
        #define CH3SET 0x07
        #define CH4SET 0x08
        #define CH5SET 0x09
        #define CH6SET 0x0A
        #define CH7SET 0x0B
        #define CH8SET 0x0C

          const int PIN_START = 7;
          const int IPIN_DRDY = 9;
          const int PIN_CS = 10;

          const int DOUT = 12;
          const int DIN = 11;
          const int PIN_SCLK = 13;
          const int PIN_RESET = 8;

          byte chSet;
          byte chSet2;
          boolean flag = false;
          long t0, t;

        void setup(){

          // You can use serial communication for debugging
          Serial.begin(2000000);
          Serial.flush();
          delayMicroseconds(100);
          // You have to set SPI communication according to datasheet
          SPI.setDataMode(SPI_MODE1);
          //SPI.setClockDivider(SPI_CLOCK_DIV16);
          SPI.setBitOrder(MSBFIRST);
          SPI.begin();

          pinMode(DOUT, OUTPUT);
          pinMode(PIN_SCLK, OUTPUT);
          pinMode(PIN_CS, OUTPUT);
          pinMode(PIN_START, OUTPUT);
          pinMode(IPIN_DRDY, INPUT);
          pinMode(PIN_RESET, OUTPUT);

          //reset communication, see datasheet
            digitalWrite(PIN_SCLK, LOW);
            digitalWrite(DIN, LOW);
            digitalWrite(PIN_CS, HIGH);

          digitalWrite(PIN_CS, LOW); //Low to communicated
          SPI.transfer(RESET);
          digitalWrite(PIN_CS, HIGH); //Low to communicated

          // Wait longer for TI chip to start
          delay(500);
          send_command(SDATAC);
          delay(10);
          chSet = read_byte(0x00);
          Serial.println("-- ID CHIP is:" + hex_to_char(chSet) );

          // Write Config 1 and 2: see datasheet page 47
          // Config 1: Bits 7 6 5 4 3 2 1 0 --- 1 DAISY_EN=1 CLK_EN=0 1 0 DR[2:0] (110-- 250 Sample/S)  --->   0b11010110
          // Config 2: Bits 7 6 5 4 3 2 1 0 ----  1 1 0 INT_CAL=1(Int/Ext test sig) 0 CAL_AMP=(calibration signal amplitude)
          // CAL_FREQ[1:0] (calibration signal frequency)  ----->  0b11010100

          // for normal operation write to config1 0x02, config2 0xA0. For test signal write 0xA3 to config2
          write_byte(CONFIG1, 0x96);   // Daisy chain Enabled: D6 , Daisy chain Disabled: 96
          delay(10);

          write_byte(CONFIG2, 0xD1);   // Test signal Enabled: D0   Test signal  Disabpled: C0
          delay(10);

          write_byte(CONFIG3, 0xE0);   // INT Reference Enabled: E0    else  INT Reference Disabled: 60

          delay(1000);
          //this part is just to check if you send and read correct data
          Serial.println("Check Configs");
          chSet = read_byte(CONFIG1);
          Serial.println("CONFIG1: Received " + hex_to_char(chSet) );
          chSet = read_byte(CONFIG2);
          Serial.println("CONFIG2: Received "  + hex_to_char(chSet) );
          chSet = read_byte(CONFIG3);
          Serial.println("CONFIG3: Received "  + hex_to_char(chSet) );

          //remember that ch1 is used for respiration! use channel 2 for ECG measurements

           // Ch1 Setting: Bits 7 6 5 4 3 2 1 0 ---  PDn(channel power mode) GAINn[2:0] (PGA gain-- 101:  12 110 : 24)
           //SRB2 (SRB2 connection) MUXn[2:0] (channel input selection: 000 : Normal electrode input , 101 : Test signal )

           /// Input Channel Shorted  ---> 0b00000001 0X01;   Test signal Activated ---> 0b00000101 0X05;
          delay(1000);

          write_byte(CH1SET, 0x05); //
          write_byte(CH2SET, 0x05); //
          write_byte(CH3SET, 0x05); //
          write_byte(CH4SET, 0x05); //
          write_byte(CH5SET, 0x05); //
          write_byte(CH6SET, 0x05); //
          write_byte(CH7SET, 0x05); //
          write_byte(CH8SET, 0x05); //

          Serial.println("Check Channel Settings");
          chSet = read_byte(CH1SET);
          Serial.println("Ch1: Received " + hex_to_char(chSet) );
          chSet = read_byte(CH2SET);
          Serial.println("Ch2: Received  " +   hex_to_char(chSet) );
          chSet = read_byte(CH7SET);
          Serial.println("Ch7: Received  " +   hex_to_char(chSet) );
          chSet = read_byte(CH8SET);
          Serial.println("Ch8: Received  " +   hex_to_char(chSet) );

          // Start communication, you can use RDATAC or RDATA according to datasheet
          send_command(RDATAC);
          digitalWrite(PIN_START, LOW);
          delay(150);
          send_command(START);
        //  digitalWrite(PIN_CS, LOW); //Low to communicated
        //  SPI.transfer(START);
        //  digitalWrite(PIN_CS, HIGH); //Low to communicated

        }

        boolean gActiveChan [2];
        int nChannels = 1;
        int gMaxChan=1;

        void loop(){

        // Based on the Page. 36 For the 8-channel ADS1299, the number of data outputs is
        //[(24 status bits + 24 bits × 8 channels) = 216 bits].

          delayMicroseconds(10);

             if(digitalRead(IPIN_DRDY) == LOW){
              t0 = micros();

                digitalWrite(PIN_CS, LOW);

                long output[9];
                long dataPacket;
                for(int i = 0; i<9; i++){
                    for(int j = 0; j<3; j++){
                        byte dataByte = SPI.transfer(0x00);
                        dataPacket = (dataPacket<<8) | dataByte;
                    }

                    output[i] = dataPacket;
                    dataPacket = 0;
                }

                digitalWrite(PIN_CS, HIGH);
                Serial.println(output[1]);

        // t = micros()-t0;  // calculate elapsed time
       // Serial.print(1000000/float(t));
        //Serial.println(" samples per second");
        //delay(200);

         }

                }

            String hex_to_char(int hex_in) {
          int precision = 2;
          char tmp[16];
          char format[128];
          sprintf(format, "0x%%.%dX", precision);
          sprintf(tmp, format, hex_in);
          //Serial.print(tmp);
          return(String(tmp));
        }

        // see datasheet 38
        int read_byte(int reg_addr){
          int out = 0;
          digitalWrite(PIN_CS, LOW);
          SPI.transfer(0x20 | reg_addr);
          delayMicroseconds(5);
          SPI.transfer(0x00);
          delayMicroseconds(5);
          out = SPI.transfer(0x00);
          delayMicroseconds(1);
          digitalWrite(PIN_CS, HIGH);

          return(out);
        }

        void send_command(uint8_t cmd) {
          digitalWrite(PIN_CS, LOW);
          delayMicroseconds(5);
          SPI.transfer(cmd);
          delayMicroseconds(10);
          digitalWrite(PIN_CS, HIGH);
        }

        //see page 38
        void write_byte(int reg_addr, int val_hex) {
          digitalWrite(PIN_CS, LOW);
          delayMicroseconds(5);
          SPI.transfer(0x40 | reg_addr);
          delayMicroseconds(5);
          SPI.transfer(0x00);
          delayMicroseconds(5);
          SPI.transfer(val_hex);
          delayMicroseconds(10);
          digitalWrite(PIN_CS, HIGH);

        }

title: Using Arduino to Record analog signals with SPI ADC + Sampling Rate Issue

Answers: 1

body:
Try changing the order of these:

      SPI.setDataMode(SPI_MODE1);
      //SPI.setClockDivider(SPI_CLOCK_DIV16);
      SPI.setBitOrder(MSBFIRST);
      SPI.begin();

I think SPI.begin() needs to be started before the other two calls.

Instead of digitalWrite to control the chip select, use Direct Port Manipulation, much faster.

Does the ADC support 8 MHz SPI clock? From 7.6 & 7.7 of the datasheet, I would say yes.
You can get rid of all the delayMicroseconds(5), (1), (10), as well, they are not doing anything for you.

"Unpack" this and just do 3 SPI.transfers in a row to read the data, doing it in a loop slows it down:

            for(int i = 0; i<9; i++){
                for(int j = 0; j<3; j++){
                    byte dataByte = SPI.transfer(0x00);
                    dataPacket = (dataPacket<<8) | dataByte;
                }

I would go so far as to do all 27 in a row even, then do the array manipulation/data combining when all 27 bytes are captured.


body:
I've done some extensive googling but haven't found any kind of proper documentation. Is it possible to use i2s with the built-in ADC on an esp8266 to sample audio?
And if so: any sample code on how to do so?

title: ESP8266 and Arduino, using i2s and the built in adc?

Answers: 0


body:
New to this site and wanted advice and sanity checking on my project design. I know there are similar questions to this but I couldn’t find one that was closely similar to mine.

I’m creating a device the uses two NEMA 17 stepper motors (https://www.omc-stepperonline.com/nema-17-stepper-motor-bipolar-l48mm-w-gear-raio-1001-planetary-gearbox-17hs19-1684s-pg100.html) with chunky 100:1 gearboxes in addition to using 1/16 microstepping. The end result of this is to achieve a stepper motor that turns very slowly (minutes per revolution).

Each motor is rated at 2.8V and 1.68A per phase (3.36A total since two phase) and I’m using an A4988 driver for each of them (https://www.amazon.co.uk/gp/product/B07FKXXJ41/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1) (note that these are Chinese versions where RCS = 0.1Ω). Since the A4988 drivers are limited to 1A without additional cooling, I’ve used the onboard potentiometer to reduce Vref to just below 0.9V to prevent overheating (using the equation Vref = 8 x Imax x RCS from Pololu).

This should mean that consequentially the torque output from each motor is reduced by a factor of 1/(3.36) = 0.3 (as torque α current) since each motor is only being supplied with 1A (which is not an issue due to the large gearing ratio giving a suitable output torque). I think 1/16th microstepping might also reduce the torque slightly, but I couldn’t find any conclusive sources that didn’t contradict each other on this.

This gives a power requirement of 2.8 x 1 = 2.8W per motor, hence 5.6W in total. So, I plan to use a power source that provides at least 3A (surplus on the 2A required by the drivers) and rated at a voltage of 12V-24V to run the stepper motors. I’m also aware that I need to make sure I power the drivers in parallel from this source, and not in series to reduce strain / overheating.

I’ve included two power sources I was thinking of using:

1: 24V, 4A, 96W Desktop Switching Power Supply (https://www.amazon.co.uk/DTK-Charger-90-240V-Switching-Transformers/dp/B07K85GJ54/ref=sr_1_1_sspa?crid=362Z7XFFLAYLL&keywords=24v+3a+dc+power+supply&qid=1565084176&s=electronics&sprefix=24V+3A+dC,electronics,124&sr=1-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFHM1hUTjRTOUhYVDcmZW5jcnlwdGVkSWQ9QTA5NzA5MzQzM09IT05IR1JITEpQJmVuY3J5cHRlZEFkSWQ9QTA0NjgyMTUyQjY0UEYzRFI5OVBFJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==)

2: 24V, 15A, 360W PSU Transformer Adaptor (https://www.amazon.co.uk/NEWSTYLE-Universal-Regulated-Switching-Transformer/dp/B0758BNMLH/ref=sr_1_3?keywords=PSU+24V&qid=1565084433&s=electronics&sr=1-3)

Overall question is: would either of these power supplies be suitable, I think the second might be a bit overkill but i'm not sure.

Here’s the circuit diagram for reference:
[![enter image description here][1]][1]

Apologies for the long post, just needed to get all the information out of my head. I’m curious to see if I’ve made any errors in my calculations / assumptions, so any help is greatly appreciated.

  [1]: https://i.stack.imgur.com/PTkzL.jpg

title: Powering two stepper motors with A4988 drivers

Answers: 1

body:
Both power supplies are suitable.

The actual 12V/24V current required is not comparable to what the driver current is set at, since the stepper motor coils do not have those 12V/24V across them.

My first 3D printer came with a 12V 5A power supply, which proved suitable for simultaneous use of four stepper drivers, the control board, a display, and the heater cartridge (40W).


body:
I am new to this micro controller thingie world so bare with me :)

**Let me describe a scenario first.**
Say I have a linux box for house automation embedded in a wall.
For security reasons is **the only active access** to the box the display mounted to the wall.

**Another access would be via network and ssh but ssh is disabled.**
Unfortunately does the web app sometimes crash and nothing goes. In the wake of that do I have to disassemble quite some stuff to get to the box and to revive it.

**My Idea:**
I can use a nfc or rfid sensor and hook it up to Arduino.
**Would it be possible to make Arduino log on to the linux box and fire up and shutdown ssh?**

I don't want to use Arduino Yun.
Is it achievable with an Arduino nano/Mega?

If not, which system would be your first choice to accomplish this task?

Thanks for your patience :)

title: Using Arduino as contact to the world for linux box if app crashes

Answers: 1

body:
I will put our comments together in an answer.

You are overthinking the security issue. In my opinion, using RFID to reset the system is a bigger security thread, than using ssh the correct way. Normal RFID chips are susceptible to spoofing (copying an existing chip). Also the intruder could remove the RFID module to directly access the communication lines (depending on how much you will have accessible of the extra hardware). Also you can of course use the Serial interface of an Arduino to execute shell commands on your machine. You need a program on the machine to read the input and execute the commands (Majenko mentioned `agetty` for this). But is that really the best way? Using an Arduino here is a very hardware-ry way of solving a software issue. It is overly complex to do things this way and there are better options.

Instead you should really just use ssh with key-based authentication (disable password authentication). You can limit the ssh daemon to the local network (though, if you don't have configured corresponding port forwarding in your router, it isn't reachable from the internet either way), or - if you really want the additional security - to one specific device in your network. With a normal ssh key (I think 2048 bit is the standard), brute forcing is not a viable option for intruders. If you keep your private key save, there is very very little chance, that an intruder can get past that. You can also save the private key only on an USB stick, which you only use for resetting the machine. Also you can limit the commands, that the ssh user can execute, to only the resetting (like only allowing rebooting).

Depending on your actual security needs, you can choose, how far you want to go. I personally would just use key-based ssh limited to the local network. That should be plenty enough security and would also give you the possibility to access the machine, that is running in your home easier.

---

Or, if you really don't want to open ssh for the machine, you can write a simple watchdog program, that can run on the machine. Since the webapp is failing, you can write a simple python program (or any other language you like), which is regularly loading the webapp (how exactly depends largely on the webapp and the exact type of failure - may be a simple HTTP GET request) to check, if it is still alive. If the liveliness test fails for a defined number of times (let's say 3), it will reboot the machine.

This method does not require any access to the machine, but you will have to develop the liveliness test. Writing the program is then really simple.

---

All that said, it is not a good sign, that the app fails that often. You didn't write, what app that is, and what exactly fails. Maybe you are able to fix that issue directly. Or the developer of the app can, so maybe raise an issue on his platform (where the project is hosted).


body:
I have a string formattedDate.
When I am trying to give sprintf(payload,"{\"timestamp\":\"%s\",\"temperature\":%f,\"humidity\":%f}",formattedDate,t,h);
Its not printing the date and time.

title: What is the format specifier for string in arduino

Answers: 0


body:
I have bought an arduino uno but when i plugged in the arduino to my laptop its not turned on (the built-in LED was off) and at the arduino IDE I wasnt able to change the port (the port button was unavalible)
what should I do for the arduino uno board to work?

title: Arduino Uno not turning on

Answers: 0


body:
### Setup:

* Arduino Mega 2560 w/ Wiznet W5500 Ethernet Sheild

* Using TP-Link TL-MR6400 LTE router to connect to internet over cellular connection in Uganda.

---
Using an HTTP Post with the following,
<!-- language-all: lang-cpp -->
```
client.println("POST /hook HTTP/1.1");
client.print("Host: "); client.println(server);
client.println("Accept: */*");
client.print("Content-Type: text/html;");
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
```

where PostData is a `String` and Ethernet2 is the library used.

This works just fine from the US to the same AWS server, or a [https://requestbin.com/][1] instance.

---

When testing from Uganda using a Raspberry Pi and curl it works fine.

```
$ curl -vs -d 'ABCDEFG' -H "User-Agent: Arduino/1.0"  -H "Content-Type: text/html" -H "Connection: close"   http://<server here>/hook
*   Trying <ip here>...
* TCP_NODELAY set
* Connected to <server here> (<ip here>) port 80 (#0)
> POST /tg HTTP/1.1
> Host: <server here>
> Accept: */*
> User-Agent: Arduino/1.0
> Content-Type: text/html
> Connection: close
> Content-Length: 7
>
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
< Date: Tue, 06 Aug 2019 21:06:49 GMT
< x-pd-status: sent to primary
< X-Powered-By: Express
< Content-Length: 16
< Connection: Close
<
* Curl_http_done: called premature == 0
* Closing connection 0
{"success":true}
```

---

I even tried an HTTP GET example from the Ethernet2 library,

[https://www.arduino.cc/en/Tutorial/WebClientRepeating][2]

It worked just fine in the US but in Uganda I get,

```
My IP address: 192.168.1.177

connecting...

connecting...

connecting...

```

I increased the time between requests here to 100 seconds where it is listening for the whole time inbetween.

It seems that `client.connect(server, 80)` is successful and the `client.print` messages go through but the message never reaches the server so there is no response. My AWS server does not recieve the request and this is the same for the requestbin instance. This behavior is mirrored in all my Arduino tests.

I thought the ISP might be blocking but the RPi can send nearly the same message. I thought maybe a timeout somewhere but I can not find where with my tests. I thought my message was too long but I reduced the size to only 10 characters with the same results.

---

Trying to figure out why the Arduino HTTP request cannot reach any webhooks from Uganda and how to fix it if possible. Different ISP, slower connection, cellular connection?

Any help would be appreciated.

  [1]: https://requestbin.com/
  [2]: https://www.arduino.cc/en/Tutorial/WebClientRepeating

title: Arduino HTTP Request Fails Slow Cellular Connection

Answers: 1

body:
**Buffering and flush()**

Many arduino libraries suffer of slow communication because the authors didn't use buffering. To not to send every small piece of data over a connection with overhead of protocol bytes use buffering. Data are collected until the buffer is full and then the collected data are send and the buffer is ready for next bytes. The flush() functions sends the buffer even if it is not full, but you do not have more data. (The flush() 'dilemma' was resolved and in Arduino core classes the flush() method is declared in Print class which is the Arduino standard interface for output streams.)

My StreamLib library offers a BufferedPrint class which wraps the target stream and buffers the data to be send over the target stream. Of course, do not forget to use flush() after last data printed.

----------

**HTTP data length**

It is common practice in Arduino sketches to not to send the Content-length header with POST requests. In most cases it is because when the HTTP headers are send, the size of data is not known. The WebServer then doesn't know if it received all the data and waits until the connection is closed or timeout is reached. It leads to long time until a Web Server sends the response to requesting Arduino sketch.

If the data can be prepared to a string in memory, fill the Content-length HTTP header.

If the data to be send as response or in POST request wouldn't fit into available memory, ChunkedPrint from my StreamLib can be used with HTTP chunked Transfer-Encoding. And ChunkedPrint is an extension of BufferedPrint so the Web Server handles your request without hesitating.


body:
I am trying to send measurements over UDP, but the function Udp.endPacket continuously fails.

I use an Arduino Uno WiFi rev 2, WiFiNINA library version 1.4.0 and WiFiNINA firmware version 1.2.1 which seems to be the latest available.

WiFi connection setup works, obtaining a correct IP address in the 192.168.3.0/24 network.

This is a snippet of my code:
<!-- language-all: lang-cpp -->
```
const char* udpDestIP = "192.168.3.126";
const int udpDestPort = 1844;
WiFiUDP Udp;

void loop() {
  // establish variables for distance result:
  long cm;

  // execute measurement
  cm = measureDistance();

  // check for false measurements and repeat if necessary
  if(minDist < cm && cm < maxDist) {
    Serial.print(cm);
    Serial.print(" cm");
    Serial.println();

    // Check WiFi connection and reconnect if necessary
    if (WiFi.status() != WL_CONNECTED) {
      connectToWifi();
    }

    // Send over UDP
    //if(!Udp.beginPacket("192.168.3.255", udpDestPort)) {
    if(!Udp.beginPacket(udpDestIP, udpDestPort)) {
      Serial.println("beginPacket fail");
    }
    String msg = "water_distance:";
    msg += cm;
    byte size = Udp.write(msg.c_str(), msg.length());
    if(DEBUG){
      Serial.print("Sending this message over UDP: ");
      Serial.println(msg);
      Serial.print("udp write: ");
      Serial.println(size);
    }
    if(!Udp.endPacket()) Serial.println("endPacket fail");

    delay(delayTime);
  }
}

```

Terminal output is as follows:
```
151 cm
Sending this message over UDP: water_distance:151
udp write: 18
endPacket fail
151 cm
Sending this message over UDP: water_distance:151
udp write: 18
endPacket fail
33 cm
Sending this message over UDP: water_distance:33
udp write: 17
endPacket fail
34 cm
Sending this message over UDP: water_distance:34
udp write: 17
endPacket fail
153 cm
Sending this message over UDP: water_distance:153
udp write: 18
endPacket fail

```

Which makes me conclude the beginPacket, and udp.write functions are executed correctly, but I see no reason why the endPacket function keeps failing. Does anyone have an idea? Thanks a lot.

title: Udp.endPacket fails

Answers: 1

body:
The Arduino Ethernet and WiFi library implementations require to specify the outgoing port with UDP.begin(port) before calling UDP.beginPacket().

But UDP.begin(port) starts listening for UDP messages on this port too, so it is not a clean API. Call UDP.end() to stop listening for incoming messages.


body:
Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"

In file included from C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.cpp:15:0:

C:\Users\Admin\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:29: fatal error: Adafruit_Sensor.h: No such file or directory

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

title: I am working on a thermometer and humidity why am i getting this error

Answers: 1

body:
This indicates your IDE is missing the "Adafruit Unified Sensor" library as outlined [here][1].

To install it, select "Tools" -> "Manage Libraries" and search for "Adafruit Unified Sensor". You can install the library by selecting it and pressing "Install".

  [1]: https://forum.arduino.cc/index.php?topic=471001.0


body:
I'm trying to find a way to detect blocks being placed on grid on a table. The table will have fixed places where you can place the blocks, but the user is allowed to place the blocks in any free slot. I would like to have an Arduino poll the slots on the table and tell me which blocks are placed where.

I'm going to design the blocks with magnetic connections on the top and bottom to create a circuit as soon as they are placed.

What kind of chips can I use so that the arduino can give me the topology of the blocks when placed?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/sozrl.png

title: Arduino detect order of objects

Answers: 1

body:
You need to track unique objects in an 8x8 grid of slots? How many unique objects?

If the total number of objects is 112 or less, you could give each one a unique I2C address.

You'd add 4 circular electrical contacts in a "bulls-eye" configuration on the top and bottom of each object so that all the I2C pins would connect regardless of orientation. All objects in the same stack would be connected together on that stack's I2C bus.

You'd have an 8x8 multiplexer to connect to the I2C bus for each of your 64 grid positions in turn, and poll that bus for each of the possible I2C addresses. (Send a ping for each address and look for `ACK`s.)

---
Alternately, you could give every object a unique weight, varied by a power-of-two amount. (first object weighs 1000 grams. Second weighs 1001 grams (1000+2^0)) third object weighs 1002 grams (1000+2^1). Fourth object weighs 1004 grams (1000+2^2). Etc.)

Then you'd put a scale on each pad. Weigh the objects, modulo 1000 grams. That result, in binary, would give you flags for every object on that pad.

---

Or 2 circular electrical contacts on the top and bottom of each object, with resistors that have unique power-of-two resistance on each one, as Juraj suggests in their comment. Measure the resistance and you can figure out which set of objects is present.

The math would be simpler if you rigged the objects so that they made a series circuit through all objects present (put a normally closed switch on the top that shorts the top contacts of that object through its resistor if there's no object on top of it. If there is an object, the switch would open, and the objects on top would close the circuit.)


body:
Is this timer set correctly for Arduino Mega? It should count exactly one second. And why when I print in serial monitor (seconds_passed++) is it incremented by 2 not by 1?

Full code on Pastebin: [LINK][1]

    noInterrupts();
    //set and initialize the TIMER1

    TCCR1A = 0; // set entire TCCR1A register to 0
    TCCR1B = 0; // set entire TCCR1B register to 0
    TCCR1B |= (1 << CS12);
    TIMSK1 |= (1 << TOIE1);
    TCNT1 = 3036;

    attachInterrupt(digitalPinToInterrupt(ignition_pin), ignitionSignal, CHANGE);
    interrupts();

    ISR(TIMER1_OVF_vect) {
      //TIMER1 overflow interrupt -- occurs every 1sec --
      instantSpeed();
      LPG_Consumption();
      LPG_injector_open_duration = 0;
      unleadedConsumption();
      unleadinj_Open_Duration = 0;
      seconds_passed++;
      vss_pulses = 0;
      TCNT1 = 3036;
    }

  [1]: https://pastebin.com/Efkx07WR

title: Arduino Mega TIMER1 one second interval

Answers: 1

body:
Your timer configuration is ok so far. Never the less I recommend using the `TIMER1_COMPA_vect` interrupt vector instead of `TIMER1_OVF_vect` which has the advantage of better readability (in my oppinion) and `TCNT1` doesn't have to be reset in the ISR (instead, OCR1A is just initialized with 62500 once in `setup()`). Therefore, TIMER0 has to run in CTC (clear timer on compare match) mode and `WGM12` has to be set in TCCR1B.

The reason why `seconds_passed` is incremented twice is because you `Serial.print(seconds_passed++)` in `instantSpeed()`. Printing on the serial interface is damn slow and using it in an ISR is a no-go!


body:
I am working on a project with a simple particulate matter sensor hooked up to an Arduino Uno. I'm using puTTY to log the sensor's output. My Arduino program converts the data to a numerical format, then prints it to the serial monitor every 30 to 31 seconds. I want to use puTTY to log this data to a file over a period of weeks. My problem now is that when I run it using puTTY, it stops after about 30-90 mins and "Fatal error: error reading from serial device" pops up. The wires connecting my sensor to the Arduino, and the USB cable connecting the Arduino to my computer all appear fine. Here is the code on the Arduino:
```arduino
int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;

void setup() {
  Serial.begin(9600);
  pinMode(8,INPUT);
  starttime = millis();
  Serial.print("Data is collected roughly every ");
  Serial.print(sampletime_ms/1000);
  Serial.println(" seconds.");
}

void loop() {
  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy+duration;
  if ((millis()-starttime) >= sampletime_ms)
  {
    ratio = lowpulseoccupancy/(sampletime_ms);
    concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;
    Serial.print("Concentration = ");
    Serial.print(concentration);
    Serial.print(" pcs/0.01cf at ");
    Serial.print(millis()/1000);
    Serial.println(" seconds.");
    lowpulseoccupancy = 0;
    starttime = millis();
  }
}
```
I'm using the shinyei PPD42 particulate matter sensor.
Can anyone tell me what's going on, and if there's any sort of workaround I can use? I don't necessarily need to use puTTY, I just need to log the serial output from my Arduino.
Thanks!

title: Difficulty getting Arduino data via puTTY

Answers: 0