text:
Increase sample rate in ESP32 board
For my final project on the university as a Systems Engineer, I'm working on a "electronic stethoscope", which is giving me a lot of headaches.
I bought a Adafruit Feather ESP32 Huzzah (https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/overview) which has a dual core processor that works around 240 MHz of speed, it has support of wireless communication with Bluetooth classic (which is the one I'm using) and also works with the I2S protocol.
That is the reason why I bought an I2S MEMS Microphone SPH0645 (https://www.adafruit.com/product/3421), which according with its documentation works under 50Hz-15KHz.
As a first approach, I thought that it would be enough, but I'm getting a very slow sample rate that is around 800 samples per second. With these values, I can't reproduce any sound with the expected quality.
On the other hand, since the ESP32 has not a high level library to interact with I2S such as ArduinoSound I had to create my own code based on the specification (https://esp-idf.readthedocs.io/en/v2.0/api/peripherals/i2s.html).
My code on the Arduino IDE looks like this:
#include "libraries/SmappioSound/SmappioSound.cpp"
#include "BluetoothSerial.h"

int *buffer;
BluetoothSerial serialBT;
int value = 0;
int framesRead = 0;

SmappioSound smappioSound(6835); //value for stabilization

void setup() {
  // put your setup code here, to run once:

  pinMode(DATA_PIN, INPUT); // Supuestamente necesario para que no haya ruido
  serialBT.begin("smappio_PCM");
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  smappioSound.begin(buffer);
}

void loop() {

  //gets the amount of bytes readed from the buffer.
  framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;

  for(int index = 0; index <= framesRead; index++)
  {

      value = smappioSound.getSampleValue(index);
      if(index % 2 == 0)
      {
          serialBT.print(String(value) + ",");
          Serial.println(value);
      }
  }
}

The SmappioSound.h library is where the interaction with I2S occurs.
The configuration for i2S is the following:
#pragma region // Sección de Configuración
  static const print_mode_t PRINT_MODE = BYTES;                                   // Tipo de impresión: BITS | BYTES | INTEGER | FULL_DETEAILED
  static const bool PRINT_BOTH_CHANNELS = false;                                    // Indica si imprime solo el "Canal 0" ó el "Canal 0" y el "Canal 1"
  static const int FRAMES_REQUESTED = 1;                                           // Parece relacionarse con la cantidad de buffers
  static const int TICKS_TO_WAIT = 0;                                            // Investigar
  static const i2s_bits_per_sample_t BITS_PER_SAMPLE = I2S_BITS_PER_SAMPLE_32BIT;   // Datasheet: 24. Ejemplo: 32.

  static const i2s_config_t SPH_CONFIG = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),                                            // El controlador es el Maestro y Recibe, el microfono es Esclavo y Transmite
    .sample_rate = 32000,                                                                           // Entre 32KHz y 64KHz (Datasheet)
    .bits_per_sample = BITS_PER_SAMPLE,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,                                                   // El formato que usa el micrófono. No se encontró el Datasheet
    .communication_format = (i2s_comm_format_t) I2S_COMM_FORMAT_PCM,    //(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB) // Investigar
    //MSB: most significant byte -> BIG ENDIAN
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,                                                       // High interrupt priority (investigar)
    .dma_buf_count = 2,                                                                            // Cantidad de buffers, 128 max.
    .dma_buf_len = 32 * 2                                                                           // Tamaño de cada buffer
  };

#pragma endregion Sección de Configuración

As you can see, I'm trying to get 32KHz as sample rate with 32 bit-depth (not working for 16, and 24 bits), and I'm setting 115200 baud-rate in the Arduino IDE.
On the other hand, I created a .NET Winforms application that is receiving the generated PCM values over bluetooth 4.0. After 1 second is giving me only 693 samples which is very few.

Can I reach at least 20KHz as sample rate with these hardware components? Do you see something wrong in my code?

Serial is slow. Very slow. You can't do audio over it like that.

Thanks Majenko. What hardware component can you recommend for streaming audio with high quality?

Usb with isochronous transfers.

I don't get it. Are you using Bluetooth or USB-UART serial as a transmission medium? Because you transmit the values on both channels.

I want to transfer only 1 channel. I just saw that I can use channel_format = I2S_CHANNEL_FMT_ONLY_LEFT to send only mono. I'm using Bluetooth as a transmission medium.

Here's a few tips on optimization.
  for(int index = 0; index <= framesRead; index++)
  {

      value = smappioSound.getSampleValue(index);
      if(index % 2 == 0)
      {
          serialBT.print(String(value) + ",");
          Serial.println(value);
      }
  }

Doing
          serialBT.print(String(value) + ",");
          Serial.println(value);

is very wasteful. First of all you're debug-outputting every value as an ASCII string to Serial, second you're doing the same thing over serialBT with an additional ,.
It's wasteful because:

your baud rate is extremely low (115200 on Serial)
converting every value to ASCII will induce an overhead

Your int value is 32 bits / 4 bytes which may take arbitrary values. Say the value is at its positive max at 0x7fffffff = 214748364. Then transmitting the ASCII string will take 9 bytes (10 bytes for largest negative value), sending the raw binary value will always take 4 bytes. Thus you should always send your samples in raw binary format, not converted to an ASCII String.
At a wanted sampling rate of 32KHz with 32-bit values, you'd need an effective bit rate of 32000*32 = 1,024,000 Bits/s. Your Serial on which you are also printing every 2nd value, is on 115,200 bit/s (and you'd still have to account for the UART overhead, aka start and stop bits for every 8 data bits!).
Depending on the quality of the USB-UART converter on your board (FTDI, CP2102: good, CH340: bad), you can actually get to over 1 megabaud. The ESP32's UART periphal will allow you to set whatever clock divider you want to divide the 80 MHz APB clock (source, chapter 13.3.2). ESP-IDF has the UART_BITRATE_MAX defined to 5,000,000 (source), and since Arduino-ESP32 derives from ESP-IDF, that should be possible there, too.
As I said, the USB-UART adapter between the ESP32 and your PC is critical. It has to support such a high speeds with a sufficiently large TX/RX buffer. The max baud rate of a CP2101 is 921600 (source), an FT232RL (source) up to 3 megabaud.
In general you don't want to give your sample values to the peripheral value-wise. Both your Serial and your BluetoothSerial have the possibility to enqueue a whole buffer at once (source). I don't know the real underlying implementation where the final samples will be stored (and held stable for a while) but you might just be able to do
framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;
serialBT.write((uint8_t*) buffer, framesRead * sizeof(int32_t));

to send the whole buffer at once. You'd also have to check how to handle or set the transmission speed on the bluetooth peripheral. I don't know much about the ESP32's BT / BLE radio to answer that.
Speed on a UART adapter could further be advanced to a non-blocking DMA backed variant. Since both I2S and the UART periphal support DMA transfers. Thus, the maximum transfer speed would be reachable.
Another posisbility would be to change the transission medium. You could have your ESP32 join a WiFi network and transmit its audio buffers via UDP or TCP to some server listening on the PC. I think however Bluetooth and UART (with the right tweaks) would also be possible.

Thanks a lot Maximilian, I will check all the details of your response and I'll let you know how it goes.

The CH340 hardware can send with baud rates up to 3 MBaud (unfortunately with 6 stop bits). For details please read my CH341 baud rate calculation HOWTO at https://github.com/nospam2000/ch341-baudrate-calculation


text:
Arduino remote-controlled car stops after a few seconds
I am making a remotely controlled car for a project at Uni. The car is made from an Arduino Uno, a 2 motor driver and a Bluetooth transceiver. I have written some code for it, but it randomly stops after 2 or 3 loops.
Here is my code:
#include "SoftwareSerial.h"

typedef unsigned char u8;

typedef struct {
  u8 right;
  u8 left;
} speed;

SoftwareSerial bluetooth(4, 2);

const u8 RIGHT_MOTOR_PIN1 = 3;
const u8 RIGHT_MOTOR_PIN2 = 5;
const u8 LEFT_MOTOR_PIN1 = 6;
const u8 LEFT_MOTOR_PIN2 = 9;

const u8 MAX_SPEED = 0xFFU;
const u8 HALF_SPEED = MAX_SPEED / 2;
const u8 NO_SPEED = 0x0U;

static u8 command = 0U;
static speed potentialSpeed;
static speed actualSpeed;

void setup() {
  bluetooth.begin(115200);
  while (0U != bluetooth.available()) bluetooth.read();
  potentialSpeed.right = MAX_SPEED;
  potentialSpeed.left = MAX_SPEED;
  actualSpeed.right = NO_SPEED;
  actualSpeed.left = NO_SPEED;
}

void loop() {
  readCommand();
  {
    if (clockwise(command)) {
      if (0U == (command & 0xFEU)) {
        actualSpeed.right = - MAX_SPEED;
        actualSpeed.left = + MAX_SPEED;
      }
    } else if (counterclockwise(command)) {
      if (0U == (command & 0xFDU)) {
        actualSpeed.right = + MAX_SPEED;
        actualSpeed.left = - MAX_SPEED;
      }
    } else {
      if (right(command)) {
        potentialSpeed.right = HALF_SPEED;
      }
      if (left(command)) {
        potentialSpeed.left = HALF_SPEED;
      }
      if (forward(command)) {
        if (!backward(command)) {
          actualSpeed.right = + potentialSpeed.right;
          actualSpeed.left = + potentialSpeed.left;
        }
      } else if (backward(command)) {
        actualSpeed.right = - potentialSpeed.right;
        actualSpeed.left = - potentialSpeed.left;
      }
    }
    if (0U == command) {
      potentialSpeed.right = MAX_SPEED;
      potentialSpeed.left = MAX_SPEED;
      actualSpeed.right = NO_SPEED;
      actualSpeed.left = NO_SPEED;
    }
  }
  runAt(actualSpeed);
  delay(95);
}

void readCommand(void) {
  command = 0U;
  if (1U == bluetooth.available())
    command = bluetooth.read();
}

