Using 8-bit instead of 16-bit in Adafruit library I tried to modify the Adafruit_GFX and Adafruit_ST7735 libraries to make the color variable( as shown in code below) to use 8-bit instead of 16-bit for displaying 8-bit color on LCD screen.

void Adafruit_ST7735::pushColor(uint16_t color) {
 #if defined (SPI_HAS_TRANSACTION)
   SPI.beginTransaction(mySPISettings);
 #endif
  *rsport |=  rspinmask;
  *csport &= ~cspinmask;

   spiwrite(color >> 8);
   spiwrite(color);

   *csport |= cspinmask;
 #if defined (SPI_HAS_TRANSACTION)
   SPI.endTransaction();
 #endif
}

I changed it to the below

void Adafruit_ST7735::pushColor(uint8_t color) {
  #if defined (SPI_HAS_TRANSACTION)
   SPI.beginTransaction(mySPISettings);
  #endif
   *rsport |=  rspinmask;
   *csport &= ~cspinmask;

   //spiwrite(color);
   spiwrite(color);

   *csport |= cspinmask;
#if defined (SPI_HAS_TRANSACTION)
  SPI.endTransaction();
#endif
}

I have made similar changes in other portions of the code. This time nothing was displayed in the LCD(it was blank). However, when the spiwrite(color) is written twice i.e. the comment is removed, the code works fine.
Why is there a need to write 'spiwrite' function twice even in case of 8-bit color?

The original Adafruit library files are also attached.
drive.google.com/open?id=0B3x_NfKXnhtHR0VBcTNZbk5WT0E

Did you read the datasheet of the LCD screen? The LCD expects you to
send the data in a specific format, and you should comply with that
format rather than invent your own and expect it to magically understand
it. If the LCD expects you to send 16 bits, you should do so. Or maybe
it has a 8 bit mode and there is a way for you to tell it “I'm switching
to 8-bit mode”. Read the datasheet to be sure.

If you want to display 8-bit color on an LCD expecting 16-bit, you
should find a way to map the 8-bit values into 16-bit values. The most
obvious way to map the range [0, 255] to [0, 65535] is to multiply the
8-bit numbers by 65535/255 = 257. Which is the same as sending the byte
twice.


Arduino library not working, can't find header I have fair experience with C/C++ so I decided to have a go at writing my first simple Arduino library. I wrote the code which seems to be fine to me except that it keeps complaining about the header file not found during compilation:

/home/me/sketchbook/libraries/SegDisplay/SegDisplay.cpp:1:24: fatal error: SegDispaly.h: No such file or directory
 #include "SegDispaly.h"
                        ^
compilation terminated.

I have the library located in my sketch folder under the name "SegDisplay":

/home/me/sketchbook/libraries/
└── SegDisplay
    ├── examples
    ├── keywords.txt
    ├── README.md
    ├── SegDisplay.cpp
    └── SegDisplay.h

and here's the code:

SegDisplay.h:

#ifndef _SEVEN_SEG_H_
#define _SEVEN_SEG_H_

#include <math.h>

#if defined(ARDUINO) && (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

class SegDisplay
{
public:
    SegDisplay (int clockPin, int latchPin, int dataPin, int digitPins[4]);
    void display (double value);

private:
    const int digitPins[4];
    const int clockPin;
    const int latchPin;
    const int dataPin;
    const byte digit[10] = //seven segment digits in bits
    {
        B00111111, //0
        B00000110, //1
        B01011011, //2
        B01001111, //3
        B01100110, //4
        B01101101, //5
        B01111101, //6
        B00000111, //7
        B01111111, //8
        B01101111  //9
    };
    int digitBuffer[4];

    void setRegisterData (byte data);
    void clearRegister();
    void clearDisplay();
    void updateDisplay();
};

#endif

SegDisplay.cpp:

#include "SegDispaly.h"

SegDisplay::SegDisplay (int a, int b, int c, int d[4]):
    clockPin (a), latchPin (b), dataPin (c), digitPins (d), digitBuffer ({0})
{
    for (int i = 0; i < 4; i++)
    {
        pinMode (digitPins[i], OUTPUT);
        digitalWrite (digitPins[i], HIGH);
    }
    pinMode (latchPin, OUTPUT);
    pinMode (clockPin, OUTPUT);
    pinMode (dataPin, OUTPUT);
}

void SegDispaly::setRegisterData (byte data)
{
    digitalWrite (latchPin, LOW);
    shiftOut (dataPin, clockPin, MSBFIRST, data);
    digitalWrite (latchPin, HIGH);
}

void SegDispaly::clearRegister()
{
    setRegisterData (B00000000);
}

void SegDispaly::clearDisplay()
{
    // deactivate transistors
    for (int n = 0; n < 4; n++) digitalWrite (digitPins[n], HIGH);
}

//writes the temperature on display
void SegDispaly::updateDisplay()
{
    byte outByte;
    // dispaly digits
    for (int i = 0; i < 4; i++)
    {
        clearDisplay();
        clearRegister();

        // enable nth cell cathode (transistor)
        digitalWrite (digitPins[i], LOW);

        // output nth digit on display
        if (i == 1)
        {
            //print the decimal point on the 2nd digit
            outByte = digit[digitBuffer[i]] | B10000000;
        }
        else outByte = digit[digitBuffer[i]];
        setRegisterData (outByte);

        //delayMicroseconds (500);
        delay (5);

        //Serial.print (outByte, BIN);
        //if (i == 3)
        //{
        //  Serial.println (".");
        //}
        //else Serial.print (", ");
    }
}

void SegDispaly::display (double value)
{
    int n = int (value * 100);
    digitBuffer[0] = n / 1000;
    digitBuffer[1] = (n % 1000) / 100;
    digitBuffer[2] = (n % 100) / 10;
    digitBuffer[3] = (n % 100) % 10;
    updateDisplay();
}

My target AVR is Arduino Uno R3, the code used to work fine in a sketch before I decided to create a library out of it. Any help would be greatly appreciated. thanks in advance.

You spelled the header filename wrong:

#include "SegDispaly.h"

should be:

#include "SegDisplay.h"

You have also made the same mistake in the class name multiple places in SegDisplay.cpp.


Is it possible to run two small motors off an Arduino and have the motors move separately based on a random number generator? I am a 2nd year design engineering student working on a design project where we are tasked with automating the movement of a rainfall simulator. One of our design ideas consists of two small motors running perpendicular to each other with the movements based on a random number generator. I was told that this would be fairly easy if we used a Siemens Program Logic Controller, but we have a very limited budget so I thought I would check out other options.

I am not familiar with the Arduino or much of anything to do with programming so I thought it would be beneficial to ask for advice from some people who know what they are doing. I attached an initial sketch of the idea and a picture of the rainfall simulator to hopefully clarify what I am hoping to accomplish. The most the device can move from its rested state is only 0.5".

Is this a path worth working towards? Or is this not the proper choice of equipment?

Any advice would be greatly appreciated!

Thanks,

Nick

Leaving your mechanical equipment uncommented *), an Arduino itself cannot drive 7.4V 1A Stepper Motors. An Arduino itself cannot drive any motor. You need a sufficient power supply and motor driver electronics. And there's a vast amount of different devices to choose from.

But then, the answer to "is it possible (random, two motors, moving independently)" is yes.

*) Well, regarding "uncommented" :
200 lbs is quite heavy to simulate/produce a few raindrops. Small motors won't move such gear as in your pic.


DC motors only run in one direction I'm quite new to Arduino and am making my first proper project, an obstacle avoiding robot.

I'm using an Arduino Uno and a motor shield compatible with the Adafruit motor driver library. I'm trying to run the example code from here: https://learn.adafruit.com/adafruit-motor-shield/using-dc-motors, but with both motors running at once. This should run the motors forward for 1 sec, backward for 1 sec and then pause for 1 sec.

I'm getting inconsistent behaviour when I run the code. When I only connect 1 motor, it works fine. When the Arduino is connected to my laptop via USB, it works fine. However, when I use the 6V external power supply and both motors, they will only move in 1 direction and remain still during the second movement period. When I set them to move forward-backward-stationary, they only move forwards. When I set them to backward-forward-stationary, they only move backwards.

Any ideas what might be causing this / how I could fix it? Like I said, I'm pretty new to this so might be making a simple mistake.

Here's my setup:

I have 2 DC motors, one attached to port 1 and the other to port 4 on the motor shield. The power supply is 4 AA batteries (which I think is 6V?), which is also connected to the motor shield.

And here's my code:

#include <AFMotor.h>

AF_DCMotor leftMotor(1, MOTOR12_1KHZ);
AF_DCMotor rightMotor(4, MOTOR12_1KHZ);

void setup() {
  leftMotor.setSpeed(255);
  rightMotor.setSpeed(255);
}

void loop() {
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
  delay(1000);

  leftMotor.run(BACKWARD);
  rightMotor.run(BACKWARD);
  delay(1000);

  leftMotor.run(RELEASE);
  rightMotor.run(RELEASE);
  delay(1000);
}

Any help is much appreciated!

Possible hardware solution:

Consider using 2 battery packs.  One connected to the Arduino and the other connected to the motor drive board.  Remember to connect the grounds of the 2 battery packs together.

Possible software solution:

Software is often over looked when solving what appears to be a hardware issue.  Consider introducing a short pause between motor direction changes.  It may be that the power required to reverse the direction of a motor exceeds the capacity of the battery pack.  Likely it will take less power to first stop the motor, pause then start the motor in the opposite direction.


How to check if all pins are connected on my board to make sure Arduino sends the correct pattern number on my tool What to add on this code to check my pins state during run? And how can i trigger error using Visual basic when 1 of my pin is disconnected?

String input = "";

void setup(){

Serial.begin(9600); // Sets up communication with the serial port

pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT); // for start of program operation
pinMode(12,OUTPUT); // for stop of program operation

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);

digitalWrite(11,LOW);
digitalWrite(12,LOW);

}