inline boolean clockwise(u8 command) {
  return (boolean)((command >> 0U) & 1U);
}
inline boolean counterclockwise(u8 command) {
  return (boolean)((command >> 1U) & 1U);
}
inline boolean right(u8 command) {
  return (boolean)((command >> 2U) & 1U);
}
inline boolean left(u8 command) {
  return (boolean)((command >> 3U) & 1U);
}
inline boolean forward(u8 command) {
  return (boolean)((command >> 4U) & 1U);
}
inline boolean backward(u8 command) {
  return (boolean)((command >> 5U) & 1U);
}

void runAt(speed Speed) {
  if (Speed.right > 0U) {
    analogWrite(RIGHT_MOTOR_PIN1, 0U);
    analogWrite(RIGHT_MOTOR_PIN2, Speed.right);
  } else {
    analogWrite(RIGHT_MOTOR_PIN1, (-(Speed.right)));
    analogWrite(RIGHT_MOTOR_PIN2, 0U);
  }
  if (Speed.left > 0U) {
    analogWrite(LEFT_MOTOR_PIN1, 0U);
    analogWrite(LEFT_MOTOR_PIN2, Speed.left);
  }
  else {
    analogWrite(LEFT_MOTOR_PIN1, (-(Speed.left)));
    analogWrite(LEFT_MOTOR_PIN2, 0U);
  }
}

Could you please help me find the cause?
Also, I am unable to make it go backwards. Can that be related?

replace  if (1U == bluetooth.available()) command = bluetooth.read(); with a fixed command command = turn_left .... see if it keeps doing it

SoftwareSerial speed is limited. use 9600 or 19200 baud

have you tried to debug the serial communication of what kind of command you are getting from the Bluetooth module? you might get a wrong baud or the software is not sending correct data

I have the same problem. Here is my code: #include <Servo.h> #include <AFMotor.h> #include <SoftwareSerial.h> // TX RX software library for bluetooth Servo myservo; // create servo object to control a servo // a maximum of eight servo objects can be created AF_DCMotor motor1(1, MOTOR12_1KHZ ); //create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency int state = '0'; int PosRight = 45; int PosLeft = 135; int PosF = 90; int pos = 90; int Speed = 150; void setup() { Serial.begin(9600); myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() {

The problem was that the bluetooth module would receive bytes faster than the SoftwareSerial was able to read, so bluetooth.available() would return more than 1U after a couple of loops. This was fixed by changing the following:
void readCommand(void) {
  command = 0U;
  if (bluetooth.available()) {
    while(bluetooth.available() > 1U)
      bluetooth.read();
    command = bluetooth.read();
  }
}

The 'make-it-run-backwards' problem was also solved, but was unrelated.

source: Stack Exchange

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

sort: votes


text:
Simulating a real time clock module with software
I am building a clock with an Arduino.
Most clocks have a RTC module or some kind of RTC chip in order to get the time. I do not.
How do i replace this chip with software? Is there a C/C++ library equivalent to the Java library  java.util.date?
Can I run a Java program instead of a C program on my Arduino so I can use this Java library? I only know Java and have little experience with C/C++. I have looked into ways to program this clock in Java which I have had success with, but this is only in my computer, not in the Arduino.

you have to do some research before posting a question .... i suspect that you have not bothered to do anything before posting your question because a web search for arduino timekeeping returns good info

Can i run a java program instead of a c program on my arduino so i can use this java library? Huh? How does switching to the Java language solve the problem on how to get the time? On a PC, your PC would get the time over NTP via an internet connection. The Java library just gets that already stored value. It doesn't get the time for the pure reason it's now written in Java instead of C++. You can use the same mechanism however -- either use a network connection of some sort (e.g. WiFI) and get the time via an NTP / SNTP client, or program the time once and store it in an RTC peripheral.

you did not answer the comments in your previous question about this https://arduino.stackexchange.com/questions/53108/arduino-clock-project

Possible duplicate of arduino clock project

Your question has been flagged for quality. Please see How do I ask a good question about the Arduino?

Explain how exactly do you expect this software simulation to work. E.g., do you want the clock to always start at a predefined time after a reset?

how do i replace [an RTC] chip with software?

You can't. An RTC is made of basically two things:

a carefully trimmed crystal oscillator that has a very stable and well
calibrated frequency
some logic to count the oscillations and convert that to time and
date.

The logic can be easily replaced by software, but the crystal cannot.
Any “pure software” solution you may find ultimately relies on counting
cycles of the system clock (the signal that clocks the whole
microcontroller). On most Arduinos, including the Uno, the system clock
is based on a ceramic resonator. These are usually specified with
0.5% frequency tolerance, and they typically have a frequency offset of
about ±0.1%. That's a drift of ±44 minutes per month!
You can get better accuracy by calibrating your Arduino's clock, and
correcting by software the frequency offset you measure. However, the
frequency is not only off, it is also quite unstable, and very sensitive
to temperature variations. So even with calibration you end up with a
clock that is ridiculously bad compared with the cheapest quartz watch.

is there a c++ library equivalent to the java library java.util.date?

I don't know Java, but there are C++ libraries available for managing
time. For example, you could initialize Paul Stoffregen's TimeLib as
follows:
setTime(hr,min,sec,day,mnth,yr);  // set initial time
setSyncInterval(-1);  // pretend we don't need to resync

and then periodically query the time with now(). That should be all
you need to build a “proof of concept” of your clock: it will tell you
the time, but with an awfully bad long-term accuracy.
Note that, once you add an RTC or another good time source, you can add
a “time provider” to that library, keep the rest of your code unchanged,
and benefit from the accuracy of your new time source.

Can i run a java program instead of a c program on my arduino [...]?

No, you can't. A Java runtime will never fit in your Arduino.

The resonator can be readily replaced with an actual 16 MHz crystal.  Some older / kit boards already work that way, as do the arduino on breadboard instructions on the arduino site.  The main disadvantage then is power consumption - but your basic Arduino project runs at full speed drawing full power all the time anyway.  For the more advanced, activating the clock divider can minimize the amount of circuitry that runs at 16 MHz, peripherals can be disabled, and the processor core itself can be suspended leaving just a hardware timer counting ticks.

Having looked at you other question it seems you are trying to run before you can walk.  You may be a good java programmer, but you need to get your head around C++ before you go all in and build a clock.
To answer this question, yes there are ways to get software to keep time, but when you power it up, how do you know what the time is?  This is where having a RTC will help, there are plenty of bare ICs out there and even ones with libraries.
If you had a network then you could grab the header data from the network packets, but you are running this on a Mega, which seems an odd choice for something as simple as a network time clock, surly a nano would do, or an ESP8266.
These links will help you, but personally I think you need to break the problem down into smaller chunks.
https://www.arduino.cc/reference/en/
https://playground.arduino.cc/Code/Time

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


text:
How to make I2C work on RS485?
I'm trying to optimize the communication (minimize wires) on a project where I can control a motor and toggle some 230V devices by using RS485 and I2C.
On this project, I'm using an Arduino (Mega) for the control panel (buttons, potmeters, LED segment display (I2C) etc.).
I'm using the RS485 protocol (Modbus RTU) to control an inverter by using a MAX485 TTL converter. Now I also have a relay board (8 channel) to be able to toggle some lightning and sound devices. Both the inverter and the relay board, as well as the power supply, are located in another box, which I call the power box. Between the control panel and the power box will be a cable.
[Control Panel (with arduino mega)] <--cable--> [power box (with inverter, 8 channel relay board and 230V devices)]
I've got the following requirements:

The cable should have a minimum amount of wires (5V, Ground, 485+(A) and 485-(B) for sure)
The total length of the cable varies from 1 to 3 meters.
The signal should be reliable.

Now the relay board uses 8 channels. I've bought an I2C expander (PCF8574) to minimize that to 2 wires (SDA, SCL).
I'm thinking of using the existing 485 lines to control the inverter AND the relay board. So no additional wires are required. But theoretically I can't get it to work. So before I try to invent it.

Can I do I2C communication over the RS485 as well somehow by putting another converter?
If you recommand to just go with 6 wires (power, RS485 and I2C), how reliable is my I2C line going to be on 3 meters? What pull-up values do you recommand? (24AWG wire in mind, but also using a close-by LED segment display, so 2 I2C devices on different distances). I've read posts saying:

The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz I2C bus.

Or can I use some other protocol/trick? Either minimalize wires, or boost signal by a I2C buffer? (recommendations?)

I2C needs two signals referenced to ground and RS485 needs a twisted pair.  This is very different.  By the time you convert the signal you might have found it would have been easier to just throw away your I2C peripherals and buy new RS485 peripherals.  I2C, SPI and other similar protocols were meant to reduce the pins on peripheral chips normally located on the same PCB.  They are not meant to go long distances.  You may find you need to drop the speed on the I2C bus.  And to debug problems you likely will have to use an oscilloscope.

add a small arduino as a RS485 to I2C converter or connect the relays to it

An oscilloscope is too expensive for me. How badly is it to not use a twisted pair for rs485 on a length of 3 meters?

And what if i did use twisted pair, can the 5v and gnd line be used on a twisted pair? Or will that create a voltage drop?

Twisted pair is designed to work over longer distances. Because it is a twisted pair, any noise picked up by one wire is canceled out at the far end by the complimentary noise picked up by the other wire. That is why it is used. The reason it is not always used: Because twisted pair requires extra hardware to transmit it and extra hardware to receive it.  Adding to the cost of the product. You can not simply connect a 5v digital signal and ground to a twisted pair. To take advantage of the noise immunity you need to drive the twisted pair with equal but opposite voltages. Like USB or Ethernet.

To answer your previous comment, RS485 is supposed to use twisted pair.  If you do not, then the individual wires of the pair may not pick up the same but opposite amounts of noise.  So there may be noise at the termination (far end).  Twisted pair is easy to get and is everywhere thanks to the phone company and Ethernet cable.  Both types of cables are normally twisted pair.  And you can always use your own wire and twisted them together your self.

The oscilloscope was to check on how bad the I2C signal looked after several meters of cable.  To try different terminating resistors.  To see what might be interfering w/the signal (light dimmers, motors, fans, relays...).  Not to check on the RS485 signal.

I have to use the same cable for my power and for the rs485. So i guess twisted pair it is. The power can't be transformed to -5v. So what are the disadvabtages of 5v and 0v on a twsited pair then? And i can't twist wires myself as it should be 1 cable containing the wires. I know what you meant with the oscilloscope.

I2C and RS485 are such vastly different protocols with such vastly different signalling needs that they cannot share the same cables.
Further, I2C is not designed for connecting with long cables - it's meant for use between chips on a PCB.
The simplest "Arduino" solution would be to create a new RS485 device on your RS485 bus using another MAX485 and a small Arduino (micro, nano, etc) that responds to MODBUS RTU instructions and controls the relay board for you.

I was afraid so. But when i think about 'simple maintainence' i actually want to avoid another micro controller with software. The best solution would be just a swap of standard components. Anything you can think of?

I know of nothing. Ask Google for a MODBUS RTU compatible relay controller. Be prepared to pay lots.

Mhm, true. Industrial.. Always expensive. What about keep using i2c with a buffer/booster? I also read some posts saying they can have up to 20 meters with a slow rate and the correct resistors and such?

You're starting to enter the hacky and unreliable (and probably not working at all) area. If you're going to hack something together at least do it within the framework of your existing protocol. Just use an Arduino at the remote end like I suggested. That's by far the best low-cost option. Anything hacked together to try and force two protocols down one set of wires will be far worse in the long run, if it's even possible.

I meant when using 6 wires (own pair for i2c) but doing it on a longer distance. But yes, probably right, better use another microcontroller on the 485 bus then. I can lose the i2c completely.


text:
attachInterrupt for mega 2560 not triggering
I recently bought a mega 2560 to toy around with as a hobby. It's pretty fun so far, but I've recently gotten stuck while trying to use attachInterrupt with a button. I'm using the CHANGE mode, and have read the documentation pretty thoroughly ( I think ).
I've looked up multiple questions and tried to fix my setup and I still can't seem to make it work.
Here's my code:
int buttonPin = 18;
int ledPin1 = 11;
int ledPin2 = 9;
int ledPin3 = 5;

int value = 0;

void setup() {
  //declare inputs and outputs
  pinMode(buttonPin,INPUT_PULLUP);
  pinMode(ledPin1,OUTPUT);
  pinMode(ledPin2,OUTPUT);
  pinMode(ledPin3,OUTPUT);

  //create interrupt for button
  attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

  Serial.begin(9600);
}

void loop(){
  if(value == 0){ digitalWrite(ledPin1,HIGH);}
  else{ digitalWrite(ledPin1,LOW); }

  if(value == 1){ digitalWrite(ledPin2,HIGH);}
  else{ digitalWrite(ledPin2,LOW); }

  if(value == 2){ digitalWrite(ledPin3,HIGH);}
  else{ digitalWrite(ledPin3,LOW); }

  delay(500);
  Serial.print(digitalRead(buttonPin));

}

//count occurs when button is pressed
void count(){
  //incremement a counter
  value++;
  //reset counter from 3 to 0
  if(value >= 2){ value = 0; }
}

It's a pretty simple sketch. I'd attach a picture of my current setup but I don't really think It's needed. The button is indeed working as I'm debugging using serial.print().
If not clear, the objective of the sketch is to change the LED lit when the button is pressed. Currently, the variable value is stuck at 0.

//create interrupt for button
attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

The code does not match the comment.
attachInterrupt(digitalPinToInterrupt(buttonPin),count,CHANGE);

Thanks. This doesn't quite make sense to me though, the documentation for attachInterrupt says I should use 5 instead of 18... https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I'd like to upvote your answer but I'm not high enough in reputation

It says if you are going to use the interrupt number instead, that you should use 5. But then you wouldn't use digitalPinToInterrupt(), since that is already the interrupt number. It also recommends that you don't use the interrupt number.

Silly mistake for me to make. Thanks again for the help!


text:
Uploading to a CH340 "Nano" board using a Mac with Osx High Sierra
I recently purchased some inexpensive Nano boards, but they give an error signal and won't upload from my Mac with OSX High Sierra...  I am able to upload to Unos and Megas without issues.  I am selecting the correct board and the Atmega 328P and the dev/cu.bluetooth-incoming-port.I have also installed the CH341SER_MAC drivers using the H34X_INSTALL_V1.3 pkg. The error msg is as follows:  Can you help???
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/sketch/Blink.ino.cpp.o" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/core/core.a" "-L/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522" -lm
"/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.eep"
"/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex"
Sketch uses 948 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.Bluetooth-Incoming-Port -b57600 -D -Uflash:w:/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/daniellecomte/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.Bluetooth-Incoming-Port
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC
Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC

"Bluetooth-Incoming-Port" is not a valid port selection for an Arduino.  If you think your board has a CH341, then it is not an Arduino Nano and you should not use that tag, but rather the clones one. Conversely, if it is an Arduino, you don't want to install the notorious CH341 drivers on your system since they have no relevance to an actual Arduino. Even if needed and you decide you are willing to allow it on your system, the CH341 driver must not be in your Arduino libraries folder - it is (or at least purports to be) a system driver, it is not in any way shape or form an Arduino library.

Chris...  I don't decide how the WCH  Ch 340G drivers install themselves...  I simply click to install and follow through...  I restart my computer as they say..  but that doesn't work???

Sorry, but no.  The only way the CH340G drivers got in your Arduino folder is if you put them there (for example when you downloaded them) or if you followed some horribly mistaken unofficial instruction or used some mysterious unofficial driver package put together by someone with no idea at all what they are doing.  As yet it's unclear if the CH340 drivers are even appropriate for your board - if they are, you must remove the improper arduino-nano tag.

Hello Chris...  I gather that you prefer Arduino brand Nanos...  I'm just trying to use a half dozen Nanos that I bought on line...  they use a WCH CH340G chip, and I have run an install app to download and install the drivers...  but it's not working...  I might have the wrong type of cable which looks much thinner than the Arduino Uno cable...   Doesn't the install app know where to install the drivers???  Should I delete drivers that already exist in my Arduino library files...  I'm not sure exactly what you are suggesting that I do?   What are the exact steps to take to make this work???

The problem is that when you FALSELY state a problem as pertaining to an Arduino Nano by mis-tagging, that in fact only happens with a board using DIFFERENT PARTS NOT PRESENT IN ANY ARDUINO PRODUCT you merely confuse the issue and lessen the chance both that you will find a solution for your board, and that those who actually have Arduino products will find a solution for theirs.

As already explained, the Blueooth port is not a valid port selection.  You need to select a valid port entry.  If one is not present, you need to figure out why.

Chis... get ahold of yourself...  I'm not falsely stating anything...  Arduino itself allows other companies to make Nanos, Unos and Megas, and gives them the use of the code and the IDE...   most people use less expensive boards...

Arduino very specifically and emphatically does not allow unauthorized parties to label their products Arduino.  When your problem stems from the difference between your board and an actual Arduino, falsely labelling it an Arduino Nano by misusing that tag is indeed making a counterproductively false statement.  There is help for CH340 boards available here - in fact there are many topics on that subject.  But to get help, you have to ask about what you have, and not the board that you do not have.

And for the third time, "Bluetooth incoming port" is not a valid selection - you will get absolutely nowhere until you choose a valid port.