void loop(){

int recipe;
//Serial.print("Enter recipe number: ");

while(Serial.available()==0){    // Waits for data from serial port
}

while(Serial.available() > 0){
int data = Serial.read();
  // convert the incoming byte to a char
  // and add it to the string
input += (char)data;

recipe = input.toInt()+'0';    //recipe=0 if not a digit
if(recipe == '0')
  recipe = data;

if(data == '\n'){
  //Serial.print("Recipe: ");
  //Serial.println(recipe);
  //Serial.print("String: ");
  //Serial.println(input);
  input = "";
}
}

if(recipe == 's'){
digitalWrite(11,HIGH);
delay(1000);
digitalWrite(11,LOW);

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}

else if(recipe == 't'){
digitalWrite(12,HIGH);
delay(1000);
digitalWrite(12,LOW);

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}

else if(recipe>'0' && recipe<'32'){

recipe = recipe-'0';
char binary[7] = {0};   // This is where the binary representation will be stored
recipe += 32; // Adding 32 so that there will always be 6 digits in the string
itoa(recipe,binary,2);  // Convert recipe to a string of base 2 and save it in array 'binary'
char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

//Serial.print(signals);    // Print out the signals in binary

int i;
for(i=0; i<5; i++){
  if(signals[i] == '0')
    signals[i] = '1';
  else
    signals[i] = '0';
  digitalWrite(i+6, signals[i]-'0');    // write to pin; converts the bit of the string to HIGH or LOW
  //Serial.print(signals[i]);
}

}
else
loop();

}

As mentioned in a comment, your code has some fundamental flaws. Do not call loop() from within loop()! Aside from the code errors, your question has a legitimate element.

Testing the tri-state behaviour of an input pin will let you know if it is genuinely high, genuinely low, or floating (disconnected). The technique was given in this answer to similar problem I was encountering.

In short:

Connect a large (1MOhm) resistor to each input between the pin and ground, then for each pin:

Turn off internal pullup;
Read value of input pin;
Turn on internal pullup;
Read value again.

If the value changes from the first to the second digitalRead(), the input was not connected to anything. If the value remains the same then it is a genuine value from a connected device.


MQTT on nano with Ethernet shield not working I'm using an arduino nano with an ethernet shield (ENC28J60), and  ethernet eem to be working (I can create a webserver with Ethercard library).However, i'm stuck when i try to connect to a MQTT server.
I tried NanodeMQTT (stuck at waitforlink), Adafruit MQTT Library + Ethernet.h ( MQTT_connect() : Connection failed, endlessly retrying), PubSubClient + Ethernet.h (client.connect return 0) and some others.
At this point i am wondering if i am doing the right configuration each time:

when asked an ip, i set the static one i want for my arduino : 192.168.1.50
when asked an gwip, i set one of wy internet router : 192.168.1.254
when asked for a server, i set it to my mqtt server ipv4 : 192.168.1.185 (and port is 1883)
when asked for a mac adress, i keep the one in the example, or just write a random one

Do you know what can cause the ethernet.h or mqtt library to fail, but still ethercard is working fine ?

Thanks to Juraj pointing me that UIPEthernet is just a replacement for the Ethernet library, I finnally found this article Which works just fine.


How to convert frequency into db I have made an Arduino circuit which outputs in terms of frequency(hz) and I need output in terms of db as well

So is there any formula which can I apply to convert frequency hertz to db or is there any reference link to understand the conversion process.

Any help will be highly appreciated

dB is volume (sound pressure), frequency is pitch. The two are entirely different concepts and can't be converted. A bit like you can't convert the roundness of a doughnut into blue. Roundness and blueness (it has blueberries in it by the way) are two different properties of the doughnut.


Will Funduino Joystick Shield work on a Mega? I am trying to get a Funduino Joystick Shield working with an Arduino Mega and I need to use the WiFi capability. The specs I have found for the Funduino (see https://protosupplies.com/product/funduino-joystick-shield-v1-a/) use the standard UNO pins for the RF24: 9..13, The Mega uses pins in the high 40s for this interface. Is there a way to make this work?

The shield will work on Mega, except of the SPI connection for the nRF24L01 connector. The shield expects SPI on pins 11, 12, 13 and Mega has them on 50, 51, 52. Other shields use the SPI pins on the ICSP header to have compatibility with different boards. This shield doesn't connect to the ICSP header.

You can wire the nRF24L01 to SPI pins on 50, 51, 52.


Blinking 2 LED having input from serial monitor Sir while entering the values on the serial monitor, I ask the user to enter the value for red led voltage(0-255) then again ask for yellow at the red voltage asking it produces the user to  put the value, after that it asks for yellow led input but the time to enter the value for yellow led input is very less and so it does not get entered and the futher program starts. So only red led works where as Yellow does not.

int REDledpin=9;        //RED led on pin 9 of the uno board.
int YELledpin=7;        //YELLOW led on pin 8 of the uno board.
int REDonleddelay=500;  //The red led will be on for 500 ms.
int REDoffleddelay=500; //The red led will be off for 500 ms.
int YELonleddelay=600;  //The YELLOW led will be on for 600 ms.
int YELoffleddelay=600; //The YELLOW led will be off for 600 ms.
int countredled=5;        //The RED LED count variable
int countyellowled=5;     //The YELLOW LED count variable
String red="Red led is blinking";
String Yellow="Yellow led is blinking";
int redintensity;
int yellowintensity;

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

void loop() {
Serial.println(red);
for(int j=1;j<=countredled;j=j+1)
  {
    Serial.print("The red LED blink star: ");
    Serial.println(j);
    analogWrite(REDledpin,redintensity);
    delay(REDonleddelay);
    analogWrite(REDledpin,0);
    delay(REDonleddelay);
  }

Serial.println(" ");
Serial.println(Yellow);
  for(int j=1;j<=countyellowled;j=j+1)
  {
   Serial.print("The yellow LED blink stars");
   Serial.println(j);
   digitalWrite(YELledpin,yellowintensity);
   delay(YELonleddelay);
   digitalWrite(YELledpin,0);
   delay(YELoffleddelay);
  }
 Serial.println(" ");
}

@Juraj was on the right track however the end-of-line characters for example may not be buffered and the problem could continue.

The correct approach is the wait for the end-of-line character specifically.  Let's take the easy way out and use Serial.readStringUntil

#define EOL_CHAR '\n'

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.readStringUntil(EOL_CHAR); // clear serial buffer to end of line character

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

This all depends on what you're Serial Monitor is sending as a new line; it could be CR (\r), LF (\n) or CRLF (\r\n), so change the EOL_CHAR value accordingly depending on your serial monitor setup.


How to program Esp8266 remotly via wifi? I hope it's not a sci-fi for arduino. But I saw that dual system with two MCU can program each other via radio connection. It has been done in experimental space cube projects.
It is theoretically possible? I'm thinking about two arduino MCU first of them will be main MCU and second will be like programming device via serial link.I want to program mcu via wifi without cable connection. Somehow send hex file via wifi to eeprom and upload to second device flash memory.
How do you see this issue? Is that a big nonsense?

The firmware update over WiFi is called OTA update. OTA stands for "over the air".
The esp8266 can OTA update itself. The Arduino library for this is called ArduinoOTA and it is bundled with the ESP8266 Arduino boards support package.
See the example for ArduinoOTA library in IDE Examples menu.
Other MCU have the self update option too. ESP32 has it of course, then for SAMD boards Arduino made WiFi101OTA library. For ATmega I made the ArduinoOTA library based on the WiFi101OTA library so it supports SAMD too. And it doesn't have to be WiFi. Cable works too.
The OTA update stores the uploaded firmware in free part of the flash and after successful upload it moves the firmware to target location and resets the MCU.
For any Arduino with SD bootloader OTA update is possible, because the library only has to store the uploaded firmware to the SD card and reset the MCU.
For small ATmega ftp bootloaders exists. Here the bootloader waits for network upload.
Update over a second MCU solutions are for MCU with less flash, mostly for the ATmega328p. The ESPLink firmware and the WiFiLink firmware for ESP8266 can flash attached ATmega328p over RX/TX. The ESP8266AVRISP can flash ATmega wired over SPI.
ArduinoIDE supports OTA upload. It creates a network port based on MDNS record propagated by the ArduinoOTA library or firmware with OTA support.

Other update way is to download the new firmware from a server or upload it over a web page. ESP8266 has for this ESP8266httpUpdate and ESP8266HTTPUpdateServer libraries. For SAMD, ATmega and other boards my ArduinoOTA library has examples on how to store and apply the update received as download or upload.


Start / end events using milis I want to start a relay, have it run for 3 seconds, stop for 10 seconds, repeat.

I can't use delay, because I have a motor driver starting / stopping every 100 milis.

So I put together this code, but it does not work. Any help appreciated.

There's a 500ms delay to stop too much debugging info.

Also for some reason, tenSecondsBool switches to true as soon as you run the code.

unsigned long threeSeconds=3000; // the time we need to wait
unsigned long threeSecondsMillis=0; // millis() returns an unsigned long.
unsigned long fourSeconds=7000; // the time we need to wait
unsigned long fourSecondsMillis=0; // millis() returns an unsigned long.

unsigned long previousMillis=0; // millis() returns an unsigned long.
bool ledState = false; // state variable for the LED
bool led2State = false; // state variable for the LED
unsigned long tenSecondMilis=0; // millis() returns an unsigned long.
unsigned long tenSeconds=10000; // the time we need to wait

unsigned long paliGasiMilis=0; // millis() returns an unsigned long.
unsigned long paliGasi=1000; // the time we need to wait

unsigned long ventMilis=0; // millis() returns an unsigned long.
unsigned long ventInt=100; // the time we need to wait

bool threeSecondBool = false;
bool tenSecondBool = false;

int Fin1 = D7;

#define enA D1
#define in1 D2
#define in2 D3
#define button 4

int rotDirection = 0;
int pressed = false;

void setup() {
  Serial.begin(9600); // send and receive at 9600 baud
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(button, INPUT);
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  pinMode(Fin1, OUTPUT);
  digitalWrite(Fin1, HIGH);
  threeSecondBool = false;
  tenSecondBool = false;
}

void loop() {

 unsigned long currentMillis = millis(); // grab current time

 if ((unsigned long)(currentMillis - tenSecondMilis) >= tenSeconds) {
    Serial.print("---------------\n");
    Serial.print("10 second end\n");
    Serial.print("---------------\n");
    tenSecondBool = true;
    tenSecondMilis = millis();
}

Serial.print("10 second bool = ");
Serial.print(tenSecondBool);
Serial.print("\n");
Serial.print("3 second bool = ");
Serial.print(threeSecondBool);
Serial.print("\n");

 if (tenSecondBool) {
  if ((unsigned long)(currentMillis - threeSecondsMillis) >= threeSeconds) {
   Serial.print("---------------\n");
   Serial.print("3 second end\n");
   Serial.print("---------------\n");
   threeSecondBool = true;
   threeSecondsMillis = millis();
  }
 }

if (!tenSecondBool && threeSecondBool){
  Serial.print("Both triggered!\n");
  digitalWrite(Fin1, HIGH);
}

if (!tenSecondBool && !threeSecondBool){
  Serial.print("Both triggered!\n");
  digitalWrite(Fin1, HIGH);
}

if (tenSecondBool && threeSecondBool){
  threeSecondBool = false;
  tenSecondBool = false;
  digitalWrite(Fin1, LOW);
}

delay(500);

  if ((unsigned long)(currentMillis - ventMilis) >= ventInt) {
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
    ventMilis = millis();
  } else {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
  }

}

Your code is somewhat confusing, probably because it has too many
variables. For doing what you describe, the program only needs to
remember two things:

is the relay in the ON state or in the OFF state?
when was the last time the relay changed state?

These can be represented as follows:

bool relay_is_on = false;
unsigned long last_relay_change = 0;

Then, I recommend you use descriptive names for your variables and
constants. Calling a constant threeSeconds is not useful. It has no
added value over just typing 3000. Having the constant named
RELAY_ON_TIME makes it a lot clearer what it is intended for. It is a
common convention to name the constants with all caps to make them stand
out relative to variables:

const uint8_t RELAY_PIN = ...;
const unsigned long RELAY_ON_TIME  =  3000;  //  3 s ON
const unsigned long RELAY_OFF_TIME = 10000;  // 10 s OFF

With this in place, periodically switching the relay on and off can be
achieved as follows:

void loop()
{
    unsigned long now = millis();
    if (relay_is_on && now - last_relay_change >= RELAY_ON_TIME) {
        // Turn off.
        digitalWrite(RELAY_PIN, LOW);
        relay_is_on = false;
        last_relay_change = now;
    }
    if (!relay_is_on && now - last_relay_change >= RELAY_OFF_TIME) {
        // Turn on.
        digitalWrite(RELAY_PIN, HIGH);
        relay_is_on = true;
        last_relay_change = now;
    }
}


Task watchdog gets triggered during Bluetooth initialization The board ESP32-Dev-WROOM-32D cannot establish a bluetooth connection due to the task watchdog. Here's my code:

#include "BluetoothSerial.h"
//check if Bluetooth is enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test");
  Serial.println("The device started!");
}