If your clones come with a CH340G-chip you might proceed as follows:
Download the latest driver with Hi Sierra compatibility here: Select Driver version 1.4 !!
Install the driver by double clicking the downloaded file - the installation will stop, issuing an error message as it is an unsigned driver - but if you downloaded the driver via the GitHub link, it is ok. So open Tools, Security and you will be asked by OS X's security system if you want to install the driver anyway - YES!
After restarting your Mac connect your Nano clone and start a copy of the Arduino IDE. Assuming you got version 1.8.5: under Tools/Port you should see something like /dev/cu.wchusbserialXXX - select this port. Now update your board manager, close and restart the IDE again. Under Tools select  "Board: Arduino Nano" and "Processor: ATmega 328P (Old Bootloader)".
Now you should be ready to upload your sketch.
Background information:
Since January 2018 all original Nanos come with the Optiplex bootloader (which is also incorporated in other Arduinos like the Uno. Clones will most likely have the old bootloader pre-loaded, that's why the Processor selection must be set to ".... (Old Bootloader)".
Hope that helps to get along.

Wow, THANKYOU. This completely resolved my uploading problems with: OS X Mojave; clone Nano; CH340/341 drivers installed via https://learn.sparkfun.com/tutorials/how-to-install-ch340-drivers/all - until I switched to OLD BOOTLOADER, my uploads would fail with "not in sync" because avrdude was apparently getting confused by the startup serial messages from my running code.


text:
Wireless Communication with NRF24L01+
I have decided to use NRF24L01+’s for my Arduino project for wireless communication. I am using the RF24 library by TMRh20 to talk back and forth.
Github Link: https://github.com/nRF24/RF24
I want to be able to send and receive data as fast as possible between the remote, and the receiver. After reading through the library I was able to create a some simple code that allowed the remote to transmit ~600 32-byte messages a second and the receiver was able to read ~490 messages a second.
Transmitter Loop Code:
if (radio.available())
  { radio.read( &myData, sizeof(myData) ); }
Receiver Loop Code:
radio.write( &myData, sizeof(myData), 1);
With this code however, the remote control cannot receive telemetry data back from the receiver. It is only a one way communication with no acknowledgments.
I have a few questions about wireless communication with the NRF24L01+. First, what is an acknowledgement? I understand it is a way for the transmitter to know that the receiver got the message, but what is being sent in the acknowledgment?
What is the difference between commands such as radio.write, radio.writefast, radio.startwrite, and radio.startwritefast. The RF24.h file has explnations of these commands but their desrciption does not make too much sense to me.
After doing some research, I found that to write, I must stop listening, write the message, and then start listening again for messages. The issue with this code is that the NRF is never listening long enough to receive a message (unless I add in a delay where it stays in RX mode). Is there anyway to keep a reading pipe open while writing and then pick it up from the FIFO when I am ready to read?
It seems that it is possible to write an ACK Payload, and this allows the NRF to transmit a message without leaving RX mode. Is this a possibility, and what is an ACK Payload?
What is the best practice for achieving the fastest speed two-way communication. Is it common practice to have two NRF’s and have one dedicated to listening and one dedicated to writing on each Arduino? Is there a good way to achieve high speed two-way communication rates with a single NRF?

I’d suggest reading the data sheet for the NRF24. Have a good look at the state diagram in it. The ACK is there to acknowledge that the packet was received, and not lost due to interference or weak signal. You can indeed send some data along with the ACK packet. To increase speed; the NRF has three speeds. Set it to the highest value. Also see which channel works the best, so you have the least number of lost packets. You can’t send and receive at the same time. Write will wait for the message to be send, before returning. WriteStart will not block, so you can run code while it is sending.

I second reading the data sheet.  Be prepared to use SPI commands and write directly into the nRF24L01+ registers.  You can do that in void setup after the rest of your radio setup.

I really reccomend you to read the documentation of the nRF24L01+ from nordicsemi. It describes its capabilities and modes of operation in depth.

firstly, the radio.write command is used for checking for the acknowledgement from the RX after the FIFOs are full for a single write. But radio.writefast will not wait for the acknowledgement from the RX and would continuously transmit the payload for a single write. Similarly for radio.startwrite and
radio.startwritefast commands.
Coming to the keeping the NRF in listening mode, even I haven't tried it before so I cannot suggest an exact solution for this problem. But as far as I know,  you can go for writestart command to keep the reading pipes open while you are sending. But I would personally suggest you to confirm this from datasheet again before experimenting.
For ACK payload, it depends upon the master unit controlling the SPI communication with the NRF chip and thus, by maintaining a mutual understanding between the RX and TX units, you can define the payload for acknowledgement signal as well.
Coming to best speed possibility, To increase speed, NRF has three speeds from which you can select the highest value available. Also see which pipe/channel works the best for you so that you can achieve the least number of lost packets.


text:
Set avrdude transfer baud rate in Arduino IDE
I just got an Arduino nano (from arduino.cc, not a knock-off), and have issues uploading sketches. It refuses to upload, with the error message "programmer is not responding".
Some searching led to an incorrect transfer baud rate. Indeed, the IDE (1.8.5) output before uploading displays "overriding baud rate: 57600", and the command line has a -b57600 argument. By copying this command in a terminal and removing this parameter, the upload works. It also works with -b115200. All other values I tried do not work.
Is there a way to configure the IDE to use the correct baud rate ? I know I could use the command line, but that's not very practical, I would prefer to keep the Integrated part of the IDE :).

Update the boards package for the AVR hardware. That will give you new options in the tools menu.
Then you should just select the right CPU variant.

From top to bottom those are 115200, 57600 and 19200 baud.


text:
My "avoid car" can't move straight

I use 2 gearbox motors with 2 wheels .. but if I try to run it, he can not walk straight. he always moves slightly to the right or to the left.
How i fix it ?

well you have posted no code, no schematics, no real information, so I guess we are to guess at how you have it all configured?  I would guess you are using PWM output to  control how fast the motors are going. So you should increase or decrease one to adjust the speed

I've tried it, do I need to use a "encoder motor" ?

What were the results when you tried it?  Did it work but you were not able to find the correct balance between the motors?  Encoders will help ensure they are spinning at the same rate yes, but other factors could still make the car turn slightly.

What, exactly, did you try, and what happened? Please show more details about how your car behaves, what you changed, whether the car's behavior changed at all, etc. There just isn't enough information here to offer you much more than guesses.

swap the motor wires just to make sure that the problem is the motor (it should still turn the same direction .... if the direction changes then it is the driver or the software

Likely the two gearbox motors you have are running at slightly different speeds for the same voltage. This is probably within normal tolerances, given that you say it moves slightly to the right or left.
You can use PWM-capable pins for motor control so you can adjust how fast the motors turn. If you do this, you have a couple of paths you can take:
You can, through trial-and-error, lower the PWM value (analogWrite(pin, speed)) for the faster-turning motor so that they both turn at the same speed.
or
You can find some way to detect the actual rotational speed of each motor and do the calibration in real-time on the Arduino. This might mean adding new sensors such as rotary encoders (mechanical or optical), or light-break sensors, etc.

I will try it again , to find the same speed with PWM. But if that not work , what module can i use to the rotary encoder ?

To use the rotary encoder solution gets much more complex. You have to find a rotary encoder that can fit onto the same shaft as your motor or wheel, or obtain a motor/gearbox that has a built-in encoder.


text:
USB host shield help

Hello, I apologise for being such a noob but can someone help with this.
I am having trouble working with this. When I insert the arduino's pins into my new usb host shield , there is no indication light and when I plugged my Xbox receiver into the shield it does not turn on as it would with my desktop. Any thoughts? Please post below

We need more information. See https://arduino.stackexchange.com/help/how-to-ask E.g. What have you tried? Do other devices work? Can your program access the shield at all? What makes you think it should light up?

Posting the clear photo is helpful because it shows the USB host board has the following problem.

Thank you very much, google wasn't producing many results. I guess budget-chinese parts are a bit dodgy.

Please include the relevant information in your answer. Once the link breaks, there will be nothing in your post to give readers even a slightest hint about the problem.


text:
currentbuttonstatus
I'm trying to use momentary push buttons to switch bi color LED between RED and GREEN. I've got one working, but when I try to adapt the code for more buttons, it doesn't work. I'm just changing the buttonnumbers (which are defined).
It compiles and uploads without error.
void loop() {
  byte currentButton1Status = digitalRead(button1);
  if (currentButton1Status == button1Status)
    lastEqualButtonTime = millis();
  else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
  {
    lastEqualButtonTime = millis();
    button1Status = currentButton1Status;

    if (button1Status == LOW) {
      digitalWrite(17, !digitalRead(17));
      digitalWrite(16, !digitalRead(16));
    }
  }

  byte currentButton2Status = digitalRead(button2);
  if (currentButton2Status == button2Status)
    lastEqualButtonTime = millis();
  else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
  {
    lastEqualButtonTime = millis();
    button2Status = currentButton2Status;

    if (button2Status == LOW) {
      digitalWrite(15, !digitalRead(15));
      digitalWrite(14, !digitalRead(14));
    }
  }
}

please post the complete code .... the way it is right now, there are a few definitions missing

You might want to look into using a debounce library  e.g. https://github.com/thomasfredericks/Bounce2

it doesn't work is not a good problem description

Use serial print to debug...

@chrisl there's nothing more to it. If I have the "byte currentButton...." just for button one, it works. If I use it the way I've posted above everything compiles and uploads ok, but when I press any of the two buttons, nothing happens.

@jsotola Everything is defined and I didn't want to bother you guys with other stuff that didn't have to do anything with this problem.

@user31208, you posted a partial program, so there is no way to confirm that the code compiles, and there is no way to pinpoint the failure

They can't all use the same variable, lastEqualButtonTime, to keep up with debouncing.

You've only said "... it doesn't work" which doesn't give much to go on, but the first thing I see that might contribute it not working as (I think) you expect it o, is only one lastEqualButtonTime variable for both buttons (is it a global? I don't see a definition). I think you'll need one for each.


text:
How can I initialize an array of objects in setup?
How can I declare an empty global array, to be initialized in setup?
What I would like to do is this:
#include <ResponsiveAnalogRead.h>

const size_t ANALOG_SIZE = 3;
const int ANALOG_PINS[ANALOG_SIZE] = {A0,A1,A2};
ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

void setup() {
  for(size_t i=0; i<ANALOG_SIZE; i++){
    analog_reads[i]=ResponsiveAnalogRead(ANALOG_PINS[i], true, 0.01);
  }
}

But the error I get is:
sketch_may29c:5: error: no matching function for call to 'ResponsiveAnalogRead::ResponsiveAnalogRead()'
 ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

                                              ^

Is it impossible to declare an empty array of a given size?

did you try the example sketch that came with the library?

@jsotola yes, that compiles just fine, but that uses only one ResponsiveAnalogRead object.
https://github.com/dxinteractive/ResponsiveAnalogRead also shows how to use multiple, but initializes them globally, not in setup, I want to loop over an array of pin-numbers to initialize multiple of them.

As Craig wrote, the declaration of an class typed array will call the default constructor of the class, which is the one without any arguments. The class, that you use, does not provide a default constructor, since it needs it's parameters. You cannot do it this way.
But you can use dynamic allocation. In global scope only declare an array of pointers to ResponsiveAnalogRead objects:
ResponsiveAnalogRead *analog_reads[ANALOG_SIZE];

This array only holds pointers, that can point to ResponsiveAnalogRead objects. The objects themselves are not created yet. In setup() you can then create the objects dynamically with the new statement:
analog_reads[0] = new ResonsiveAnalogRead( input_parameters);

(Of course you have to replace input_parameters with all parameters, that the constructor needs). To call a member of the object, you can dereference it like this:
analog_reads[0]->member_function();

If you don't know about pointers yet, you should google for a tutorial (there are plenty), so that you understand the principle behind them.
Important note: Dynamic allocations of memory geht written to the heap in RAM. Since the Arduino (especially the Atmega based ones) has only very limited RAM, dynamic allocations have to be handled with great care. You should not create and delete data often in your program, since this would make swiss cheese out of your heap. But allocating the memory only once in your program and never deleting it, will not be a problem, as long as you don't try to allocate too much memory.

Makes sense! I have some experience in C, so I do know pointers :) Thanks for elaborating.

Craig already explained the reason of the error is the lack of a default
constructor, and chrisl suggested a reasonable alternative. I would like
to suggest two other alternatives.
Static initialization
You state that you want to do the initialization in setup(), but you
don't explain why you want that. I will guess that what you really
want is to have all those objects in array. The library page provides
this example showing how to statically initialize multiple instances:
ResponsiveAnalogRead analogOne(A1, true);
ResponsiveAnalogRead analogTwo(A2, true);

The problem with this example is that you don't have an array, so you
cannot loop through the instances. This problem, however, can be easily
fixed:
const size_t ANALOG_SIZE = 3;
ResponsiveAnalogRead analog_reads[ANALOG_SIZE] = {
    ResponsiveAnalogRead(A0, true),
    ResponsiveAnalogRead(A1, true),
    ResponsiveAnalogRead(A2, true)
};

Note that you don't need the ANALOG_PINS array anymore. And you don't
need to pass 0.01 as the last argument to the constructor, as this is
the default value anyway. This would be my preferred solution: it is
simple enough and doesn't increase the number of lines of code.
Patching the library
If you really want to initialize the array in setup(), then you can
patch the file ResponsiveAnalogRead.h from the library:

Add default values to all the parameters of the constructor. For
example:

ResponsiveAnalogRead(int pin=0, bool sleepEnable=0, float snapMultiplier=0.01);

Add a method for setting the pin after initialization:

void setPin(int newPin) { pin = newPin; pinMode(pin, INPUT); }

The first change will enable you to compile your code as-is. The second
change will allow you to update the objects in setup() rather than
overwriting them (which I don't find very elegant):
for (size_t i = 0; i < ANALOG_SIZE; i++) {
    analog_reads[i].setPin(ANALOG_PINS[i]);
    analog_reads[i].enableSleep();
}

Note that using the default constructor now has the side effect of
setting pin 0 to input. This should not be a big deal, as the
constructor is called before setup(), and all the IO pins are inputs
at this point. If you want nevertheless to void that side effect, then
set the default pin to -1, and patch the constructor to only configure
the pin if it's not -1.
Patching the library creates a maintenance burden though: you will have
to reapply the patch each time the library is updated. This may not be
that bad if you know how to git rebase or git merge, but ideally you
would want to get a pull request accepted by the original maintainer.
Edit: Before patching the library, consider weighting in this
issue and using this fork.
Update: A pull request addressing this issue has been
accepted. As of version 1.2.0, the class has now a default “do nothing”
constructor.

Thanks for an even more elaborate answer!
By the way, the reason I want to initialize in setup() is because I want to multiplex these analog pins to 16 channels. I want each multiplexed channel to have its own ResponsiveAnalogRead object. That also means I do not want to get rid of the ANALOG_PINS  array, because I want to loop over that 16 times :) I considered patching the library after @Craig 's answer, but I have no C++ experience. Thanks for suggesting the issue and the fork, but I've gone with the solution offered by @chrisl already.

When you declare an array it will call the default constructor for the type. ResponsiveAnalogRead does not have a default constructor so it cannot initialize the entries in the array.


text:
atmega88 timer2 32.768KHz and Serial problem
I am trying to use atmega88 timer2 with a 32.768KHz crystal. I'm using a slightly modified version of Nick Gammon's code. I am using Minicore. No bootloader, 1MHz clock from internal oscillator, BOD disabled. Sleep is interrupted every 8 seconds. I use a counter to count 12 minutes. Since it overshoots about 8 seconds every 6 hours, I am subtracting 8 sec every 6 hours. I hope to eventually make a weather logger with this.
The code is mostly working in it's bare stripped down version, after I add a delay(100) after the digitalWrite. However, I also need Serial. When I enable Serial, it does not sleep anymore. Also, the serial output has a lot of excess weird characters. This happens at all baud rates, even 1200 (serial monitor set to same baud rate as in program). I think some interrupts are being called during digitalWrite and when the usart is powered on and it is messing with the sleep. I am a beginner regarding uC programming, and am really struggling with the datasheet and the code. Any help will be appreciated.
Here is the test code:
#include <avr/sleep.h>
#include <avr/power.h>

const byte tickPin = 4;// (do not use 3 and 11)

//byte intCounter = 0;
//byte leapCounter = 0;

int intCounter = 0;
int leapCounter = 0;

unsigned long prevTime = 0;
unsigned long currTime = 0;

// interrupt on Timer 2 compare "A" completion - does nothing
EMPTY_INTERRUPT (TIMER2_COMPA_vect);

void setup(){
  pinMode (tickPin, OUTPUT);

  Serial.begin(9600);
  prevTime = millis();
  Serial.print(" P: ");
  Serial.println(prevTime);

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);

  // set up timer 2 to count up to 256 * 1024  (8 seconds)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  255;                                     // (zero-relative)

  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);

  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_twi_disable();