The program runs fine until SerialBT.begin("ESP32test"); where it freezes, and does not continue to run. The message The device started! is not printed. Instead, the task watchdog gets triggered after some time: E (24791) task_wdt: Task watchdog got triggered.

Is there any way to turn off the task watchdog? Or is there any other issue?

SerialBT.begin("ESP32test") is hanging, and because ESP32 doesn't deal well with code that hangs, so it complains about it.
ESP32 runs a Real-Time OS (FreeRTOS).
The fact that it is a real-time OS means that execution of code needs to be guaranteed to finish within a certain time-frame. You'll often see RTOS functions containing the time limit in which that a blocking function should finish executing, such as:
    uart_wait_tx_done(uart_num, 100); // wait timeout is 100 RTOS ticks (TickType_t)

(from ESP-IDF docs)
FreeRTOS comes with a task API. Each task can execute code, but they need to give other tasks the chance to execute code too. I think that when a task blocks, it doesn't allow other tasks to do work on the same CPU. (but I can't find sources to back this up)
setup() runs in one of the RTOS tasks, and when SerialBT.begin() blocks the task for too long, the task watch dog complains that the task is hanging.
If the task is blocked by some kind of looping code, then it generally helps to run vTaskDelay() to yield the task to the task watchdog for a bit.
Because your task is blocked by a single call, there isn't much to do about it, given that SerialBT.begin() doesn't seem allow you to specify when it should time out.


How can I split a string into multiple parts? I currently gather a string via bluetooth to my arduino and the string only has 5 different letters. "HELLO". I now wish to store these individual letters in a string on their own. Right now i have this code:

First I create a single string:

String readString;

Then I read my BTLEserial which is where I get the value that is being sent to the arduino and i store it in my string:

char c = BTLEserial.read();
readString += c;

readString now has the value "HELLO". Now i want to split it and what I have tried is to do it like this:

String stringOne = readString.substring (0,1); //H
String stringTwo = readString.substring (1,2); //E
String stringThree = readString.substring (2,3); //L
String stringFour = readString.substring (3,4); //L
String stringFive = readString.substring (4,5); //O

But with this i do not get the correct values in each string.

Appreciate every help I can get! :)

An array is 0 indexed, which means that number 5 is out of index. "Hello" should be index valued 0-4 and not 0-5.

Here is a better code to try out:

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

void loop() {

String recivedMessage = "";

// Read
while (Serial.available())
{
    recivedMessage += Serial.read();
}

// Print debug
Serial.print("recivedMessage: ");
Serial.println(recivedMessage);

//// Uncomment the row under if you are not sure that the splitting is working
// recivedMessage = "Hello";

// Split
char first  = recivedMessage.substring(0, 1)[0];    // H
char second = recivedMessage.substring(1, 2)[0];    // E
char third  = recivedMessage.substring(2, 3)[0];    // L
char forth  = recivedMessage.substring(3, 4)[0];    // L
char fifth  = recivedMessage.substring(4)[0];       // 0

// Print debug
Serial.print("Cut message: ");
Serial.println(first);
Serial.println(second);
Serial.println(third);
Serial.println(forth);
Serial.println(fifth);

}


Why does the transistor burn out I have an arduino uno which turns on a water pump (12V, 3.6W) once every 10 hours for a few minutes (I've followed this tutorial on how to connect the water pump). To turn on the water pump I used a PN2222A transistor, and connected the base in serial with a 220 ohm resistor to the digital pin 9.
A few minutes after turning on the power on my Arduino UNO the PN2222A transistor burned out (lots of smoke coming out of it).

I also used a 1N4007 diode, cathode connected to the positive pin, and anode to the negative pin of the water pump.

The power supply outputs around 12.6V

Maybe the resistor is too low/weak?

I've created a schematic here, attached it's a snapshot of it.

EDIT1:
Here is a picture on how I connected my transistor. I've removed from the photo:

the input wires (should be top-right of breadboard)
wire to arduino digital pin (should be on h-19 on the breadboard)
water pump from the breadboard (positive pin: c-2, negative pin: h-2)

EDIT2 (a solution that worked for me):

It looks like the input to the arduino (arduino and the pump share the same 12V input, but the arduino's goes through a step down converter to 10V) was a bit loose (to be more specific, the negative pin was loose) and randomly, the arduino would shut down and then the pump would start (maybe because the digital pin becomes HIGH, dont know why though) all while the arduino is shut off. That's when the transistor (PN2222A) burned out. I switched to TIP120 with a 1k resistor as @Jot suggested and looks like when the same problem with the power happens, nothing is burning out :)

TinkerCAD may have mislead you on the pinout for the transistor

TinkerCAD

PN2222A


Weird stepper motor behaviour on RAMPS in arduino Following this tutorial:

http://www.instructables.com/id/Complete-newbie-step-by-step-3D-printer-with-all-p/?ALLSTEPS

I connected DVD stepper motor to RAMPS 1.4 on arduino with Marlin software with this settings:

 //#define DEFAULT_AXIS_STEPS_PER_UNIT   {80,80,4000,500}  // default steps per unit for Ultimaker

 #define DEFAULT_AXIS_STEPS_PER_UNIT {215.12,215.12,8034.69,196.52}

 // #define DEFAULT_MAX_FEEDRATE          {300, 300, 5, 25}    // (mm/sec)

 #define DEFAULT_MAX_FEEDRATE {100, 100, 2, 25}

 // #define DEFAULT_MAX_ACCELERATION      {3000,3000,100,10000}    // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for Skeinforge 40+, for older versions raise them a lot.

 #define DEFAULT_MAX_ACCELERATION {200,200,50,5000}

 #define DEFAULT_ACCELERATION          100    // X, Y, Z and E acceleration in mm/s^2 for printing moves

 #define DEFAULT_RETRACT_ACCELERATION  100    // E acceleration in mm/s^2 for retracts

 #define DEFAULT_TRAVEL_ACCELERATION   100    // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves

I put a video at vid.me (hopefully with sound) showing stepper behaviour when I press +1mm,-1mm,-1mm,-1mm,-1mm,-1mm,-1mm,+1mm,+1mm,+1mm,+1mm  on Pronterface software.

The video you show shows movement of far more than 1mm.  This indicates that the steps per unit is far different than you are configuring the Marlin software for.  With a +/-1mm and 212 steps per mm, there should have been 212 steps sent to your stepper.

Recalculate your steps/mm values and slow down the feed rate to get something reliable.

For experimenting, in Pronterface, set the feedrate of 10mm/sec (600mm/min) or 1mm/sec (60mm/min) to slow things down so you can hear or count the steps with your ear, then choose smaller steps, like +0.1mm and see if you get the planned displacement.  If, at a really slow speed, you don't get the corresponding movement, then your steps/mm need adjustment to match your system.

Eyeballing it, I'd say the called-for 1mm or 212 steps is moving the stage about 10mm, so you would need numbers more like this for the x and y axes:

#define DEFAULT_AXIS_STEPS_PER_UNIT {21 ,21 ,8034.69,196.52}


Lithium Polymer/LiPo set to power Arduinos I want to switch from using disposable 9V blocks to a proper setup of 3.7V LiPolys for all my portable Arduino (Uno/Mega) projects consisting of:

only 3.7V LiPo units
charger
upconverter (to 5V)

My questions:

Is this generally a good idea? Or is there a better solution for portable Arduino power?
How should I actually hook the LiPolys up to the Arduino? They usually ship with JST connectors. Should I use the Vin/GND Pins or should I build my own JST/DC-Connector adaptor? I want to create a robust, pluggable solution.
Am I actually losing power twice that way (once in the upconverter and then in the Arduino voltage regulator)?

If you can get away with it, I recommend not using a boost converter and instead connecting the battery directly to the supply voltage input (the "5V" pin).

The AVR chips used in most Arduinos (but not the Due or Zero [and the Yún and Tre are a totally different kettle of fish entirely]) can operate with anywhere between 2.7 and 5.5 volts, with the ATmega328P found in the Uno able to run with as little as 1.8V. This is a much larger range than the 3.0-4.2V available from rechargeable Li-ion/Li-poly/LiFePO4 cells.

Naturally you will need to make sure that any external components can run with the reduced voltage as well, but quite a few are able to work with anything from 2.0 to 5.5 volts.


Best strategy to parse 5 byte arrays to find a pattern Ok here it goes, my first ever question posted to stackexchange! Please be gentle on me!
I am using an Arduino UNO (at the moment, will move to a faster micro later - but still use an Arduino sketch) to read in data as an SPI slave to extract the display data off of a commercial product that has no other exploitable data output that I can use. I am using a very generic sketch that Nick Gammon posted for the purpose of demonstrating the capability - and I can read the SPI data coming in ok. (Thanks Nick!)
The data is being pulled from a commercial product that has a 8 character, 5X7 dot matrix LED display that was specially made for this product and after exhaustive searches and emails to Broadcom/Avago - has no datasheet, but there are slightly similar products that I was able to use to get a bit of a handle on how the part works, I just went on the assumption that even if the interfaces are not the same, they probably didn't reinvent their command structure. However; the display doesn't have a nice driver chip embedded like your typical parallel LCD display.
I had to do a bit of reverse engineering using a logic analyzer to figure out:

It is SPI data at 4MHz.
The gist of the commands coming in and in what order
Used excel to convert the pixel mapping of the display to the font actually getting displayed on the device.
That the displayed font/text for each of the 8 characters is made up of 5 bytes - where the bit positions of those bites end up lighting a tiny LED in the display so the letter 'H' looks like 0x7F, 0x08, 0x08, 0x08, 0x7F. Each byte controls a column of 7 LEDs, ignoring a row.

Right now:

I am using a modified version of Nick's slave sketch to simply extract the first 44 bytes of the command string to display something on the display
all that is important to me is the 40 bytes after the first 4
because those bytes are what get displayed. I am taking 5 elements of the 44 byte array that I know correspond to a character and spitting them out on the serial monitor such as:
0x00, 0x01, 0x5F, 0x11, 0x00 // i
0x7F, 0x08, 0x08, 0x08, 0x7F // H
etc...

And now after a lengthy introduction - my actual question:
I need to parse the patterns of each of the 5 bytes that makes up a letter and convert it to ASCII text so that the actual word is displayed on the serial monitor.
Back when I used to use another programming language / environment on PICs we had things like LOOKUP and LOOKDOWN which made comparing patterns a bit more abstracted, which is weird considering Arduinos...
I need help coming up with a function that takes the 5 bytes that I need to build each letter from and maybe compares it to an array that represents each possible letter and then maybe passes the matching result to another function to build / concatenate the displayed word out of those characters? That method sounds wildly inefficient, but it's all my little brain can come up with and I'm drawing a blank on how to even do that... I don't need a lot of error checking because thus far the data I'm getting is spot on with what I see on the actual display - we are also talking one 8 character word (max) at a time and it is fairly static, no scrolling words or a lot of chatter - just a single word or some data that changes relatively infrequently. But the displayed data can be different enough than the last to make trying to match entire words out of the question unless it's a side feature to speed things up. I think work properly it needs to work on one character out of 8 - one at a time. Another thought is maybe summing the 5 bytes to determine if we have a match or not, but I'm not sure if two different characters might end up having the same sum? Math is not my strong suit. Thanks for any and all help.

This is really a pure programming problem rather than an Arduino one, but to get you started, you could do a table lookup, like this:
#include <stdio.h>
#include <string.h>

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

unsigned char patterns [] [5] =
  {

    { 0x7F, 0x08, 0x08, 0x08, 0x7F },   // H

    // other byte patterns here

  };  // end of patterns

char patterns_converted [] =
  {

  'H',

  // other letter equivalents here

  };  // end of patterns_converted

char convert_pattern (unsigned char what [5])
  {
  for (int i = 0; i < ARRAY_SIZE (patterns_converted); i++)
    if (memcmp (what, patterns [i], 5) == 0)
      return patterns_converted [i];

  return '?';

  } // end of convert_pattern

int main ()
{

  unsigned char test1 [5] = { 0x7F, 0x08, 0x08, 0x08, 0x7F };
  unsigned char test2 [5] = { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE };  // won't be found

  char x = convert_pattern (test1);

  printf ("Result for test1 is %c\n", x);

  x = convert_pattern (test2);

  printf ("Result for test2 is %c\n", x);

}

You would find out all your bit patterns and put them in the patterns array, and then put the equivalent letter in the patterns_converted array.
The function convert_pattern does a linear search of the table of patterns, returning the corresponding letter, or "?" if not found.
I coded that in pure C++, but since the Arduino IDE basically uses C++ you should be able to convert it for your use.


Can I connect a servo directly to arduino uno without a transistor? I am going to mount an ultrasonic sensor on the servo.

The Arduino's GPIO pins can drive the signal of most model servos directly, without any extra transistors.

Driving a model servo signal input is not the main problem with driving servos from an Arduino.

The main problem is trying to use the Arduino's power supply to power the model servo. With many model servo's, the amount of current the model servo needs to start, or when it is almost stopped is so big that the Arduino's power supply can't maintain 5V. As the Arduino's power supply voltage drops, the Arduino often gets reset, and the program restarts from setup.


I2C master/slave maximum requestEvent message size Using a NodeMCU master and an Arduino slave (Wire.h on both sides), is there a maximum message size (32 bytes?) for the answer that the slave sends from requestEvent()?

If so, is there any solution to circumvent such a restriction WITHOUT the use of other libraries (like I2C_Anything, for example)?

The I2C protocol itself does not have a transmission size restriction. But the implementation in the Wire library only reserves a specific amount of RAM for the buffers. This site mentiones 32 bytes for normal Arduinos (couldn't find the source code currently) and I found 128 bytes for the ESP8266 in the source code.

You cannot have unlimited message length, since the buffer has to hold the whole message and the RAM on normal Arduinos is very limited.

But you can make the buffers of the libraries bigger by changing the corresponding defines in the header files to a bigger value. Keep in mind, that the actual used memory space is with a factor 2, since the buffer size gets used for both send and receive buffer.

If you need bigger messages, than is fitting in the available RAM, you should either change to a board with more RAM, or develop a way to process one part of a message, deleting it and then process the next part (multi part message). Though that raises the question, why the messages have to be that big in the first place.


Setting the sampling rate for timer interrupt I had performance problems with the data acquisition and after some reading on the web, someone told to define a timer with the frequency I need (50hz):

// TIMER 1 for interrupt frequency 50 Hz:
cli(); // Stop interrupts.

TCCR1A = 0; // Set entire TCCR1A register to 0.
TCCR1B = 0; // Same for TCCR1B.
TCNT1  = 0; // Initialize counter value to 0.

// Set compare match register for 50 Hz increments.
OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
// Turn on CTC mode.
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 64 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
// Enable timer compare interrupt.
TIMSK1 |= (1 << OCIE1A);

sei(); // Allow interrupts.

But with that, I was unable to achieve good performance; I was expecting 50 reading / seconds. Luckily, I've changed for 8 bits prescaler instead of 64 and I've start to get better performance:

// Set CS12, CS11 and CS10 bits for 8 prescaler.
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

But, honestly, I'm a newbie and I don't understand why!

// = 16000000 / (8 * 50) - 1 (must be <65536) that 8 in the formula refers to the prescaler. So this formula expect you to have a /8 prescaler. But four lines below you used a /64 prescaler. So your timer runs 6.25 Hz.

When you changed it to /8, you got the correct frequency.


Do external battery packs need to connect to ground on the arduino? I am going to be controlling 2 servo motors with an arduino. I will use an external battery pack for power. Do I need to connect the negative of the battery to ground on the arduino? If I just use the battery pack to power an LED, it works without connecting it to ground. Can someone please explain the logic behind this in simple wording? Thank you

Ground is merely a label. It is a logical point in the circuit relative to which you measure all other voltages against.

For instance the 5V pin on the Arduino is actually 5V relative to the ground pin.

A 12V battery's + terminal is 12V relative to the - terminal. In this situation the - pin can be labelled Ground.

Electricity only ever flows when there is a circuit.  That is, current can only flow when it has some way of flowing back to where it came from.

A battery with an LED and resistor attached has a circuit: Battery -> LED -> Resistor -> Battery.  An Arduino itself is a circuit: Power -> Arduino -> Internal Gubbins -> Power

By the rule above, electricity can only ever flow out of an I/O pin if it has some way of getting back to where it came from. That route back is the Ground pin of the Arduino.  Interfacing some external device with the Arduino, whether it has its own power supply or not, requires that connection back to the Arduino's ground in order for the signal you send from the Arduino to have a complete circuit.


AVR has no vprintf_P? Well this was unexpected. AVR libc has many the variants of printf, including vprintf, but is missing vprintf_P. Is this really just not present or implemented elsewhere?

It has vfprintf_P and stdout is a FILE. Why would you want to waste time and space with implementing vprintf_P as well?

If you really want it, you can make your own:

#define vprintf_P(...) vfprintf_P(stdout, __VA_ARGS__)

Incidentally, the source code to vprintf looks like this:

int
vprintf(const char *fmt, va_list ap)
{
    return vfprintf(stdout, fmt, ap);
}

That does exactly the same job as a preprocessor macro - just forwards your request on to the FILE-based function.

It is actually more efficient to use a preprocessor macro than needlessly nesting functions like that - less stack usage, less calls, etc (unless the compiler happens to choose to inline that function, which since it is in a library it likely won't).

The non-FILE based functions can be considered simple wrapper functions to the FILE-based ones. They are mostly provided for convenience, but are actually completely redundant and can all be replaced with direct calls to the FILE-based variant.  They mostly still exist purely for historical compatibility. And since _P is specific to AVR libc there is nothing historical for it to be compatible with.


Connect 20 12v led to an arduino mega I want to control about 20 leds with an arduino mega.
This leds works with 12v voltage.

I tried to put 20 relays but this solution is not good for me because leds will often blink

I have also tried transistors but it needs to make a pcb.

I am looking for a solution without having to create a pcb

Any idea ?

Thanks

You can use the commonly available L298N module to drive four of your LEDs with each module. That means you would need five of them.

Those modules are suitable for driving either one stepper motor, two DC motors (in both directions), or four "unidirectional" loads such as your LEDs.

The input can be connected directly to your MEGA, but you may need additional series resistors depending on the LED you use (though this likely does not apply for LEDs specified as "12V").

There are also LED driver eval boards available which may suit your needs:
https://www.digikey.de/product-detail/de/adafruit-industries-llc/1455/1528-1019-ND/4990768


How to sample incoming 600khz pin and divide it by 4 and generate low frequency signal at output pin of arduino I am trying to divide a incoming high frequency signal 600kHz by 4 and output wave at arduino MEGA2560 digital pin.

The input to arduino comes from incremental Encoder which is connected to motor that runs at 9000 rpm and the generates 1024 pulses per rotation.
I am trying to downsample the frequency I am getting from arduino to 250kHz or less.
I tried following approaches :

a. I counted the rising edge of the incoming wave and a interrupt is triggered as number of rising edge reaches certain value and ISR toggle an output pin.
b. I tried to get hardware counter work at T0 pin but I was not able to hit ISR when the count has reached specific value.

The problem with approach 1 is: As my frequency of incoming wave increases the output wave starts missing some pulses and generates one half cycle for 6/8/10 pulses of incoming wave. It should actually generate one half cycle for 4 pulses.

Here is approach 2 code:

#define outPin1 10
volatile short encoder = 4;

void setup ()
{
   pinMode (outPin1, OUTPUT);
   Serial.begin(9600);
   cli();
   // reset Timer 0
   TCCR0A = 0;
   TCCR0B = 0;

 }  // end of setup

 ISR(TIMER0_COMPA_vect)
 {
     digitalWrite(outPin1, !digitalRead(outPin1));

 }

 void loop ()
 {
    TCNT0 = 0;      //counter to zero

    // set compare match register to desired timer count:
   OCR0A = encoder;
    // turn on CTC mode:

   bitSet(TCCR0A, WGM01);
   // Timer 0 - counts events on pin D4

  bitSet(TIMSK0, OCIE0A);    // interrupt on Timer 0 CTC
   // start Timer 0
  // External clock source on T0 pin (D4). Clock on rising edge.

   bitSet(TCCR0B, CS02);
   bitSet(TCCR0B, CS01);
   bitSet(TCCR0B, CS00);
}

Please someone help me out with this issue

This is probably too fast to have have software involved in the loop.
You should try to use a hardware-only solution. Note the Arduino timers
should be usable as hardware frequency dividers:

configure a timer to be clocked off the input signal, so that it
behaves like a counter.
configure it for delivering a PWM output with a period of 4 timer
clock cycles and a duty cycle of 50%.

You may try this, but beware I have not tested it:

void setup()
{
    // Configure Timer 5 as a frequency divider:
    //   input: digital pin 47 = PL2 = T5
    //   ouput: digital pin 46 = PL3 = OC5A
    DDRL  |= _BV(PL3);    // set pin PL3 as output
    TCCR5A = 0;           // undo the Arduino core's configuration
    TCCR5B = 0;
    ICR5   = 4 - 1;       // period = 4 timer clock cycles
    OCR5A  = 2 - 1;       // output HIGH for 2 timer clock cycles
    TCCR5A = _BV(COM5A1)  // non-inverting PWM on pin OC5A
           | _BV(WGM51);  // mode 14: fast PWM, TOP = ICR5
    TCCR5B = _BV(WGM52)
           | _BV(WGM53)
           | _BV(CS50)    // clock on rising edges of T5
           | _BV(CS51)
           | _BV(CS52);
}

void loop(){}


What do the charactors " '/2' " mean in the variable declaration? I'm working on an RS485 project, In the CPP file there are const variables declared in the following manner:

#include <RS485_protocol.h>
const byte STX = '\2';
const byte ETX = '\3';

What does the '\2' and '\3' mean?

The '\2' and '\3' are characters with octal code 2 and 3. Which is nothing more then 2 and 3 in octal and in decimal. The author could simply write const byte STX = 2; const byte ETX = 3;.

Characters with ASCII code 2 and 3 are control characters STX (start of text) and ETX (end of text). Control characters are invisible characters used to control the terminal or as mark characters in communication.


Is there a real alternative now to using GSM for data sending? I would like to create an Arduino system that sends the temperature in a place outdoors to a server.

I've read in Internet forums that there might be alternatives to GSM and GPRS technology for sending data remotely, but I'm not sure about them. In absence of WiFi, is GSM the best technology today, even that you have to use the SIM plan to use it?

GSM (or more realistically now, LTE) is really the only option.

Simply put: you need some method of accessing the internet, and unless you create your own local infrastructure that means using the mobile phone system. It's the only system that is virtually everywhere and doesn't require you to install your own communication system.

So that means some modem device that can communicate with the mobile phone system. GSM is what it used to be, although some mobile companies are now deprecating the GSM system and only really providing UMTS (3G) and LTE (what will eventually be 4G), but LTE modems are quite expensive still.

So yes, you need a SIM to do it. You can't access a mobile phone network without one.

One option that could be a cheaper possibility would be to get a cheap second hand smartphone off eBay (or dig out your old one from the bottom of the desk drawer) and use that as your own mobile WiFi hotspot. Your Arduino device connects to the phone with WiFi, and the phone connects to the UMTS or LTE network using a cheap PayG SIM.

LoRA is a technology that is gradually becoming more popular and allows long range wireless communications at low power and low cost. There are areas where LoRA is becoming available, such as in Munich. Should LoRA become available in your area, or should you invest in your own infrastructure, that could become a viable alternative to using the mobile phone network.


How to get elapsed seconds since Jan 1, 1970? I am building a time-critical system using Arduino. Is there any way to get the elapsed seconds like time.h of C in Arduino? I tried time(NULL) but it returns 0. Then moved forward to use now() in Time.h. But the result persists.

How can I get the elapsed seconds since Jan 1, 1970 until now?

An arduino does not have a real time clock (RTC) built in. Every time it restarts it will reset the millis counter.

You will need to add a RTC peripheral that you can poll to find the current date and time.


Level shifting 5V  3.3V My main goal is to use connect the HC-SR04 ultrasonic sensor with ESP8266.

Problem is, HC-SR04 works with 5V while the ESP8266 works with 3.3V
In order to solve this, idea would be to use a logical level converter.

I bought some of this 3.3V 5V TTL Bi-directional Logic Level Converter(s) a good while ago, and thought they would fit best for this project.

Here's my setup

5V from arduino
3.3V from digital power supply
GND connected together
Nothing connected to TX0 (HV side)
Voltmeter connected to TX1 (LV side), still getting a 3.3V

Here's a closer look at the breadboard connections

Am I doing something wrong ? Any suggestions would be appreciated !

Edit: Forget the post above if you just want to know how your board is working. Your board is a retired Spurkfun product - clone.

Here you can see the schematics and all info about your board:

https://learn.sparkfun.com/tutorials/retired---using-the-logic-level-converter

Original post:

The module you got, use the BSS138 MOSFET.
The circuit is easy, and how @Majenko said, it has just 2 pullups:
See https://electronics.stackexchange.com/questions/367052/replace-bss138-with-ao3400a-in-level-shifter-circuit

But this board is really strange: what means TX0, TX1, RX0, RX1 on the same MOSFET? It is better if you can measure it to be sure how to connect the sensor to the TX.

But there is a better way to solve it: Since you just have 1 input to your ESP, why not use 2 resistors?
5V--- 1k --- 2k --- GND
And connect the ESP input between the 2 resistors? It is even faster, because the MOSFET need up to 20ns to change state.


connection between two ARDUINO with xbee I have a setup where two XBEES modules are talking to each other, both using XBEE shields, one attached to an UNO ARDUINO and the other a MEGA ARDUINO. One XBEE sends the data and the other receives it and switch on or off a LED.
The problem is the receiver one don't work.
This is the sender code

int led = 13;
const int bouton = 2; String inputString;
void setup() {
pinMode(led, OUTPUT);
Serial1.begin(9600);
Serial.begin(9600);
digitalWrite(led, LOW);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}
if (inputString.length() >0) {
Serial.println(inputString);
Serial1.println(inputString);
inputString="";
}
}

This the receiver one

int led = 13;
String inputString;
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}

if (inputString.length() >0) {
Serial.println(inputString);
if (inputString == "on"){
digitalWrite(led,HIGH);
Serial.println("LED ON");
}

if (inputString == "off"){
digitalWrite(led,LOW);
   Serial.println("LED OFF");
}
inputString="";
}
}