//  power_timer0_disable();
//  power_timer1_disable();
  power_spi_disable();
  power_usart0_disable();
  power_adc_disable ();

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);

  // get ready ...
  sleep_enable();

}  // end of setup

void loop(){
  sleep_cpu ();
  ++intCounter;

  power_usart0_enable();
  Serial.print("I: ");
  Serial.print(intCounter);
  Serial.print(" L: ");
  Serial.print(leapCounter);
  currTime = millis();
  Serial.print(" C: ");
  Serial.print(currTime);
  Serial.print(" E: ");
  Serial.print(currTime - prevTime);
  Serial.println();
  prevTime = currTime;
  power_usart0_disable();
  delay(1000);

  if ((leapCounter > 30) && (intCounter == 1)){
    leapCounter = 0;
    intCounter = 0;
  }
  if (intCounter > 89){
    ++leapCounter;
    intCounter = 0;
    digitalWrite (tickPin, ! digitalRead (tickPin));
    delay(100);
  }
//  digitalWrite (tickPin, ! digitalRead (tickPin));
//  delay(100);
}  // end of loop

The chip is an Atmega88 (not P). It is drawing the same 6.5uA during sleep, with or without timer0 and timer1. So, I probably don't care if I have to leave them enabled.
I am planning to use a DHT11 and a ds18B20 and write the data to a w25Q64 flash, every 12 minutes. I'd prefer reading it all out via serial port every few weeks, without having to stop the uC.
update
Calling timer2 ISR, instead of handling wake up directly in main loop. Possibly more stable (not affected by Serial and digitalWrite)... but I am not sure.
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

//const byte tickPin = 4;// (do not use 3 and 11)

volatile bool t2flag = LOW;
volatile byte t2counter = 0;

byte leapCounter = 0;

//preventing digitalWrite from causing interrupt (did not help much)
EMPTY_INTERRUPT(PCINT2_vect);

void setup(){
  pinMode (4, OUTPUT);
  pinMode (1, INPUT_PULLUP); //set TX pin default HIGH

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);
  // set up timer 2 to count up to 256 * 1024  (8 seconds)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  255;                                     // (zero-relative)
  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);
  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_twi_disable();
//  power_timer0_disable();
//  power_timer1_disable();
  power_spi_disable();
  power_usart0_disable();
  power_adc_disable();
  wdt_disable();// reduces 6.5uA to 2.2uA @ 3.3V

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);
  sleep_enable();
}

//ISR to handle timer2
ISR (TIMER2_COMPA_vect){
  ++t2counter;
  if (t2counter > 89){t2flag = HIGH;}
}

void loop(){
  if (t2flag == LOW){

    power_usart0_enable();
    Serial.begin(9600);
    Serial.print("I: ");
    Serial.print(t2counter);
    Serial.println();
    Serial.flush();
    delay(10);
    Serial.end();
    power_usart0_disable();

    //blip the tickPin every 8 sec
    PORTD |= (1<<PD4);
    delay(10);
    PORTD &= ~(1<<PD4);

    delay(100);//helps a lot
    sleep_cpu();
    return;
  }

  ++leapCounter;
  if (leapCounter == 30){
    t2flag = LOW;
    return; //delay another 8 sec every 6 hours
  }
  if (leapCounter > 30){leapCounter = 0;}

  t2flag = LOW;
  t2counter = 0;

  power_usart0_enable();
  Serial.begin(9600);
  Serial.print("L: ");
  Serial.print(leapCounter);
  Serial.println();
  Serial.flush();
  delay(10);
  Serial.end();
  power_usart0_disable();

  //long blip every 12 minutes
  PORTD |= (1<<PD4);
  delay(100);
  PORTD &= ~(1<<PD4);
}