I get on the serial monitor of ARDUINO UNO what i wrote in the serial monitor of ARDUINO MEGA but the LED don't switch on or off :/

Probably you are getting a new character/carrier return (\n or \n\r) in your receivers' string, that is why it won't match exactly "on" or "off", it will be "on\n", "on\r\n" or similar.


How to read this hmackey for arduino? I understand the HMAC with SHA256 example provides a set of keys:
(https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde)

#include "sha256.h"
uint8_t hmacKey1[]={
  0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,
0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b
};
uint8_t hmacKey2[]={
  0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,
0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19
};
...

I did a bit research and have a sense that these keys are in hexadecimal form with 0x added as prefix. If I like to use my own key, like a string, abece123*, do I just convert the key string to hex?

I tried to use this site below to convert above hmacKey2 to see what the key may look like. But the result is not recognizable. Here's what I did: copy and past

0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,
0x0f,0x10,0x11,0x12,0x13,0x14, 0x15,0x16,0x17,0x18,0x19

to the site below to convert to string.
https://codebeautify.org/hex-string-converter

I am very new to this field. Please help me understand how these key works and and the steps needed to replace one of the preset hmac keys with my own key string (e.g. abece123*). Thanks.

Those are examples for keys. You need one key and you can choose any text with any length.

Did you see this line in the example:

sha.initHmac((uint8_t*)"Jefe",4);

It uses the key "Jefe" with a length of 4.
You can use your own key, but you also need the length.

char myKey[] = "abece123*";
int length = strlen(myKey);
sha.initHmac((uint8_t*)myKey, length);


This logic level converter does not want to work I got this logic level converter to be able to use my lcd but I can't figure out how to get it to work, the problem is that the current is not passing through. This is the model: TXS0108E

Any help is appreciated.

[EDIT]

A few Combinations that I have tried:

And I tried to swap the voltages, same wiring as in the pictures but 3.3v instead of 5v and vice versa.

The TSX0108 doesn't magically provide you with a regulated voltage. You have to provide the voltage, the TSX0108 merely switches it.

As you can see from the datasheet, the basic wiring is:

In the circuit above the 1.8V connection is your 3.3V connection, and the 3.3V is your 5V connection.

You must provide both the 3.3V and 5V power sources.


Am I at the limit of UART transmission time? I'm currently using an STM32F103C8 (With an arduino core) to read 4 sensors at 1kHz, then send that data via UART (at 115200 baud) to another device. Each sensor returns a float, I also include an unsigned long representing milliseconds since boot time. This adds up to be a 20 byte package, that I attempt to send at 1kHz. Sensor sampling is carried out via a timer interrupt, as it is crucial the time between samples is constant.
The data transmission itself (If I send it slowly) takes approx. 70 microseconds. When sped up to 1kHz, it takes approx. 2500. I assume this is because I am filling a serial buffer of some sort.
Is this about the limit of the communication method? If it takes longer than 1000 microseconds to send the data, then presumably the interrupt will trigger before the data is sent and it will have to start again?

At 115200 baud you can send 11520 characters per second. At 20 bytes per packet you can send 576 packets per second. That's 1,736µs per packet.
That's assuming zero wait between bytes. That's not going to happen.
Your measurement of 70µs will just be the time taken to place data into the transmit buffer, and has nothing to do with how long the transmission itself takes.
Roll all that together and the value of 2,500µs per packet is not unreasonable.
To transmit faster you will simply have to run at a faster baud rate.  If you're getting 2500µs per packet currently and a packet takes 1736µs (call it 1,750 for simplicity) then there's about a 750µs overhead per packet to do the actual work of sending the data from the buffer. I'll assume this is a fixed value, though with no knowledge of how the STM32F1 UART works it may not be.
If you want <1000µs then that leaves you about 250µs of time to fit the packet into. That means an equivalent of 4,000 packets per second, or 80,000 bytes per second, or a baud rate of 800,000baud.
1 MBaud is more than possible, and is a good standard baud rate number that most things can cope with. So raising your baud rate to 1,000,000 should allow the communication to happen fast enough.


Refactor to save bytes? I'm a painful 128 bytes of my max for this Trinket. Any refactoring I could do to get down the size?

#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <RTClib.h>

#define LEDPIN 1
#define TONE 4
#define BTNPIN 3

RTC_DS1307 rtc;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, LEDPIN, NEO_RGB);

const long fadeTime = 10 * 60000L; // X minutes
const int colorStops = 255;
const int delaySpeed = fadeTime / colorStops;
const int notes[] = {262,294,330,349};
const uint32_t alarmLength = 5 * 60000L; // 5 minutes

void setup() {
  rtc.begin();
  rtc.adjust(DateTime(__DATE__, __TIME__));

  pinMode(TONE,OUTPUT);
  pinMode(BTNPIN, INPUT);
  digitalWrite(BTNPIN, HIGH);

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  // If it's 5:10 am on a week day, start the fade in
  if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,i));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
         strip.setPixelColor(np, strip.Color(random(50,255),random(50,255),random(50,255)));
      }
      strip.show();

      beep(notes[random(0,3)]);
      delay(100);
    }

    turnOffPixels();
  }
}