The problem is not always present. But when it appears, it happens the same way. After pressing reset button, first led blink is always after 8 seconds. After that, one of three things seem to happen. 1. Second flash is after 8 seconds and everything works as expected. 2. Second flash is after 3 seconds and all flashes after that are also after every 3 seconds. 3. Second flash happens immediately after first flash (and any delay() in the code) and this keeps on happening. In all cases, the serial output also shows the same pattern.
Sometimes it seems that wires connected to the serial or miso, mosi, sck may be causing this, but that is not always the case. The problem may occur even if these wires are not connected. Also, the problem may or may not occur with the same code (e.g. pressing reset after 30 sec may not show any problem, but pressing reset within 5 or 10 seconds leads to problem cases 2 and 3 above. So there is some kind of race condition, or buffer or interrupt noise or something.
I have to program with Arduino as ISP, as the bootloader is unable to sync with the ftdi chip for some reason while uploading sketch. But data transfer from the sketch with serial.print is working fine. So pulling out the miso mosi sck pins everytime is a hassle. Everything is on breadboard. I transferred full circuit to new breadboard (from old loose breadboard) but there is no change. So maybe not a breadboard issue.

this is not an Arduino question, but it is very interesting

Thanks. I didn't know where to ask, and the old arduino had a somewhat similar atmega8, I think (although not a watch crystal).

https://arduino.stackexchange.com/questions/13167/put-atmega328-in-very-deep-sleep-and-listen-to-serial

@jsotola Thanks for the link. However, that is not what I see. Enabling usart is waking up the uC even from power save (or at least seems like it). Besides, there is also the problem of garbled output even with correctly set baud rates.

I see two issues in this code.
The first is that you are trying to send data through an UART that has
been powered off. Serial.print() doesn't wait for the data to get out,
it merely stores it into a memory buffer. You should wait until
everything gets out before switching the UART off. This can be done by
calling either Serial.flush() or Serial.end(). I would use the
latter, as it feels safer to stop the UART before switching if off. But
then you have to Serial.begin() again on wakeup.
To avoid the garbled characters in the serial stream, you could try to
either pinMode(1, INPUT_PULLUP); or digitalWrite(1, HIGH);. This way
you ensure that the TX line stays HIGH (which is its normal idle
state) when the UART goes off.
The second issue is your use of the Arduino timekeeping functions
millis() and delay(). These functions rely on an interrupt triggered
by Timer 0. If you power off that timer, millis() and delay()
won't work. If you don't, SLEEP_MODE_PWR_SAVE does it for you while
sleeping. Then those function will work while awake, but millis() will
not count the time you spent sleeping.

Edit: There are two interrupts related to the UART that are enabled
by Serial.begin():

USART_UDRE, “Data Register Empty”, is used for transmission. It
fires when the hardware transmit buffer is ready to receive new data.
The corresponding ISR's job is to copy one byte from the transmit
memory buffer (the one Serial.print() writes into) into the hardware
transmit buffer.
USART_RX, “Receive Complete”, is used for reception. It fires when a
byte is received. The corresponding ISR copies this byte into receive
memory buffer (the one Serial.read() reads from).

The first one fires when transmitting. Once you wait for the end of the
transmission (say with Serial.flush()), you shouldn't see this
interrupt firing anymore.
The second one fires only when receiving. If you are not receiving
anything, this interrupt shouldn't fire. If the RX pin is floating, the
interrupt could be triggered by external noise. This can be prevented by
enabling the internal pullup on the RX pin. Alternatively, you can
disable the receiver part of the UART:
UCSR0B &= ~_BV(RXEN0);  // disable the UART receiver

Note that if you stop the UART with Serial.end(), both the transmitter
and the receiver are disabled, and you don't get UART-related interrupts
anymore.

Thanks. I will check if that fixes the serial issues. I did not know that millis would be halted during sleep, inspite of keeping timer0 enabled. Maybe I'll be able to check that if I can get serial to work reliably. However, I'm only using millis() as a rough estimate as it's running from the internal oscillator, so not a dealbreaker if it is messed up.

I checked, and your instructions fixed the garbled messages of the serial line. Also, millis() does indeed only count the wake time. However, it seems serial uses interrupts, so it is still causing some problems. I put the timer2 interrupt in an ISR, and it is slightly better. It causes a problem only if the serial wires are connected during reset.

@Indraneel: Re serial interrupts: see the edited answer. I don't know what you mean by “I put the timer2 interrupt in an ISR”.

Thanks for the update. I'll see if that helps. I think, writing to the LED pin may also be causing an interrupt. It is helping to put a delay after the write. I have edited my question above with the updated code.

@Edgar_Bonet Problem is mostly during startup, like if I press the reset pin for too long (1-2 seconds, instead of small tap). But problem shows up only after 1st sleep cycle is complete (after 1st 8 seconds). No difference on adding 0.1uF capacitor to reset pin.


text:
OneButton with pins A6 and A7
I noticed that OneButton library does not work with pins A6 and A7 (with A1 and A2 it works good) on my Arduino Nano. Is it because A6 and A7 are Analog only? There is possibility to make them work properly?
sketch example is here https://github.com/mathertel/OneButton/blob/master/examples/TwoButtons/TwoButtons.ino

Is it because A6 and A7 are Analog? ... why would you would ask that?  A1 and A2 are also analog pins. .... please post the sketch that fails

A1 and A2 could be also digital, but A6 and A7 as I understand - no (see attached pinout schema)

that is not what you said in your question .... when it comes to technical questions, you have to be precise  .... change your statement to Is it because A6 and A7 are "analog only"?

Pins A6 and A7 are analog only pins. They have no digital functionality at all.

You can see that pins 19 and 22 only have ADCn on them - no Pxn for digital operation (ignore the colour scheme of those pins - that's an error in the datasheet).

That is what I thought... So is it possible to make OneButton with analog pins?

That is correct. You would have to adapt it to use analogRead() on those pins and compare the incoming values to threshold values for HIGH and LOW. Could be done, but clunky.

In the library, in the function tick, there is the digitalRead call. You could change that line to test if pin a6 or a7 is used and then use code with analogRead. Perhaps the author of the library is willing to add that. You could make an issue and ask for a feature request.

authors: Филипп Цветков


text:
LiquidCrystal library and timers don't seem to be compatible
If I set timer2 to Compare Match mode, my LCD display stops working. If I use Overflow Interrupt it works fine.
Here's my test code. I have a loop() function which does its thing, and a timer interrupt which increments another variable, just to show it's working.
#include <LiquidCrystal.h>
#include <avr/interrupt.h>
#include <avr/io.h>

LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD:

int i;
volatile int j;
void setup()
{
  i=0;
  j=0;
  //button adc input
  pinMode( A0, INPUT ); //ensure A0 is an input
  digitalWrite( A0, LOW ); //ensure pullup is off on A0
  //lcd backlight control
  pinMode( 10, OUTPUT ); //D10 is an output
  digitalWrite( 10, HIGH ); //backlight control pin D10 is high (on)
  //set up the LCD number of columns and rows:
  lcd.begin( 16, 2 );

  // setup timer interrupt
  cli(); //disable global interrupts
  TCCR1A = 0;   //set tccr1a and tccr1b to 0
  TCCR1B = 0;
  //set cs10 and cs12 bit so timer runs at clock iSpeed/ 1024
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);

  // Compare Match Mode **Doesn't work**:
  //set compare match register
  OCR1A = 15624;
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Overflow mode **Works**
  // enable overflow interrupt
  // TIMSK1 = (1 << TOIE1);

  //enable global interrupt
  sei();
}
void loop()
{
  lcd.setCursor( 0, 0 ); //top left
  lcd.print(i);
  lcd.setCursor(0,1); //bottom left
  lcd.print(j);
  delay(500);
  lcd.clear();
  i++;
}

ISR(TIMER1_OVF_vect)
{
  j++;
}

If I use overflow interrupts it works fine, the loop() counter is displayed on the top line and the interrupt counter on the second, but by using overflow interrupts I'm limited to the whatever timing the various prescalers give me.
If I use compare match the LCD display just shows faint flickering squares on its first line, like it's doing something but too quickly for the LCD to display.
I looked at the source for liquidcrystal.cpp, and it doesn't seem to use any timer or interrupts, so I'm completely mystified.

Dang, it was a bit of a noobish error. I had the interrupt handler setup for the overflow interrupt, but when I swapped the code in for the Compare Match interrupt I didn't make a handler for it. So since there's an interrupt without a handler it seems it just resets, hence the flashy-flashy garbage I was seeing on the LCD.
Adding this fixed the problem:
ISR(TIMER1_COMPA_vect)
{
  j++;
}


text:
Connecting HC-06 and LM35
Hello I am trying to send temperature data via bluetooth using the HC-06 module. Since TXD and RXD only allow 3.3V I have divided the circuit into two like the below image.
Is this method correct? or is there a better way to connect both two?

Any help is appreciated.

I think you have it backwards. You should be dividing the TX from the Arduino (5V) down to 3.3V for the RX into bluetooth.

@Majenko Thank you for your comment. I'm a little confused. Is the below picture correct. So the purple and green wires should be reversed?

No, the resistors should be on the green wire not the purple.

Is the lower module a bluetooth master? If I recall it correctly, the HC-06 module have their firmware set to slave only

"Who" is on the other end? Once HC-06 is paired with a master - Nexus 7, f/ex, or PC's with Bluetooth 2 - it will communicate just fine. Just remember the HC-05/06 are Bluetooth 2 devices and can't talk to BLE devices -- current iPhones and many current PCs.

As mentioned by chrisl, you cannot use HC-06 as a master device. Its firmware restricts it to behave only as a slave. So even if you are able to process the analog data from LM 35, you won't be able to send it using HC-06. It would be better if you go for HC-05 module and try the command AT+ROLE: x (x = 1 for master/0 for slave) to get the job done.
Coming to the 3v3 voltage constraint, I would suggest you to go for any Zener diode (in reverse biased mode) with 3.3V Reverse breakdown voltage. You can check the circuit for this here and order it from this link. If this is not possible anyhow, then you can also go for LM1117 3V3, but I would personally suggest you to go for zener diode. Comment back if you need any help in future.


text:
Sensor Robot Car Arduino Cannot Detect Every Inch
I'm very new about this thing. I have made an arduino robot car for my assignment. There is a maze that I have to complete it. I'm using L298N Dual H-Bridge Motor Driver, Servo Motor, HC-SR04 Ultrasonic Sensor, DC Motor, Arduino Sensor Shield.
The problem when in the maze is, the sensor will check if there is wall front of the car. Then it will scan from left, then right. BUT, the maze was straight line and at the middle, has one way out.
I have a problem on how to make the sensor detect the 180 degree of wall every second. What I mean is, when the car move ahead inch, the sensor will scan left, front, right. Then, if there is a wall at left, the car move ahead inch, then scan again. I really need help for this assignment.

Here is my code:
#include <Servo.h>
// Pins for the Echo Sensor
#define TRIG_PIN A0
#define ECHO_PIN A1
//Define all the connections maps to the L298N
#define enA 13
#define in1 12
#define in2 11
#define in3 7
#define in4 6
#define enB 5
#define servoPin 2

class Motor{

int enablePin;
int directionPin1;
int directionPin2;

public:

//Methods to define motor pins
Motor(int ENPin,int dPin1,int dPin2){
enablePin = ENPin;
directionPin1 = dPin1;
directionPin2 = dPin2;
};

//Method to allow robot to turn and move forward and backwards
void Drive(int speed){
if(speed>=0){
digitalWrite(directionPin1, LOW);
digitalWrite(directionPin2, HIGH);
}
else{
digitalWrite(directionPin1, HIGH);
digitalWrite(directionPin2, LOW);
speed = - speed;
}
analogWrite(enablePin, speed);
}
};

Motor leftMotor = Motor(enA, in1, in2);
Motor rightMotor = Motor(enB, in3, in4);
Servo myservo; // create servo object to control a servo

void motorInitiation(){
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
// Set initial direction and speed
digitalWrite(enA, LOW);
digitalWrite(enB, LOW);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
}

//Variables--------------------------------------------------------------------------
// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;
bool ObsticalAhead = false;
int servoPos = 90;

enum Directions { Forward, TurnLeft, TurnRight, TurnAround,Brake};

Directions nextStep = Forward;

unsigned long t1;
unsigned long t2;
unsigned long pulse_width;
float cm;
float inches;

//SETUP--------------------------------------------------------------------------
void setup() {

// The Trigger pin will tell the sensor to range find
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);

// Serial monitor to view the sensor output
Serial.begin(9600);
myservo.attach(servoPin);
motorInitiation();
Directions nextStep = Forward;
}

void loop() {

checkDistance();
checkDirection();
drive();
}

void checkDistance(){

// Hold the trigger pin high for at least 10 us
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// Wait for pulse on echo pin
while ( digitalRead(ECHO_PIN) == 0 );

// Measures how long the echo pin was held high (pulse width)
t1 = micros();
while ( digitalRead(ECHO_PIN) == 1);
t2 = micros();
pulse_width = t2 - t1;

// Calculate distance in centimeters and inches from sound to bounce back
cm = pulse_width / 58.0;
inches = pulse_width / 148.0;

// Print out results
if ( pulse_width > MAX_DIST ) {
//Serial.println("Out of range");
} else {
//Serial.print(cm);
//Serial.print(" cm \t");
//Serial.print(inches);
//Serial.println(" in");
}

// Wait at least 60ms before next measurement
delay(60);

if(cm<= 20){
ObsticalAhead = true;
Serial.println("Problem Ahead");

}
else{ ObsticalAhead = false;}

}
void checkDirection(){
Serial.println("checking direction");
if(ObsticalAhead ==true){
nextStep = Brake;
drive();
myservo.write(180); // tell servo to go to position in variable 'pos'
delay(400); // waits 15ms for the servo to reach the position
checkDistance();
if(ObsticalAhead ==false){//if left side is open
nextStep = TurnLeft;
Serial.println("Next step is TurnLeft");
myservo.write(90);//reset servo position
delay(400);
}
else{// left is blocked, now need to look at right
myservo.write(0); // tell servo to go to position in variable 'pos'
delay(800); // waits 15ms for the servo to reach the position
checkDistance();
if(ObsticalAhead ==false){//if right side is open
nextStep = TurnRight;
Serial.println("Next step is TurnRight");
myservo.write(90);//reset servo position
delay(400);
}
else{//right is blocked as well, need to turn around
nextStep = TurnAround;
myservo.write(90);//reset servo position
delay(300);
Serial.println("Next step is TurnAround");
}
}

}
else{nextStep = Forward;}//No obstical ahead
}

void drive(){
switch (nextStep){
case Forward:
leftMotor.Drive(255);
rightMotor.Drive(255);
Serial.println("Forward");

break;
case TurnLeft:
leftMotor.Drive(-255);
rightMotor.Drive(255);
Serial.println(" TurnLeft");
delay(400);

break;
case TurnRight:
leftMotor.Drive(255);
rightMotor.Drive(-255);
Serial.println(" TurnRight");
delay(400);
break;
case TurnAround:
leftMotor.Drive(255);
rightMotor.Drive(-255);
Serial.println(" TurnAround");
delay(600);
break;

case Brake:
leftMotor.Drive(0);
rightMotor.Drive(0);
Serial.println(" stopped");
}
}

Tip: break your program down into smaller functions and "unit test" them. Make sure that each component of your program does what you expect it to, then make them all work together.

I am not sure from your description what the problem is. What is it not doing that it should, or doing that it shouldnt?


text:
Connecting and using ESP8266 wifi
My ESP8266 has stopped working.
The red power light comes on and the blue TX light is on solid.
Here's what I did.
Connecting
ESP8266  -> Arduino nano
VCC, CH_PD, RST  -> 5V (external supply)
TX -> TX
RX -> RX
I could send AT commands via the serial monitor.
Then I connected
RX -> 11
TX -> 10
and set up software serial intending to repeat the experiment.
I was getting garbage characters in the response, and found that I had to esp8266.println("AT+IPR=9600"); to reduce the baud rate.
Then the blue TX light cam on permanently and it's stopped working at all.

Reflash the firmware. That fixes most issues.

It's looking that way.
Do you know of a good guide on reflashing via arduino?

Serial devices should be connected RX to TX and TX to RX.
When you connected the RX to RX you connected the esp8266 to USB chip on Nano. Because the USB chip is connected to Atmega on Nano RX to TX, so if you connect the esp8266 to the same line, the it is connected RX to TX to USB.
On this picture esp8266 is connected to Atmega and not accessible from USB:

Communication from Serial Monitor over USB to esp8266 on pins 10 and 11 of the Atmega could work only with SerialPassthrough sketch resending data between Serial and SoftwareSerial on pins 10 and 11.


text:
L298 with stepper.h disable break
I try to control a Stepper motor with an arduino and a L298. I use the library stepper.h and it works well but i have a problem : the L298 become very hot. So i want to disable the break (the thing that we can't turn the motor by hand), but i don't know how to do this.
Do you have an idea ?
My code is simple :
#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

I took it from here : https://coeleveld.com/arduino-stepper-l298n/
Thanks !

There is no facility in the stepper library to do what you want - however the stepper library just sequences IO pins in the right order.
There's nothing to stop you just placing those same IO pins in a different state - the library won't care.
void sleepStepper() {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
}

That will effectively set every port of the L298 LOW, which is equivalent to "brake" mode on a normal DC motor, or "not actively driving" on a stepper (not perfect freewheel, there is still some flyback braking).
Another option is to connect the EN pin(s) of your L298 chip to a GPIO and use that to turn the whole system on and off. That will disconnect the drivers from the motor and give you even less movement resistance than the "all low" method above.

Oh ! I thought that the library will block the pins ! Thank you.

@LelaidierLucas Nah - it just performs a sequence of digitalWrite() calls.


text:
Creating a webserver on a Wemos D1 mini pro
I am trying to put a web server on my Wemos D1 mini pro. I am using this example for the Arduino code:
https://github.com/wemos/Arduino_D1/blob/master/doc/esp8266wifi/server-examples.rst

#include <ESP8266WiFi.h>

const char* ssid = "GL-AR300M-ceb";
const char* password = "********";

WiFiServer server(80);

void setup()
{
  Serial.begin(115200);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");

  server.begin();
  Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}

// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
  String htmlPage =
     String("HTTP/1.1 200 OK\r\n") +
            "Content-Type: text/html\r\n" +
            "Connection: close\r\n" +  // the connection will be closed after completion of the response
            "Refresh: 5\r\n" +  // refresh the page automatically every 5 sec
            "\r\n" +
            "<!DOCTYPE HTML>" +
            "<html>" +
            "Analog input:  " + String(analogRead(A0)) +
            "</html>" +
            "\r\n";
  return htmlPage;
}

void loop()
{
  WiFiClient client = server.available();
  // wait for a client (web browser) to connect
  if (client)
  {
    Serial.println("\n[Client connected]");
    while (client.connected())
    {
      // read line by line what the client (web browser) is requesting
      if (client.available())
      {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        // wait for end of client's request, that is marked with an empty line
        if (line.length() == 1 && line[0] == '\n')
        {
          client.println(prepareHtmlPage());
          break;
        }
      }
    }
    delay(1); // give the web browser time to receive the data

    // close the connection:
    client.stop();
    Serial.println("[Client disonnected]");
  }
}

It uploads fine and when I open the serial monitor get this:
Connecting to GL-AR300M-ceb . connected
Web server started, open 192.168.8.119 in a web browser
When I go to the IP address that it gives in the monitor, I only see a blank page. I also can't inspect element, so it doesn't load the HTML part I guess.
When I change the code like this:
if (client.available())
{
//        String line = client.readStringUntil('\r');
//        Serial.print(line);
//        // wait for end of client's request, that is marked with an empty line
//        if (line.length() == 1 && line[0] == '\n')
//        {
//          client.println(prepareHtmlPage());
//          break;
//        }
          client.println(prepareHtmlPage());
      }

then i see this

And when i add the break in the code like so:
client.println(prepareHtmlPage());
break;

in the code, i get the blank page again.
Does someone have an idea what the problem might be?

Why not use the far simpler ESP8266WebServer examples that come with the core?

Oh, thank you. Honestly, I didn't know about them yet! Let me try the HelloServer.

It's a far simpler interface than trying to implement HTTP from the ground up.

Yes! I got it to work! Thank you for this tip!

I'm no master. I don't believe there is ever a carriage return while requesting a web page.

you should go for the "Advanced Webserver" example provided by the ESP8266 libraries in your Arduino IDE.
The webserver is using callbacks like
server.on ( "/", handleRoot );
server.on ( "/test.svg", drawGraph );

and so on.
Then you can use these handles to give back a html page to your browser like
server.send(200, "text/plain", message);       //Response to the HTTP request

Note how the function returns an 200 http code to your browser, which is mandatory for showing up your web page!


text:
How to drive 16 stepper motors with Arduino?
I'm trying to drive 16 of these little steppers on an Arduino Uno.
Each test driver uses 4 digital pins for control (2 for each coil) so that would be 64 pins I will need.
I'm thinking either getting something like this or 4 of these.
Would something like that work ?
What's the most straight forward way to drive these on an Arduino Uno ?