void beep(int delayAmount)
{
  for (uint16_t t = 0; t < 30*1000/2; t += delayAmount)
  {
    digitalWrite(TONE,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(TONE,LOW);
    delayMicroseconds(delayAmount);
  }
}

void turnOffPixels() {
  for(int np = 0;np<strip.numPixels(); np++){
    strip.setPixelColor(np, strip.Color(0,0,0));
  }
  strip.show();
}

bool kill() {
  if (! digitalRead(BTNPIN)) {
    turnOffPixels();
    return true;
  } else {
    return false;
  }
}

Error...

Sketch uses 5,438 bytes (102%) of program storage space. Maximum is 5,310 bytes.
Global variables use 97 bytes of dynamic memory.

On a quick test build for an ATmega328p type Arduino, the implementation of random() and its unique dependencies seems to be about 180 bytes, so you might see if there's a more compact way of achieving your need there, perhaps using the low byte of some mathematical expression of the time, and just retrying until you get an in-range value.

Of course if you get really stuck, you could remove the bootloader and program it with ISP from an ordinary Arduino or something like that.


My millis() code doesn't work I am doing a project with bluetooth and an LED. I wrote a code which supposed to turn on an LED after it receives a byte of value 1 after 5 seconds, unless it receive another byte of value 1 (which make it need to wait another 5 seconds) so that if it receive the byte periodically, the LED doesnt turn on, and only turn on if byte value sending is stopped/bluetooth disconnected. I wrote this code and it doesn't seem to work. It doesn't even turn on the LED after 5 seconds. Can you help me spot the mistake here?

unsigned long timebetween=5000;
unsigned long lastreceivedtime;
int value;
bool timerReady = false;

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

void loop() {
  unsigned long currentMillis = millis();
  if( Serial.available() >0){
    value = Serial.read();
  }
  if ( value ==1 ){
    lastreceivedtime = currentMillis;
    timerReady = true;
  }

  if(timerReady) {
    if((unsigned long)(currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
      delay(90);
    }
  }
}

I don't think anything in your code is going to work.
First,
 you are asking the serial.Read to return an integer if it is working.  You might want to change that to a Boolean.

Second,
You are asking for a 1 and only a 1 to make your next if statement true.  If the serial.Read is working the chance it will only return a one, I think is very low

Third,
On the IF statement for setting timerReady. You will set that at a new number each time the program runs through, with the 90ms delay in the last IF statement, it looks like your timer will reset at about every 95-100ms

Fourth,
I think your last 2 IF statements are wrong, I think you want

if(timerReady==true) {
    if((currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
      delay(90);

If you do get this working you might need to set the Boolean back to false and move pin 11 to low at some point.


Will analog servo work with Arduino servo library? I ordered some cheap servos from Amazon before I noticed that there seemed to be two different kinds (digital & analog).

Mine are Tower Pro SG90 Analog (http://www.towerpro.com.tw/product/sg90-analog/)

I was trying to get mine to work with an extremely simple sample code (below) using the Arduino Servo library (using digital pin 3) and I was experiencing the jitters.

I read over the solutions at : https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking

While reading that I learned that there is also a digital flavor of the servo:
http://www.towerpro.com.tw/product/sg90-7/

I'm wondering if that is part of the problem I'm seeing with the servo jittering.  I haven't seen this addressed elsewhere.

My questions are:

Are those servos even different? Maybe that is just a marketing
thing??
Do I need to switch to using an analog pin for the servo data
    connection?
Is it even possible to use the Arduino Servo library for this
purpose or do I need to use some manual code (like analogWrite()) and move the servo to an analog pin?
Or, should it work completely fine and the jittering is just some
unrelated problem?

Here's the simple code I'm using:

#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Jitter can be caused by a lack of power, in which case it will be an irregular pattern that leaves the servo in the wrong place or it can be caused by the increment commands not being sent to the servo smoothly enough.

Have you got enough power for the servo? Where is the power coming from, does this output match the datasheet?

This analog servo requires PWM, so is pin 3 of you board PWM capable?

How fast does you servo rotate?  At the moment you are saying 1degree every 15ms, I suspect that is too slow and that's why the arm is coming to a stop and then rotating again which is making it jitter.


Is there any way I can light up a candle with an Arduino? I want to make a candle flame light up triggered by a microcontroller. Is it possible? I only want to light it up. Not turn it down. Moreover, this is for a one-time use so the candle burning down and becoming shorter is not a problem.

A simple solution is too use nichrome wire which when a current is passes through it will heat up. You could wrap some of this wire around the wick on the candle and then power it either straight from your arduino or you could include a capacitor.
This is much safer than some of the other methods which use potentially dangerous high voltages.

I tested the nichrome wire approach and it works! See following video clip. 2 Ohm resistance and 19V for 1 second.  https://1drv.ms/v/s!AvcBubMtAczvifYZwoESAhUodOoqRA


how to move my robot to the assigned coordinates I am working on an ground surveillance robot using an Arduino mega for programming, am using components like the HMC5883L compass, Adafruit GPS for assigning of coordinates (latitude and longitude) which are the way points, I have written up the code for both the compass and the GPS and am able to get information from them, but now what I want for my robot to move to those specified coordinates (latitude and longitude waypoints) which I don't know how to do please do pardon me for asking such question cause I am new to coding GPS and compass and I would appreciate it if anyone could help me out or explain a bit in details what I need to do please find my code here http://textuploader.com/drqwv

Due to my robot I have been thinking about this problem quite a few times but I never got to coding.  So this is a purely my thinking no experience.

The problem is not only calculating where you are and where to go. The robot needs to move so it needs to know whether it needs to turn (left or right; slow or fast) to drive into the correct direction.
So basically you want a method that takes the compass direction the 2 gps locations and returns a speed and turn value.
The speed and turn value will be different for a waypoint and the final destination. I thought to do so by switching to the next waypoint before coming in the "slow down area". This should make that only one algorithm can handle both situations.
I think the algorithm is likely to look like this.
Given the 2 gps locations calculate the expected compass reading.
Given the 2 gps locations calculate the distance
Based on the distance and the difference between the expected and actual compass reading decide on the speed and turn.

As to the last step there is no "one size fits all" for instance a skid driven robot may opt to turn on the spot until it hits the expected compass reading.
If you have a slow turning robot and you are close to the waypoint you may opt to drive backwards first (like parking a car)

I hope this helps


How to send volume +/- on Mac/OSX from Leonardo I saw this answer but I can't find the analog for Mac.

I've tried cycling thru keycodes from 0x01 thru maybe 0x500, and I went thru ascii a few times, also found brightness up/down, and F11, F12, but they get pressed with fn key by default which makes them do operations other than vol +/-.

Could you just untick the "Use all F1, F2, …" in System Preferences -> Keyboard?

Just wondering if that would be an option and if doing so would create the desired outcome.


Most memory efficient way to program I currently know 3 ways to do a program. Which one of them is the most memory friendly. Note that the example code is simple (blinking a led) and the final code will be VERY VERY complex. Also, the way I code is not the best, so suggest any suggestions in the way to write things or where to put them please.

1- All in the loop. The most basic way of programming.

const int led = 2;
const int interval = 500;
bool ledState = false;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

2- Functions. Similar to the loop but a little neither. Can be splitted into many tabs.

const int led = 2;
const int interval = 500;
bool ledState = false;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  blinkLed();
}

void blinkLed()
{
  ledState = !ledState;
  digitalWrite(led, ledState);
  delay(interval);
}

Then finnaly, objects. The most supreme of them all (and the one that I know the least). I like objects and classes because multitasking with it is much easier. It is more flexible too. Code taken from here.

class Flasher
{
  // Class Member Variables
  // These are initialized at startup
  int ledPin;      // the number of the LED pin
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int ledState;                 // ledState used to set the LED
  unsigned long previousMillis;   // will store last time LED was updated

  // Constructor - creates a Flasher
  // and initializes the member variables and state
  public:
  Flasher(int pin, long on, long off)
  {
  ledPin = pin;
  pinMode(ledPin, OUTPUT);

  OnTime = on;
  OffTime = off;

  ledState = LOW;
  previousMillis = 0;
  }

  void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(ledPin, ledState);   // Update the actual LED
    }
  }
};

Flasher led(2, 500, 500);

void setup()
{
}

void loop()
{
  led.Update();
}

So, which is the best out of those 3.

That is an incredibly hard question to give a definitive answer to.

In general using OO consumes more memory, but that is the price you pay for greater flexibility and ease of use. The difference is usually minor though. Variables within an object take the same amount of space as variables outside an object. It's just the overhead of instantiating the object itself that adds to the memory usage, and that can be quite small, depending of course on what the object does.

Calling functions increases memory use on the stack. Every time you call a function the return address and a number of the internal CPU registers, along with some of the parameters, get placed on the stack. The deeper your function calls go the bigger the stack gets. But that is all temporary - as you leave the functions the stack shrinks again.

However, this is where it gets more complex:

The compiler performs optimizations. One of them is to consider functions for inlining. This replaces the function call with the content of the function that is being called. It makes for a slightly larger program, but it's a program that runs faster and uses less stack.

In your first two examples, because there is only one call to the blinkLed() function, the compiler will see that as a good candidate for using inline. So your first and second programs may well both end up exactly the same.

There are times, as well, where variables that you declare don't actually ever exist. For instance, if you use a couple of temporary variables to do a few calculations in a function and then return the result the compiler may instead just use CPU registers to store the temporary values instead of allocating variable space in memory.

So it is very hard to say "this is better" or "that is better". Instead you should pay more attention to how and where you declare and use your variables.

In general there are two rules:

Keep your variables the smallest size possible for the contents (use 8 bit variables instead of int for storing smaller numbers).
Keep the scope of variables as small as possible.

The latter is often overlooked. The scope of a variable is the block (delimited by { and } for example) where the variable is declared. Anything inside that block, including sub-blocks, can see the variable. By keeping the variable in as small a scope as possible you increase the chances that the compiler will choose to use CPU registers instead of allocating memory.  For example:

int i;

for (i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (i = 30; i < 2000; i++) {
    .... do something else ....
}

That is pretty much guaranteed to allocate memory for i.  However:

for (int i = 0; i < 1000; i++) {
    .... do something ....
}

.... other things ....

for (int i = 30; i < 2000; i++) {
    .... do something else ....
}

With that method the variable i will only exist within the first loop, after which it disappears. It is then recreated as an entirely new variable for the second loop. It doesn't need to stay in memory in between. The compiler may just place it in internal registers, or it may reuse the same block of memory, etc.

Also by keeping scope as small as possible you increase the ability of the compiler to re-use the same bits of memory for different purposes. 10 integers in different scopes doesn't mean 20 bytes of memory - it may mean just 2 bytes for all 10 integers.

So as you can see managing memory effectively can be a bit of a black art at times.


Blutooth shield LED control I am trying to control a led ON/OFF using Arduino UNO and a Bluetooth shield

I have this

which is based on hc-05. The tutorials I found about hc-05 are not working for me. I have the hc-05 embedded in the shield and I did not  find any tutorials  for this shield.

Here is my code (it is working when I use the USB serial ctrl + shift + m).

void setup () {
pinMode( 13, OUTPUT );
digitalWrite(13,LOW);

Serial.begin( 9600 );
Serial.println( "Ready" );
}

void loop() {
if ( Serial.available() > 0) {
    int inByte = Serial.read();

    switch ( inByte ) {

        case '0':
            digitalWrite( 13, LOW );
        break;

        case '1':
            digitalWrite( 13, HIGH );
        break;

    }
 }
}

I connected my android phone to the shield successfully using blurterm2. When I send 1 or 0 nothing happens. What am I missing?

Have you tried the turning just running a simple program to check if the led still works, such as

void setup () {
pinMode( 13, OUTPUT );
}
void loop() {
 digitalWrite( 13, HIGH );
 delay(1000);
 digitalWrite(13,LOW);
 delay(1000);
}


most effective ( progsize/speed ) SD card usage I am making a project with several modules and libraries involved. I just tested the SD lib example, and got a binary at ~14KB  - way too much. I'd like the SD bits to go below 8KB, since it's just for logging from an NFC and RTC module. I notice some 'stabs' debug bits in my Makefile, and wonder if I could do something with that. Besides that, perhaps the experts here can recommend a smaller library for my SD bits, so I won't exceed my ~27KB flash capacity. I am using the SD example for creating/deleting files. Ask me to clarify if needed.

For AVR + SDCard you should check FatFs from Chang. It is widely used and proven C library. You can tweak the configuration file to get minimal size (8K shall be easy). Check wrapper library for Arduino here (6K with default options).

There is also even smaller version called Petit FAT (2-4K) but it doesn't support file delete feature.

If you would like to get smallest possible code, there is option to use Atmel Studio for programming Arduino boards, but you will loose the convenience of Arduino libraries (re-implement the libraries or find AVR versions of them, work with registers directly etc).


How do I turn a number of pins to high and then off after 5 seconds based on a serial command I have an Arduino sketch where I'm sending commands over serial, and as a result turning pins from low to high. What I'm looking to do is have those pins turn high for 5 seconds and then turn back to low. I was looking for a time or scheduling library for Arduino that allows multiple timers at once and lets you pass a parameter (at least I think that's what I need).

In other words, I would like to implement a "doAfter" method and pass the function it is calling a pin number.

Have you tried the delay() function? Try putting this in the loop() function for pin 3.

digitalWrite(3, HIGH);
delay(1000); // time in milliseconds as parameter
digitalWrite(3, LOW);


What are the best GPIO pins to use for my project? I'm working on a home automation project to control my Sommer Base+ garage door opener through Home Assistant.

The project consists of a WeMos D1 Mini with two reed switches (to detect door open/closed) and a 5V relay to control the door opener.

When the door is open the 'top / open' switch is triggered, giving a status of open. Likewise when the door is closed, the 'bottom / closed' switch is triggered, giving a status of closed. When neither switch is triggered (i.e. when the door is in motion), the status is either opening or closing, depending on the previous status.

This works fine unless the WeMos is powered up while either reed switch is closed (so if the door is open or closed).

I know this is because D3 and D8 GPIO pins for the open/close sensors and those can put the device into boot mode (I think that's what it's called).

What I want to know is which pins are the best to use for this project.

Is it possible for me to just change to pins ?? and ?? without needing to update my code?
Is it possible that the WeMos D1 Mini isn't a good fit for what I want?

NodeMCU and "Wemos D1 R2 and Mini" esp8266 (esp-12) pins and io overview

Serial

RX io3 RX0

TX io1 TX0

boot config pins with pullup or pulldown on board

D3 io0 PULLUP (LOW for boot to flashing mode)

D4 io2 TX1 PULLUP (Serial1 TX. no RX for Serial1)

D8 io15 PULLDOWN (SS pin if esp8266 is SPI slave); TX if Serial.swap()

untroubled GPIOs with optional function for I2C or SPI bus:

D1 io5 default pin for I2C SCL

D2 io4 default pin for I2C SCA

D5 io14 SPI CLK

D6 io12 SPI MISO

D7 io13 SPI MOSI; RX if Serial.swap()

RTC pin for timed deep sleep wake-up (if connected to reset pin)

D0 io16 - optional internal pulldown, internal pullup not available

not useable: on NodeMcu Sx pins io 6 to io 11 connect QIO SPI flash memory
(in a very special setup the SPI bus can be used with other SPI device)
(in other very special setup the QIO pins can be used as gpio)

note: most digital IO start as INPUT_PULLUP


Can the servo pulse width range be changed? I recently found that standard servos only rotate 90deg total rotation for a pulse width range of 1-2 usec.  To rotate 180deg total rotation they need a .5-2.5 usec pulse range.  The arduino is programmed to only output the 1-2 usec range for 0-180 deg rotation.  Is there a way to make the arduino output the .5-2.5 usec pulse range to get full 180deg rotation?

Thanks

The Servo Attach method has two forms,

servo.attach(pin)
servo.attach(pin, min, max)

In the latter form, you can specify values for the min and max microseconds that servo.write() will use to represent 0° and 180° respectively.

Note, default values are 544 μs and 2400 μs, which is not so different than the range you say you want, so perhaps some other problem is afflicting your setup.

Also, as explained in my answer to question  “Change Servo Speed With RedBearLabs BLE Shield”, you can issue servo.write(value) calls with value in microseconds instead of in degrees, which may allow more precise control.


Is this Arduino UNO running at 12 MHz? I am wondering if this Arduino UNO R3 clone is clocked at 12 MHz instead of the standard 16 MHz? On the board, you can see there is 12.000 written on the crystal oscillator.

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

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

The 12MHz crystal is for the USB interface.

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


How can I fix stuttering motors that are connected to ESC's [Arduino Uno]? Been making a few posts about my drone and i am getting closer and closer to my goal to make it work.

Right now I have a problem with stuttering with all four of my motors (sometimes the motors does not even start but they beep instead). This is the motor and esc I use: https://hobbyking.com/en_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I put together a very quick schematic on how i have everything connected:

So motor connected to the ESC and the ESC grounds go to arduino Gnd, the signal pins from the ESC goes to different pwm pins and the rest of the esc goes to the power distribution where i also insert my 3s lipo battery. From my power distribution i connect two cables to my arduino uno gnd and vin pin.

When I use this very simple code:

ESC9.write (100);
ESC6.write (100);
ESC5.write (100);
ESC3.write (100);
delay (2000);

ESC9.write (0);
ESC6.write (0);
ESC5.write (0);
ESC3.write (0);
delay (2000);

The motors start like they should but they stutter (some motors move more than others) and as you can see in my code i tell them to stop after 2 seconds to see if i can control them and indeed they stop nicely.

This is a 3 second video on how it looks once I enter my lipo battery:

https://vid.me/XpWg

Is this a case of bad soldering somewhere perhaps or do I need to calibrate my ESC/motor? Codewise I am just using a simple Servo and then I just use the code I posted above. Do I need to add anything else maybe? Since all 4 motors are stuttering/buzzing it is most likely not a problem with the motor/esc i suppose!

My arduino uno is a chinese copy, could that have anything to do with it?

Also I made this post earlier with a little less information but more info about my soldering: All four of my ESC motors stutters when I run it on my Arduino, how can this be fixed?

Appreciate every help and tips!

It isn't clear from your diagram or the video what wire thicknesses you've used or precisely how currents are being routed, or how big your battery is.

Let BPG denote the ground terminal on the battery pack, and BP+ the battery's positive terminal.

There should be heavy wire from BPG to the ground pin of each ESC.  There should be a signal wire (that is, heavy or light, makes little difference as long as motor currents have their own heavy wires to follow) from BPG to an Arduino Gnd pin.

There should be heavy wire from BP+ to the positive voltage pin of each ESC.  There should be a signal wire from BP+ to Arduino Vin.

There should be signal wires from Arduino PWM outputs to ESC PWM inputs.  There should be heavy wires from ESCs to motors.

Also, in your code try changing 100 on up to 200 or 250 (or near whatever the ESC maximum setting is) to see if problem persists at higher levels of PWM drive.  Also if your battery pack is small, add some more packs of the same voltage in parallel, or try a heavier-duty pack.

Edit 1: Check whether each of the motors can work ok by itself.  That is, either comment out three at a time, or use if-statements that check button or jumper settings.  If all the motors work ok singly, try them in pairs or triples.  There are six different combinations of motor pairs, so rather than trying all six of those you might first try the four different sets of three motors at a time, and if that reveals a combination of three motors that fails, try the pair combinations among those three to see if there is some interaction between two motors.  If problems occur when testing with fewer than four motors, try swapping motors on to different ESCs, to find out if the problem is due to a motor, an ESC, or the battery.  (You can also swap motors on ESCs and test all four at once, but testing with fewer motors going should provide a more systematic problem solving method.)


What could I use to vary the temperature of a Heating Pad? Could I get something like this, a 12v silicone heating pad, and vary its temperature with an arduino somehow?

http://www.banggood.com/Waterproof-Silicone-Flexible-Heating-Pad-6060MM-DC-12V-10W-p-972464.html

My grand plan is to put temperature sensors on it and make it hit a certain temperature, and make it hotter/cooler to try and reach a target temperature.

In principle, I don't see any problems. Your heating pad uses 12V and 10W, which means it would be consuming slightly less than one amp of current. The MOSFET you linked can go up to 5A (needing a heat sink with over 1A).

You could use PWM (there are 6 pins on a Uno that can do that) to provide pulse-width modulation to control the amount of output you give to the heater.

You would, of course, need to measure the heat of the device to work out when to adjust the PWM output. You might look up using a PID algorithm to adjust the PWM output depending on the sensed heat input.

References:

pid
pwm
mosfet
sensors


Arduino and DC Motor control board I've this PWM Module - 6V-90V 15A Pulse Width PWM DC Motor Speed Controller Switch which I use to control a peristaltic pump (ordinary DC motor), now I want to replace the potentiometer with an Arduino in order to create a soft-start for the pump by pressing a button.
The control is a 0-5V input from the potentiometer, and the description says "you can external drive" and "It could use of PLC controls speed of motor", unfortunately I cannot provide datasheets or schematics.

Is it possible? Or I need a digital pot?

How should I wire it? The 3 cables from the board to the pot are: ground, 0-5V and 5V

Or you may exchange the whole controller with a power mosfet module connected to your arduino. And use pwm directly from your arduino.
http://store.arduino.cc/product/T010020


ESPTool 3-run stub fail error I'm trying to program my NodeMCU ESP8266 ESP-12E module with AT commands. However, whenever I try and flash to my ESP8266 using ESPTool, I get a 3-run stub fail error. Can anyone tell me why I get this error and how to fix it?
I have my suspicions that it might be the fact that I haven't pulled any of the pins, but I've been told that GPIO0, GPIO2, GPIO15, and CH_PD are all already pulled to the proper positions by default. If that may be the reason behind this error, could someone explain to me how exactly I should pull the pins, whether it be with a circuit or through code?
If it helps, I'm trying to follow along with this resource.
The only thing the ESP is connected to is the computer with USB.

Just wanted to update and let anyone who had a similar issue learn how I solved the problem.
My baud rate was set to 1152000 rather than 115200. Setting it to 115200 solved my problem.


Static ip for esp8266 based on gateway I'm new to Arduino programming. I want to make my esp8266 get static IP based on gateway.
I mean if gateway is 192.168.0.1 then it should get 192.168.0.15 as static IP. And if gateway is 192.168.1.1 then it should get 192.168.1.15 as IP.

You can either set the router to allocate a static IP based on your esp8266's MAC address, or go the DHCP-way first, read the gateway IP address you got, and then do a WiFi.config(), something roughly like this (untested):
WiFi.begin(ssid, password);
IPAddress ip = WiFi.gatewayIP();
IP[3] = 15;
IPAddress dns(8, 8, 8, 8);
WiFi.config(ip, WiFi.gatewayIP(), dns, WiFi.subnetMask());

It is a bit of a trick, and not pretty, and you don't get to set the DNS as provided by the DHCP, because there is no getDNS(), for some silly reason, hence the use of Google DNS.
Note that when doing this, you run the risk of setting the esp8266's IP address to an address already taken by another device on the same router.


Listen for specific frequency I’m trying to build a custom baby monitor for my wife who is deaf. It needs to detect loud noises and listen for a specific series of tones from a feeding pump our daughter uses.  It will then send a radio signal to the other room to trigger a bed shaker.

I do have a loop which samples the MAX4466 microphone and uses a “peakToPeak” calculation to determine volume, which I can use to trigger for loud noises (pasted below).  However, I cannot figure out how to determine the frequency of a noise sample.  I’ve tried searching for other sketches and tutorials that would work, but haven’t found anything.  The feeding pump, when it has an error puts out a series of tones which alternates between 4.1 kHz and 2.1 kHz.   What I wanted to do is see if the first tone is sounding, and then if the second tone shows up within a couple seconds afterwards, then it would trigger sending the signal to the other device.

I’ve tried for two days now to find a way to determine the frequency, but haven’t figured it out.  Any help would be greatly appreciated.  The closest I was able to get was this: Instructables - Arduino Frequency Detection, but when I use this script, the Arduino can no longer do analogRead() to get the status of various setting knobs and such I have on the device.

The script I use to get the sound level / loudness is:

  #define micPin 0                      // Microphone
  const int sampleWindow = 96;          // Sample window width in mS (50 mS = 20Hz)
  unsigned int sample;
    while (millis() - startMillis < sampleWindow) {
      sample = analogRead(micPin);
      // Check peakToPeak mins and maxs
        if (sample < 1024) {
          // toss out spurious readings
           if (sample > signalMax) { signalMax = sample; }          // save just the max levels
           else if (sample < signalMin) { signalMin = sample; }     // save just the min levels
        }
    }
    peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude

As stated in previous answers, frequency measurement is unlikely to be
reliable because the microphone is going to pick up ambient noise, which
is a combination of many individual frequencies. You want instead to see
how much sound amplitude you have at the specific frequency of the
feeding pump. Fourier analysis seems like the natural tool for the job.

However, a Fourier transform is heavy math, and overkill for your
application. You are only interested in the Fourier amplitude at one
specific frequency. Computing that single amplitude is way easier and
faster than doing a full-fledged Fourier transform.

My preferred method for doing that is called homodyne detection. It
is fast enough to be done in real time by an Arduino Uno sampling at
9.6 kHz. Basically you multiply the input signal by both a sine and
a cosine at the target frequency, then you low-pass filter both
products. The two resulting signals are the real and the imaginary part
of the complex amplitude you are looking for.

Here is a small program of mine that does almost exactly what you are
looking for: homodyne.ino. It is set for one specific frequency
(1 kHz, but it's trivial to change), and you will have to adapt it
to be able to change the target frequency between 4.1 and 2.1 kHz.


Arduino library creation - Calling library and Merging I am new to creating a library in Arduino. I was able to create a library from YouTube. I want to merge two other libraries into the library I created. Can you please help me to do so?

I already created a keywords.txt file for my library but the keywords are not getting highlighted in orange in the IDE. But it identifies as keywords.

Please guide me how to properly create a keywords file and merge the libraries.

Keywords below:

# -----------------------------------------------------------------------------------
# Syntax coloring for IotBlueEmon library
# -----------------------------------------------------------------------------------

# Datatypes (such as objects)
CurrentSense KEYWORD1

#Methods / functions
begin   KEYWORD2
Counter1   KEYWORD2
Counter2   KEYWORD2
counter3   KEYWORD2
getCNT1   KEYWORD2
getCNT2   KEYWORD2
getCNT3   KEYWORD2

# Constants

If you consult the Arduino Library Specification's section on keywords.txt:

  A tab should be used to separate each name from the KEYWORD1/Keyword2/Literal1 identifier.

A true tab character is required, rather than spaces, as you have in your keywords.txt. It is common for text editors to be configured to add a given number of spaces when the tab key is pressed rather than a true tab character. That's great but in this case you will need to be sure that the tab character is used.

Note that the tab requirement will be relaxed in the Arduino IDE 1.9.0 release, which will also accept space(s) as a keywords separator but it's still best to use tabs for backwards compatibility since people will be using pre-1.9.0 IDE versions for years to come.


Subtraction with doubles returning zero erroneously I have a function that takes as parameter some doubles and does a subtraction operation on it. However I'm getting a result of 0 when one of the parameter is 0 for some reason.

int calcPID(double current, double desired, double k){
  double diff;
  diff = desired - current;
  Serial.print("desired = ");
  Serial.print(desired);
  Serial.print(", current = ");
  Serial.print(current);
  Serial.print(", diff = ");
  Serial.println(diff);
  int r = (int)diff;
  return r;
}

Output

desired = 250.00, current = 1.69, diff = 248.31
desired = 250.00, current = 0.00, diff = 0.00

When the current is 0.00 the result (diff) is also 0.00, when it should be 250. Can someone tell me what's going on?

You are not providing the input values in the correct type:

calcPID(0.00, 250, 0.0);

will return 0, while

calcPID(0.00, 250.0, 0.0);

will return 250

UPDATE

Here you can get a working test case: it's running on a different processor, so don't expect to behave exactly as the 8bit MCU at Arduino's core.