I wouldn't get those steppers. One part of the description says it has one chip to drive it, and another part says a completely different chip. Unless you actually have them already, in which case you can manually identify what the chip is on it. The two different chips need completely different driving strategies.

@Majenko Looks like an ULN2003 (SOIC16 !) driver in the picture, not an A3967 (SOIC24) like in the description. I, personally, would just use 8 shift registers.

If you need to drive all 16 simultaneously and independently, the Uno may not have enough capability to do it. Consider the worst-case number of motors and highest rate(s) you expect to drive at once, plus anything else you need the Uno doing at the same time. You might try a simple sketch to do all of these things (substituting LEDs for the motor drivers) at once, and use a scope to examine those LED output signals for the right frequency, wave-form, and lack of jitter. Without I/O expanders, you won't get to 16 motors' worth of outputs (unless you already have an I/O expander) but you might try doubling up on the existing output (use non-overlapping motor phases if you can).
If the Uno can manage that with clean outputs, you'll have a better idea whether it can manage the full load. If it doesn't, you may need to reconsider your choice of processor with respect to its clock-speed, both kinds of memory (depending on what you learned), number of outputs, possibly number of available timers and of interrupts.

Alternatively: split the load between multiple MCUs.

The maximum (reliable) speed I could get with those steppers was at 3ms per step.


text:
Arduino IDE - Ubuntu Mono Font Name?
I know that you go to preferences.txt and there is editor.font= line setting, but I can't get what font name to type in there to use Ubuntu Mono. I would like to use that font please. I've tried:
Ubuntu_Mono
Ubuntu-Mono
Ubuntu Mono
Ubuntu+Mono
Ubuntu.Mono
UbuntuMono
Ubuntumono
ubuntumono
'Ubuntu Mono'
"Ubuntu Mono"
'UbuntuMono'
"UbuntuMono"
'Ubuntu-Mono'
"Ubuntu-Mono"
'Ubuntu_Mono'
"Ubuntu_Mono"

Thanks for answer :]
PS: Yes, I've restarted the studio every time, but some non-monotype/default font showed up.

You need to specify the font, style and size.  I think you want
editor.font=Ubuntu Mono,plain,12

I don't know the exact name you should use for the font but you must have all three fields separated by commas.
The second field can be "plain", "bold" or "italic".
The third field is the font size, I'm not sure the units.

Thanks for answer, but I googled that out yesterday and I'm just looking for the name.

Here are instructions for finding the font names available in java your platform: https://alvinalexander.com/blog/post/jfc-swing/swing-faq-list-fonts-current-platform


text:
arduino nodejs serial data chunked and not in synch
I'm trying to get an arduino sending data to node but with no success.
I'm connecting to an ar-drone 2.0 as in https://gist.github.com/maxogden/4152815
Here is my Arduino code:
    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    #include <Wire.h>
    #include "Adafruit_HTU21DF.h"
    /*
      Sketch per creare json contenente
      lat,lon,data,ora,temp, hum
    */
    static const int GPS_RXPin = 16, GPS_TXPin = 10;
    static const uint32_t GPSBaud = 9600;

    Adafruit_HTU21DF htu = Adafruit_HTU21DF();

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(GPS_RXPin, GPS_TXPin);

    //JSON
    const size_t bufferSize = JSON_OBJECT_SIZE(6);
    DynamicJsonBuffer jsonBuffer(bufferSize);
    JsonObject& oData = jsonBuffer.createObject();

    void setup()
    {
      Serial1.begin(9600);
      Serial.begin(9600);
      ss.begin(GPSBaud);
      if (!htu.begin()) {
        Serial1.println("Couldn't find Adafruit_HTU21DF!");
        while (1);
      }
    }

    void loop()
    {
      float lat = gps.location.lat();
      float lon = gps.location.lng();
      float date = gps.date.value();
      float timestamp = gps.time.value();
      float temp = htu.readTemperature();
      float hum = htu.readHumidity();

      Serial1.print(lat);
      Serial1.print(";");
      Serial1.print(lon);
      Serial1.print(";");
      Serial1.print(date);
      Serial1.print(";");
      Serial1.print(timestamp);
      Serial1.print(";");
      Serial1.print(temp);
      Serial1.print(";");
      Serial1.print(hum);
      Serial1.print(";\n");

      //////

      Serial.print(lat);
      Serial.print(";");
      Serial.print(lon);
      Serial.print(";");
      Serial.print(date);
      Serial.print(";");
      Serial.print(timestamp);
      Serial.print(";");
      Serial.print(temp);
      Serial.print(";");
      Serial.print(hum);
      Serial.print(";\n")

      smartDelay(1000);
      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial1.println(F("No GPS data received: check wiring"));
    }

    // This custom version of delay() ensures that the gps object
    // is being "fed".
    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

and this my NodeJS code:
    var serialport = require('node-serialport');
    var WebSocketServer = require('ws').Server;

    var wss = new WebSocketServer({host:'0.0.0.0',port: 9999});
    var sp = new serialport.SerialPort("/dev/ttyO3", {
      parser: serialport.parsers.readline("\n"),
      baud: 9600,
      buffersize: 65536
    });

    wss.on('connection', function(ws) {
      ws.send('connected');
      ws.on('message', function(message) {
        console.log('received: %s', message);
      });
      sp.on('data', function(chunk) {
        var fromArduino = chunk.toString();
        ws.send(fromArduino);
        console.log(fromArduino);
      });
    });

While the CSV comes out nice on Arduino IDE serial monitor, it is all messed up both on ws and node console.

I'm using this version of NodeJS and node-serial: https://github.com/felixge/node-cross-compiler/downloads
and set ttyO3 as in https://gist.github.com/maxogden/4152815
A voltage diveder is set between drone RX and Arduino TX1 to lower signal from 5v to 1.8v.
Thanks for any help!
Lorenzo

UPDATE 2 JUN 2018
I managed to make things a little bettere with the following code:
ARDUINO:
        #include
        #include
        #include "Adafruit_HTU21DF.h"
        /*
          Sketch per creare json contenente
          lat,lon,data,ora,temp, hum
        */
        static const uint32_t GPSBaud = 9600;
    Adafruit_HTU21DF htu = Adafruit_HTU21DF();

    // The TinyGPS++ object
    TinyGPSPlus gps;

    void setup()
    {
      Serial1.begin(9600);
      //  Serial.begin(9600);
      if (!htu.begin()) {
        Serial1.println("Couldn't find Adafruit_HTU21DF!");
        while (1);
      }
    }

    void loop()
    {
      while (Serial1.available()) {
        gps.encode(Serial1.read());
      }
      float lat = gps.location.lat();
      float lon = gps.location.lng();
      int date = gps.date.value();
      float timestamp = gps.time.value();
      float temp = htu.readTemperature();
      float hum = htu.readHumidity();

      Serial1.print(lat);
      Serial1.print(";");
      Serial1.print(lon);
      Serial1.print(";");
      Serial1.print(date);
      Serial1.print(";");
      Serial1.print(timestamp);
      Serial1.print(";");
      Serial1.print(temp);
      Serial1.print(";");
      Serial1.print(hum);
      Serial1.print(";_");
      Serial1.println();
    }

NODE JS:
    var serialport = require('node-serialport');
    var WebSocketServer = require('ws').Server;

    var wss = new WebSocketServer({host:'0.0.0.0',port: 9999});
    var sp = new serialport.SerialPort("/dev/ttyO3", {
      parser: serialport.parsers.readline("_"),
      // parser: serialport.parsers.raw,
      baud: 9600,
      buffersize: 1024
    });
    wss.on('connection', function(ws) {

      sp.on('data', function(chunk) {
        var fromArduino = chunk.toString();
        // console.log(fromArduino);
        ws.send(fromArduino);
        sp.flush();
      });
    });

Now data comes out tidy on both console and ws for most of the times: I guess the problem was the serialport buffersize.
I also removed serial software from Arduino code.

Can't see what's wrong, but a few simplifications could help you nail down the problem: 1. Get rid of SoftwareSerial and use only the hardware serial port: RX from the GPS and TX to the drone. 2. Remove the HTU and JSON code from the Arduino. 3. Remove the WebSockets code from the Node.js. 4. Use parsers.readline("\r\n"), as that's what Serial.println() sends.

since the serial monitor shows correct data, i suspect that your NodeJS code has a bug .... therefore this is not an Arduino question

@lbrutti try getting rid of your parser and directly print every received character from the UART device (/dev/ttyO3) to the console as fast as possible. Maybe a UART buffer is overflowing when it isn't read fast enough. Did you also try Edgar's suggestion?

Hello, i tried removing ws and software serial. Still node output comes out chunked.  I'll try to bypass parsers and let you know. Thanks

@maximilian-gerhardt: i simplified the code by removing software serial and using a smaller buffer. data comes out tidy most of the times: not always but it is accepteable for this early prototyping stage.

Hm at these speeds there should be no problem at reading it out. Could you try lowering the baud rate? (4800, 1200, 300)

Actually, yes, NodeJS serial is expected to give "chunks" your code should put it in a buffer end do the delimiting.

just one miss Sir,
only use instead "baudRate: " not a "baud".
what's a var baud Sir??? Thanks.

  Serial.print(lat);
  Serial.print(";");
  Serial.print(lon);
  Serial.print(";");
  Serial.print(date);
  Serial.print(";");
  Serial.print(timestamp);
  Serial.print(";");
  Serial.print(temp);
  Serial.print(";");
  Serial.print(hum);
  Serial.println(";");

Serial.println will print an \r\n at the end (source). \r is a "carriage return" which will move the curser back to the beginning of the line.
Since you are reading your data with a parser that looks for \n and removes that, you are left with a string that looks like  [csv data..]\r. Once you print that to console verbatim you get the behaviour you are looking at.
Replace Serial.println(";"); by Serial.print(";\n"); (same for Serial1) and see what happens.

hello, unfortunately adding "\n" char at the end of last print didn't help: both console and ws output are messed. Serial Monitor output works well as before.

@lbrutti edit your question to show the updated code, then.