FFT library for Arduino 101? I am currently trying to get a real-time FFT working for a project on an Arduino 101 which uses the Intel Curie chip. All the FFT libraries (if any) seem to be for the Arduino Uno and architecture dependent (most of them have assembly stuff for optimization).

I was wondering if there is any robust, up do date and most importantly working (with the latest Arduino 101) library. I have tried the PlainFFT library which I read might be compatible with the Arduino 101 (https://forum.arduino.cc/index.php?topic=409791.0).

However this library seems to be out of date, using old extensions of sketch files and old library names in its code (I could not get it to work). Alternatively I wanted to try and tailor a pure C code such as https://github.com/jtfell/c-fft, which seems to have its own Makefile for compilation (this one uses a C99 compiler). I could compile and use this code on a Linux terminal but I am not sure how to go on about making it run inside an Arduino sketch.

I used lightweighted KissFFT (Mark Borgerding) at Arduino Mega and seems it is pure C code so should be running anywhere.


Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan This question is not same as the other one and this is more about employing the pwm signal to drive a CPU fan;

I am trying to follow the answer by Edgar Bonet on the question Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4 and use this pwm signal to control the speed of a 4-wire cpu fan(with black, yellow, green and blue wires);

Following is my updated code for generating the pwm signal on timer 4

void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4C1)  // non-inverted PWM on ch. C
          | _BV(WGM41);  // mode 10: phase correct PWM, TOP = ICR4
    TCCR4B = _BV(WGM43)
         | _BV(CS40);   // prescaler = 1
    ICR4   = 320;      // TOP = 320

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

I have connected pin 8 on the mega to the pwm input on the fan(blue wire) but I dont see any variation in fan speed and fan seems to run at full speed;

I dont really have any means or tools to verify if its really generating a 25khz pwm signal but fan speed is not changing or if its not generating a 25khz pwm signal because of which there is no change in the speed of fan;

I am stuck at this point and any help on this would he highly appreciated;

I've just tested your setting with older "Alpine 64 GT" CPU Fan and it works as expected. I've just added parsing integers sent from serial monitor, so I don't have to change code anymore.

void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
      analogWrite25k(w);
      Serial.println(w);
    }
}


How to connect GPS Neo-6M module to GSM Shield SIM900 V2? I'm doing my final year project, My project is based on "Arduino Real Time Gprs/Gsm & GPS Tracker". So Now I have purchased the hardware components such as:

Arduino UNO R3
GSM Shield SIM900 V2.0
Ublox GPS Neo - 6M Module

I'm a begginer to this project, I have a doubt connecting these components together. I have stack the GSM Shield with the Arduino Uno but I don't know how to connect the GPS module to the GSM Shield (How to wire the components). because as you see my pic you might see on the top of the GSM shield there are no female headers except one which comes for the display.

So do I need to implement a female header on the GSM Shield and solder it to conncet the GPS module?

Can't I connect the GPS module to the GSM Shield's UART Pins?
Please Help me Guys :)

For your program, I'll highly suggest to use softwareSerial. It pretty much emulates the serial communication on other pins (NOT PIN 0 & 1). Then connect it like if you would normaly connect an UART device to your Arduino on the 2 other pins that you chose (NOT PIN 0 & 1). This should make it easy to prorgam your Arduino while having the GPS and GSM module connected to your Arduino.

The shield can cause problems if it uses Tx and Rx on pins 0 & 1, WHICH ARE THE PINS NOT TO USE IF YOU USE SOFTWARE SERIAL, so you might as well connect it with jumper wires. Take the TXs from both of your module and connected to whatever GPIO you want and do the same to the RXs, NOT ON PIN 0 & 1.

Once again, softwareSerial is NOT ON PIN 0 & 1.


making a digital dice i'm trying to make a digital dice to play catan with, here's what i have so far

#include <LiquidCrystal.h>
#include <DFR_LCD_Keypad.h>

// this is factory config shield initialisation
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// initialise the keypad
DFR_LCD_Keypad keypad(A0, &lcd);
int lcd_key     = 0;
int abc_key_in;
int read_LCD_buttons;
int  diceOne;
int  diceTwo;
#define btnSELECT 4
int read_LCD_buttons()
{
  abc_key_in = analogRead(0);
if (abc_key_in < 790) return btnSELECT;}
const int button = 4;
const int BUTTON4LOW = 400;
const int BUTTON4HIGH = 650;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i
}

void loop() {
  int reading =  analogRead (A0);

  lcd_key = read_LCD_buttons();

 if (reading<BUTTON4LOW && reading<BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

  if (diceOne + diceTwo == 7) {
    lcd.clear();
    lcd.setCursor(7, 0);
    lcd.print("7");
    lcd.setCursor(3, 1);
    lcd.print("The pirate");

      if (diceOne + diceTwo == 3,2,1,5,4,6) {
          lcd.clear();
          lcd.setCursor(7, 0);
          lcd.print("fish");
      }
      }
  }
}
}

and im running into a error code saying

Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons'
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'int read_LCD_buttons()':
demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void setup()':
demo_simple:28: error: 'i' was not declared in this scope
   i
   ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void loop()':
demo_simple:34: error: 'read_LCD_buttons' cannot be used as a function
   lcd_key = read_LCD_buttons();
                              ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: At global scope:
demo_simple:58: error: expected declaration before '}' token
 }
 ^
exit status 1
'int read_LCD_buttons()' redeclared as different kind of symbol

You have

int read_LCD_buttons;

int read_LCD_buttons()
{
//..
}

You can't have a variable int read_LCD_buttons at the same time as a function called read_LCD_buttons -- this identifier is already taken. It looks however like you're not assigning or reading anything from this variable, so it probably never should have existed in the first place -- deletion is the solution.

In the case that you wanted to write a function prototype (which you by the way don't have to write in the Arduino IDE because it autogenerates them), the correct form would have been

int read_LCD_buttons();

i.e., the exact same prototype ended by a ;.

In setup() you have a random i which doesn't belong there.

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i //delete this line
}

Finally, you have a mismatch of opening and closing curly braces. Always format your code correctly, so that these errors are more easily spotted! You have one final } too much.

void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");

      if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
        lcd.clear();
        lcd.setCursor(7, 0);
        lcd.print("fish");
      }
    }
  }
}
} //This } is too much!

Then you'll also see that the third if statment which checks for a sum is actually within another expression where it was asserted that the sum is already 7. Then the inner if can never become true. You probably meant to move the if to the outer part, i.e. write

void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");
    }
    //the line below is still wrong
    if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("fish");
    }
  }
}

Next, this expression makes no sense.

if (diceOne + diceTwo == 3,2,1,5,4,6)

I think you meant that "if the sum of diceOne and diceTwo are equal to either 3, 2, 1, 5, 4, or 6 (i.e. within 1 and 6 inclusive), then do something.

Using multiple or statments this would be expressed as

if ((diceOne + diceTwo == 3) || (diceOne + diceTwo == 2) || (diceOne + diceTwo == 1) || (diceOne + diceTwo == 5) ||(diceOne + diceTwo == 4) || (diceOne + diceTwo == 6))

Or using the simpler interval check, assuming both numbers are positive and greater than 1.

if( diceOne + diceTwo <= 6)

Also this expression is suspect

if (reading<BUTTON4LOW && reading<BUTTON4HIGH)

When you have a LOW and a HIGH boundary and you want to check if reading is between these, you would write it as "if reading is greater than the lower boundary and less than the higher boundary", i.e.,

if (reading > BUTTON4LOW && reading < BUTTON4HIGH)


Why does the Arduino UNO have a separate power port if USB also powers it? Can you power the Arduino off a USB cable alone, without using the regular power connection? If so, what's the point of the additional power connection: to provide extra power?
Also Why not just have two usb ports one for power one for connecting to the computer, or a micro usb.

Can you power the Arduino off a USB cable alone, without using the
  regular power connection?

You can use the USB cable alone to power the board.

  If so, what's the point of the additional power connection: to provide
  extra power?

You can use either to power the board. By using just the power plug you can make your Arduino portable by using a battery box or power it via a wall plug.

  Also Why not just have two usb ports one for power one for connecting
  to the computer, or a micro usb.

Only ONE USB is needed to power and program.


Avoid overflowing of counter I have a global uint32_t that keep tracks of used Bytes:

uint32_t usedBytes;
int bytesWritten;

byteWritten = myFile.print(data, FILE_WRITE);

if (byteWritten > 0) {
  usedBytes += bytesWritten;
}

What happen if usedBytes is close to the maximum (0xFFFFFFFF)? Will incrementing it make it 0, or stuck at 0xFFFFFFFF?

It will wrap around though 0.

0xFFFFFFFF + 1 = 0

You can add a higher order word to track more data:

if (byteWritten > 0) {
    uint32_t newUsed = usedBytes + byteWritten;
    if (newUsed < usedBytes) {
        fourGigsUsed ++;
    }
    usedBytes = newUsed;
}

Or you could use uint64_t to automate it - however none of the Arduino print routines cope with the uint64_t variable type.


Arduino IDE with ATtiny85 error "multiple definition of `__vector_5" I am having a problem compiling the code for my ATtiny85 circuit.

I am using the timer/counter0 in normal mode so that when it overflows it triggers the TIMER0_OVF_vect ISR. When I have that ISR in my code, it wont compile and gives this error:

wiring.c.o (symbol from plugin): In function `__vector_5':
(.text+0x0): multiple definition of `__vector_5'
sketch\Glove_heater_v1.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board ATtiny25/45/85.

Maybe I just need to use a different name for the ISR?

My Code:

//Red LED on PB0
//Blue LED on PB1
//Pushbutton PB2
//Battery voltage divider PB3
//Mosfet control PB4

#include <avr/io.h>
#include <stdint.h>
#include <avr/interrupt.h>

volatile uint8_t checkVoltage = 0;

void setup() {

   DDRB = 0b0010011; //set PB0,PB1,PB4 as output, PB2,PB3 as input
   PORTB = 0b00000011; //set PB0,PB1 HIGH so LEDs are off, other pins LOW

   //Setup TC0 for overflow interrupt trigger
   TCCR0B |= 0b00000101; //clk/1024 prescaler
   TIMSK |= 0b00000010;  //set TOIE0 enable overflow interrupt
   sei();
}

void loop() { //do nothing in this test code

}

ISR(TIMER0_OVF_vect){ //Timer/counter0 interrupt check voltage
   checkVoltage = 1;
}

Any ideas are appreciated!

The error message was:

  wiring.c.o [...]: multiple definition of `__vector_5'
  Glove_heater_v1.ino.cpp.o [...]: first defined here

__vector_5 is TIMER0_OVF_vect. So you have one definition of this
ISR in your sketch, and another one in wiring.c. This wiring.c is part
of the Arduino core. As KIIV puts it in a comment, it uses
TIMER0_OVF_vect for timekeeping (millis(), micros() and
delay()).

You have two options for solving this:

you can use the other timer (Timer 1) in your sketch, and leave Timer
0 for the Arduino core
since you are not using the Arduino core anyway, you can get rid of it
by simply defining main() in your sketch instead of setup() and
loop().


Powering Arduino Pro Mini with different voltage, fuse setting Arduino Pro Mini commonly comes in two packages, 5V 16MHz and 3.3V 8MHz.

The only difference between those two boards are regulator and clock crystal, right?
What happens if I supply 2V to VCC pin of 5V 16MHz board?
What happens if I supply 2V to RAW pin of 5V 16MHz board?
What happens if I supply 5V to VCC pin of 3.3V 8MHz board?
What happens if I supply 5V to RAW pin of 3.3V 8MHz board?

I read from some websites stating that Arduino Pro Mini power consumption can be reduced by removing regulator.

Does removing regulator cause VCC pin = RAW pin?

Jean created a custom board for Arduino Pro Mini rated at 1MHz 1.8V.

Which pin should I supply voltage after changing fuse setting? (Jean changed the fuse setting but I am not sure where to connect the supply voltage of 1.8V)
Related to question 7, is there a need to remove regulator to supply 1.8V?
Can I supply higher voltage (3V) on board with 1.8V fuse setting?

Reason for question/ Confusion

I want to power Arduino Pro Mini using 3V coin cell. Battery voltage decreases after usage to around 2V. I am thinking of simply inserting 3V coin cell to Arduino with 1.8V setting. But regulator may hinder the operation. That is why I am confused. Sites I visited states the possibility of using lower voltage after changing fuse setting but did not mention where to connect and whether regulator need to be removed.

Furthermore, ATmega328p datasheet states the VCC range is 1.8V to 5.5V. If that is so, why not just plug those voltage to VCC pin of Arduino Pro Mini instead of specifically 5V or 3.3V. Question 1-5 should clear my confusion on this.

Read the datasheet once more. A certain voltage is needed for a certain clock frequency. There is a graph somewhere.

Since the Atmega328p is able to run up to 5.5V for VCC, that 5.5V is for every clock frequency.

Using 2V for VCC is not enough to run it at 16MHz. According to the datasheet even 3.3V is not enough. But 3.3V and 16MHz will work (it is outside the specifications though).

The RAW pin is the voltage before the voltage regulator, right ? Depending on the voltage regulator you can apply a large range of voltage.
See the pinout.

When you remove the voltage regulator, the RAW pin is open. Sometimes I remove the voltage regulator and use 3 AA batteries and feed the 4.5V into the VCC (or 5V pin) of a 8MHz ATmega328p board.

Yes. The bootloader and sketch have to know the clock frequency. A sketch compiled for 8MHz is for a 8MHz Arduino board and a sketch compiled for 16MHz is for a 16MHz Arduino board.
2V is too low. 3.3V should work.
2V is too low. 3.3V depends on the voltage regulator.
No problem. The voltage regulator gets a reverse voltage.
No problem.
No. See the schematic.
To VCC.
Not a "must", but it is highly preferred to remove the voltage regulator, so no current is leaking towards the voltage regulator which gets a reverse voltage.
Yes. The fuses are to lower/disable the BOD, so a higher voltage is no problem.

This is the best tutorial about the power of the Atmega328p : Nick Gammon about Power

ADDED

I forgot to mention to remove the led as well.
This is a Pro Mini with a coin cell.

Lowering the clock speed will make it run at lower voltages, but that will not always reduce the used energy. Doing a calculation at a slow speed takes more time than the same calculation at high speed (and going into sleep mode after that).

ADDED 2

When a low voltage is supplied (for example 2V to a 5V 16MHz Arduino board), the voltage regulator will not work. How much current/voltage is still passed on depends on the voltage regulator. With the BOD disabled, and the microcontroller runs below its required voltage, anything weird can happen. Parts of the chip will work and parts will not. That is why the BOD was invented in the first place (to reset the chip and avoid weird things to happen). I think it is very unlikely that the microcontroller will get damaged with a (too) low voltage.


Why can't I print boolean variable values (0 and 1) through println function? source code :

int buttonPin = 8;
boolean buttonState = 0;

void setup()
{
   Serial.begin(9600);
   pinMode (buttonPin, INPUT);
}

void loop()
{
   buttonState = digitalRead(buttonPin);
   Serial.println(buttonState);
   delay(500);
}

But when, instead of boolean I specify an int data type for buttonState variable it produces the result I want i.e. 1 when pressed and 0 when not pressed.
Is it related to the way these variables when stated with different data types give different values to the println() function to convert them into ASCII values?

First, you are not supposed to use boolean with digitalRead.

The function prototype in Arduino.h is:

int digitalRead(uint8_t);

Thus, the correct data type for buttonState in your code is int. Then your other problem goes away. What I am guessing is happening is that the version of the IDE you are using does not have an overloaded function for Serial.println that takes a boolean argument, and the compiler is casting it to byte, in which case it would print as 0x00 (LOW) or 0x01 (HIGH) which are not printable characters.

Unfortunately the documentation for digitalRead on the Arduino site does not mention the datatype, it just mentions that it returns HIGH or LOW which isn't very helpful to help you work out what data type to use. BTW, neither of those values are, per se, booleans. If they had said it returns true or false you might reasonably put the result into a boolean field.

I have tried to get the Arduino developers to improve the documentation in this respect, something they have declined to do. I raised the issue almost 4 years ago, and no-one is even assigned to this particular task.

If you insist on using the boolean type, then a reasonable way of printing would be:

Serial.println(buttonState ? "HIGH" : "LOW");

In response to some comments ...

  Works fine for me. – Majenko

...

  boolean is a typedef for bool. bool gets promoted to int, not byte - Majenko

What you mean by "is a typedef for bool" is in some (later) versions of the IDE.

Looking at, for example, Arduino pre-release version 0023 I see in the file wiring.h:

typedef uint8_t boolean;
typedef uint8_t byte;

So you can clearly see that boolean and byte are the same, and therefore that using boolean would be treated as byte. Now if you look at the Print class in that release:

class Print
{
  private:
    void printNumber(unsigned long, uint8_t);
    void printFloat(double, uint8_t);
  public:
    virtual void write(uint8_t) = 0;
    virtual void write(const char *str);
    virtual void write(const uint8_t *buffer, size_t size);

    void print(const String &);
    void print(const char[]);
    void print(char, int = BYTE);
    void print(unsigned char, int = BYTE);
    void print(int, int = DEC);
    void print(unsigned int, int = DEC);
    void print(long, int = DEC);
    void print(unsigned long, int = DEC);
    void print(double, int = 2);

    void println(const String &s);
    void println(const char[]);
    void println(char, int = BYTE);
    void println(unsigned char, int = BYTE);
    void println(int, int = DEC);
    void println(unsigned int, int = DEC);
    void println(long, int = DEC);
    void println(unsigned long, int = DEC);
    void println(double, int = 2);
    void println(void);
};

So you can see that the overload for print and println treats an unsigned char (effectively uint8_t) to be printed with BYTE default treatment and not DEC treatment.

BYTE is declared:

#define BYTE 0

And the writing is done thus:

void Print::print(unsigned long n, int base)
{
  if (base == 0) write(n);
  else printNumber(n, base);
}

What this boils down to is that both byte and boolean will be written as "binary" bytes, not converted into decimal.

As Majenko says, things are different today, and boolean is now equivalent to bool which is promoted to int.

ElectroManiac did not respond to a question about what version of the IDE s/he is using, however my point is that for some versions of the IDE my explanation is true.

  Oh, and assigning the return of digitalRead to a bool is perfectly valid ...

Yes, for bool, but the question was about boolean. Whilst we know, by reading the code and reading the documentation, that digitalRead will return a 0 or 1, the fact that the return type is int means that the compiler can potentially see that you are stuffing a 16-bit return value into a 8-bit variable which will possibly lead to data truncation.

I must admit I don't get a warning when compiling with the Arduino IDE, however there is certainly the potential for truncation. A test program written in C++ and compiled with the -Wconversion flag gives a suitable warning:

warning: conversion to ‘uint8_t {aka unsigned char}’ from ‘int’ may alter its value [-Wconversion]

(There is no warning if you are placing the result into bool, however that is not the version of the IDE that the OP is using).


Arduino as Slave to Return Multiple Values I'm having trouble trying to get my two Arduino Unos to communicate with each other over i2c. I'm trying to have the master request for analog values from the slave by sending a request to the slave device for one of the six ADC pin values.

Master Code

#include <Wire.h>

void setup()
{
  Wire.begin();
  Serial.begin(115200);
}

void loop()
{
  Wire.beginTransmission(0x22); // Start communication with Arduino slave at address 0x22

  for(byte i=0;i<4;i++)
  {
    Wire.write(i);              // Request data from analog pin 'i'
    delay(5);                   // Give the slave a moment to sample ADC and respond
    while(Wire.available())
    {
      byte c = Wire.read();
      Serial.println(c);        // Print returned value to serial window
    }
  }

  Wire.endTransmission();       // End communication with Arduino slave
  delay(500);
}

Slave Code

#include <Wire.h>

void setup() {
  Wire.begin(0x22);
  Wire.onReceive(receivedHandler);
}

void loop() {
}

void receivedHandler() {
  byte data = Wire.read();
  byte analogValue;

  if(data == 0) analogValue = analogRead(A0)>>2;
  else if(data == 1) analogValue = analogRead(A1)>>2;
  else if(data == 2) analogValue = analogRead(A2)>>2;
  else if(data == 3) analogValue = analogRead(A3)>>2;
  else analogValue = 0;

  Wire.write(analogValue);
}

I can see that the data is being received by the slave, but the slave is not sending any data back, so I'm a bit confused how to send data back to the master. For the master there is "Wire.requestFrom(address, num of bytes)" to request a specific number of bytes, and for the slave "Wire.onRequest()" which will call a handler function to send back the number of bytes requested by the master, but for my application I won't be able to return more than 1 byte at a time.

Bidirectional communication in I2C is a two stage thing.

First you have to tell the slave which pin (or register) you want to read. Then you have to read it.

A typical master sequence would be:

Wire.beginTransmission(0x22);
Wire.write(1);
Wire.endTransmission();
Wire.requestFrom(0x22, 2);
byte b1 = Wire.read();
byte b2 = Wire.read();

And of course your slave has to respond to the write() and remember which pin is being selected, then separately respond to the requestFrom() and return the data corresponding to the pin that was selected earlier.


ADXL345 Data Rate seems to depend more upon Baud rate than the actual Data Rate that I set I have an Arduino UNO that is connected to an ADXL345. The problem is I need to collect data at 50Hz at least. The ADXL345 according to its Data sheet can go up to 3200Hz without any problem. I am using the Adafruit library using I2C interface but the accelerometer does not go above 10-12Hz as reported by the getDataRate() function of Adafruit library.

Im trying to set the data rate like this:

accel.setDataRate(ADXL345_DATARATE_100_HZ);

The strange thing is that the data rate is depended more upon increasing the baud rate at the beginning of my setup function. If I set this to 38400 I get around 90-92 readings every second. I have setup my code in a way that every measurement from the accelerometer is recorded with the timestamp down to seconds. This is a snapshot of the output from the serial monitor.

Data Rate:    9 Hz
------------------------------------
Sensor:       ADXL345
Driver Ver:   1
Unique ID:    12345
Max Value:    -156.91 m/s^2
Min Value:    156.91 m/s^2
Resolution:   0.04 m/s^2
------------------------------------

Range:         +/- 8  g

84.00,18:40:4,15/7/2018,0.59,9.14,2.82
85.00,18:40:4,15/7/2018,0.59,9.14,2.86
86.00,18:40:4,15/7/2018,0.63,9.10,2.86
87.00,18:40:4,15/7/2018,0.55,9.10,2.82
88.00,18:40:4,15/7/2018,0.55,9.10,2.82
89.00,18:40:4,15/7/2018,0.59,9.10,2.82
90.00,18:40:4,15/7/2018,0.59,9.10,2.82
91.00,18:40:4,15/7/2018,0.55,9.10,2.86
92.00,18:40:4,15/7/2018,0.55,9.10,2.86
93.00,18:40:4,15/7/2018,0.63,9.10,2.90
94.00,18:40:4,15/7/2018,0.63,9.10,2.90
95.00,18:40:4,15/7/2018,0.63,9.06,2.82
96.00,18:40:4,15/7/2018,0.63,9.06,2.82
97.00,18:40:4,15/7/2018,0.59,9.06,2.82
98.00,18:40:4,15/7/2018,0.59,9.06,2.82
99.00,18:40:4,15/7/2018,0.59,9.10,2.82

Is it a problem with the code, or the adxl345?

You do know that sending data through serial takes time, don't you?

You are sending 41 bytes per reading. The serial port has a 64 byte buffer. By the second reading the buffer is full and all printing blocks until there is room in the buffer.

At 38400 baud that's sending 3840 bytes per second. With 41 bytes per reading that's 93.66 readings per second (not including the time taken to do the actual reading) that you can squeeze down the serial port.

Either run at a faster speed, or reduce the quantity of data you're sending per reading - or do both.


It is possible to revive my Arduino Leonardo (mini beetle) board? I have this board:

It has the atmega32u4 chip.

I have updated its code several times, and used it without issues for several months. Today, while updating (using Arduino IDE) it started to throw some errors. At the end it said that the checksum didn't match, so I repeated again few more times with the same behavior until it reported "Uploaded" without errors. I used for few minutes and it was working as expected. Then, I had to do another update and the same happened (checksum didn't match). However this time I got to the point in which it was no longer detected by the OS (Ubuntu), and no LED is turning on.

Whenever I connect it to the USB port, I can only see in the logs:

usb 1-9.4: new full-speed USB device number 9 using xhci_hcd

However /dev/ttyACM0 is not longer created.

I'm trying to use avrdude to reset it, but it is reporting:

avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory

which make sense as /dev/ttyACM0 doesn't exists. So, what are my options? Is there anything I can do to make it work again?

UPDATE

I didn't realize that this board has a reset marked as "RES". Following Juraj recommendation I bridged RES and GND. The LED marked as "SDA" turns ON after I release the contact and I can read in the logs:

[1212051.679205] usb 1-9.4: USB disconnect, device number 22
[1212058.532030] usb 1-9.4: new full-speed USB device number 23 using xhci_hcd
[1212058.621972] usb 1-9.4: New USB device found, idVendor=2341, idProduct=0036
[1212058.621982] usb 1-9.4: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[1212058.621988] usb 1-9.4: Product: Arduino Leonardo
[1212058.621994] usb 1-9.4: Manufacturer: Arduino LLC
[1212058.622933] cdc_acm 1-9.4:1.0: ttyACM0: USB ACM device

Which I think its good news. However, it seems ttyACM0 becomes available for few seconds. I was able to upload the Blink example into the chip and I can confirm its working because its blinking. Still the ttyACM0 disappears after few seconds.

Output of avrdude -c avr109 -p atmega32u4 -P /dev/ttyACM0 :

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.00s
avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: safemode: Fuses OK (E:FB, H:D8, L:FF)
avrdude done.  Thank you.

Probably you have overwritten your Bootloader.
Connect MOSI, MISO, SCK and RESET to an ISP-Programmer and flash the file
Caterina-LilyPadUSB.hex
to it.
There are lots of tutorials on the net how to use a spare arduino as an ISP-Programmer.


How do I connect multiple pinhole cameras and take photos and video at the press of a button? I am trying to set up a 4 cameras which can take videos/photos at the press of a button.

Things which I will need:

4 micro cameras(the ones which are very small in size) with good
shutter speed and sensor. The cameras will often travel at 20 to
30mph. So I guess good shutter speed is needed.
2 Push buttons. One will start and stop taking pictures really fast, and the other will do the same for video
Battery which can last atleast taking 5 images/1 min of video recording.
4 Microsd cards and the connectors. Is there anyway I would be able to set up a common adapter to all these cards, so when connected to a computer it will show up as 4 different drives?

So I think I can make the set up using this: http://www.arducam.com/
But can it take images really fast. I couldn't see any information regarding this. It should be able to take like 4 images per second. Also it would be awesome if this set up can somehow support taking videos.

Now another thing I need is a push button which will start taking the photos and stop taking it.

This whole thing should operate from a battery.

Mostly I want to know is the list of products which will work or the specs to look for when choosing the products. Also I would like to know if this is the best way to go for  a project like this. This thing will be more like a toy, so I don't want to use really expensive parts for this. Also I don't want a gopro. I want to make this whole set up myself.

Let me know if you need to know more details about this.

Arduinos and Cameras do not mix well at all.  It's all down to the sheer quantity of data involved in pictures.

Take for instance a typical VGA image - 640x480 pixels at 24-bit (3 byte) colour depth.  One single picture requires 640x480x3 = 921600 bytes just to store it.

Add to that the fact that most small cameras include hardware JPEG compression which the Arduino really has no hope of being able to handle, and you just can't do anything with it.

Most camera modules use a system called CSI-3 (Camera Serial Interface version 3) for streaming the raw data from the CCD elements into the target.  That allows for high speed data transfer of the whole frame at a speed that is able to support video.  If you think about video as 25 frames per second, and raw data, that means that the data is being transferred from the CCD elements in total at arouns 22 MiB/s - there is absolutely no way that an Arduino can deal with that kind of data.  So cameras that attach to an Arduino have their own controller chip that compresses the image to JPEG and streams it out through a much slower interface - typically RS232.  All the Arduino can then do is tell the camera "Take a picture for me" at which point an image is captured and compressed, and then the Arduino receives the JPEG data through serial (slowly) and stores it on an SD card (also slowly). It can't do anything else with it.

To crunch those numbers - assume that the compressed VGA image from the camera's processor chip is 100,000 bytes (I took a typical photo, scaled it to 640x480 and saved it with 90% JPEG compression and it was roughly that size).  At 9600 baud you get 960 bytes per second. 100,000 / 960 = 104 seconds.

That is how long it would take to transfer one single image through the Arduino.

If the camera has a higher speed UART, say 115200 baud (11520 Bps), that would then give you 100,000/11,520 = 8.7 seconds.

So no, using an Arduino to control cameras in that way just isn't possible.

Instead you need a system that can talk CSI-3 directly - something with a direct camera connection, such as the Raspberry Pi.  Another alternative is any embedded computer with enough processing power and USB ports to connect cheap USB webcams to.  Again the Raspberry Pi would do - especially the newer version 2 with the quad core processor.


Is it possible to put priorities between external interrupts? My question is quite simple. I am using one external interrupt on the Mega2560 to wake it up with an alarm from the rtc DS3231 and record data from sensors for about 30 seconds and I would like also to use the other external interrupt to wake it up in case of shock detection to measure the signal.

The thing is that I know external interrupts have priority on internal interrupt but is it possible to put, in my case, the shock detection prior to the alarm ? In case the shock occurs during the alarm recording I would prefer to record the shock signal.

Thank you for your help !

Interrupts are not the right place to handle priorities. The interrupt
handlers should be as short as possible. Then the likeliness of two of
them happening at the same time is very low. And even if it happens, the
lowest-priority interrupt will only be delayed by a handful of
microseconds, which should not be a big deal.

In this case, the sensible approach is to have the interrupt handlers
set a global flag and do nothing else. Then the main program will
check the flags and do the real work, handling the priorities as needed.

Conceptually, the code could be something along these rough lines:

// Global flags.
volatile bool alarmDetected;
volatile bool shockDetected;

// Interrupt handlers.
void onAlarmInterrupt() { alarmDetected = true; }
void onShockInterrupt() { shockDetected = true; }

void loop() {
    if (shockDetected) {  // check this first!
        measureShockData();
        if (gotEnoughShockData()) {
            shockDetected = false;
            alarmDetected = false;  // ignore the alarm
            goToSleep();
        }
    } else if (alarmDetected) {
        recordSensorData();
        if (gotEnoughSensorData()) {
            alarmDetected = false;
            goToSleep();
        }
    }
}

Note that you can remove the line that ignores the alarm in case of
shock. If you do so, the alarm will be handled after all relevant
shock data has been recorded.


Why does my Arduino freezes when i turn a servo I have a Servo Motor and an Arduino Uno.

I used the Arduino to run a servo motor. The code was very simple. It was to just Turn it 90 Deg Anti-Clockwise when a switch is pressed and Turn back to its original position (90 Deg Clockwise).

The servo had 3 pins.
 1. V+
 2. Ground
 3. Data

I connected the V+ to the Arduino's 5v Output. And the Ground to the Arduino's GND pin. I connected the Data to Digital Pin 3.

When ever this script runs, The servo turns a little and then stops. It stops because the arduino froze and It wont do anything. I pressed the Reset button and it does nothing. I plugged off the Servo and the Power Supply and replugged the Power and it works.

The power source was a battery pack with 4x 1.5 Volts batteries in it. Maybe there was a problem with this?

Do anyone know what might be the problem here? Any Answer will be Appriciated. Thanks.

You said that you were using 4x 1.5v batteries. That would make a total of 6 volts. The current that those batteries can supply is also little.

The Recommended Input Range is 7-12 volts. And the Limit is 6-20 volts.

You were supplying it with 6 Volts which is at the very limit of the Input Voltage Range. When the motor runs, the Voltage might have dropped and made the arduino freeze.

The fix is to supply the arduino with another source such as a benchtop supply that can supply more than 8 volts.


Having problems with HC-05 and three relays I'm trying to control three relays with the Arduino Uno rev3 and a HC-05 bluetooth module from Elecfreaks.

I've wrote this code:

// the comments are the part of the code that I use to replace the Serial by default to be able to use the HC-05 module
//#include <SoftwareSerial.h>
int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay1estatus = 0;
int relay2estatus = 0;
int relay3estatus = 0;
char command;
//SoftwareSerial bluetooth(5,6);

void setup() {
 Serial.begin(9600); //bluetooth.begin(9600);
 pinMode(relay1, OUTPUT);
 pinMode(relay2, OUTPUT);
 pinMode(relay3, OUTPUT);
 digitalWrite(relay1, LOW);
 digitalWrite(relay2, LOW);
 digitalWrite(relay3, LOW);
}

void loop() {
 while(Serial.available() > 0){ //bluetooth.available()
  command = (byte)Serial.read(); //(byte)bluetooth.read();
  Serial.println(command); //bluetooth.println(command)

  if (command == 'a'){
   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   }else{
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }
  }

 if (command == 'b'){
  if (relay2estatus == 0){
   digitalWrite(relay2, HIGH);
   relay2estatus = 1;
  }else{
   digitalWrite(relay2, LOW);
   relay2estatus = 0;
  }
 }

 if (command == 'c'){
  if (relay3estatus == 0){
   digitalWrite(relay3, HIGH);
   relay3estatus = 1;
  }else{
   digitalWrite(relay3, LOW);
   relay3estatus = 0;
   }
  }
 }
}

The problem is that this code works perfectly using the Arduino IDE serial monitor, but when I try it using instead of the default serial methods, the SoftwareSerial ones it doesn't work.

Doesn't work in a very strange way because I can switch one by one the relays between on or off but, when I have two of them activated seems like freezes, I can't switch the third one on or off and neither I can switch the other two again.

To send the 'commands' through bluetooth I use the Bluetooth Terminal app available in the PlayStore.
(I've just posted the same question in stackoverflow but now I think here's the best place to ask it)

I don't see a problem with the code indicated for bluetooth; if that code is indeed ok, then probably you should look for hardware issues;  first, look for low +5V when multiple relays are turned on.  (Attach a voltmeter or a scope to +5, see if it changes when a second relay comes on, etc.)  Second, look (with a storage scope) for glitches when the relays switch.  If you don't have a storage scope, try testing with a separate power supply for the relays.  (Tie the grounds of things together, but give the Arduino and the HC-05 +V that's isolated from relay +V.)

More seriously, your code is overweight.  For example, replace

   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   } else {
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }

with

    relay1estatus = 1 - relay1estatus;
    digitalWrite(relay1, relay1estatus);


How can i split an incoming data in arduino? So  for my arduino project I need to split this line of servos data

180 0 0 0 90 90 0

Which would be parsed as:

servo position1 servo positin2 servo positin3 ...servo position 6

in to separate servo values, but i am new at arduino and c typе languges so a little bit help will be very good. So my question is how can I split these values up?

Scanning string formatted data can be done with sscanf (docs). It takes format strings just like printf() does, but instead of printing formatted data, it parses formatted data into the given variables.

For example,

String input = "180 0 0 0 90 90 0";
//parse input (6 integers)
int servoPositions[6];
int numScanned = sscanf (input.c_str(),"%d %d %d %d %d %d",
    &servoPositions[0], &servoPositions[1],&servoPositions[2],
    &servoPositions[3], &servoPositions[4],&servoPositions[5]);

//print positions again
Serial.println("Parsed servo positions:");

for(int i=0; i < 6; i++) {
    Serial.print("position ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(servoPositions[i]);
}

Outputs

Parsed servo positions:
position 0: 180
position 1: 0
position 2: 0
position 3: 0
position 4: 90
position 5: 90


Serial connection two devices two power supplies I'm trying to connect an ESP32-CAM to a 3d printer using a serial connection.
When powering the ESP from the 5V rail on the 3D printer(and using 3.3V zener diodes between tx, rx & gnd), everything works fine. The ESP expects 3.3V on the serial pins, hence the diodes.

circuit diagram

Common ground not shown.

Then when I try to run the ESP32 from its own 5v power supply, I cannot establish a serial connection, regardless of whether I connect the gnd from the 5v from the 3d printer with that of the ESP power supply.
In fact, the ESP doesn't function then.

Any suggestions?

PS: the ESP has its own power since it should trigger a relay to cut power to the printer.

The 3.3V zener diodes are connected backwards. The anode should be connected to ground and the cathode (banded end) to the GPIO signal. Zener diodes work in reverse bias...as you have them connected now they are forward biased and will clamp the signals to about 0.7V.

The zener diode on the line for data transmitted at 3.3V to a 5V input doesn't do any good. You need to increase that signal voltage to a proper 5V logic level. The best thing to do would be to get rid of the zener diodes altogether and use a proper logic level converter.

Also, you really should have resistors between GPIO output pins and the zener diodes, to limit the current through the zeners when the GPIO pin is at 5V.


ZS-040 (HC-05) blueetooth module Arduino Mega I followed this tutorial http://www.martyncurrey.com/using-an-arduino-mega-with-a-hc-05-zs-040-at-mode/ and it seems that the AT mode is on. (the LED is blinking like it's supposed)

I connected my pins like this:

  BT VCC to Arduino 5V out. Disconnect before running the sketch

  BT GND to Arduino GND

  BT RX (through a voltage divider) to Arduino TX1 (pin 18)

  BT TX  to Arduino RX1 (no need voltage divider)   (pin 19)

This is the code I run: (from the tutorial)

// Basic Bluetooth test sketch 5a for the Arduino Mega.
// AT mode using button switch
// HC-05 with EN pin and button switch
//
// Uses serial with the host computer and serial1 for communication with the Bluetooth module
//
//  Pins
//  BT VCC to Arduino 5V out. Disconnect before running the sketch
//  BT GND to Arduino GND
//  BT RX (through a voltage divider) to Arduino TX1 (pin 18)
//  BT TX  to Arduino RX1 (no need voltage divider)   (pin 19)
//
// When a command is entered in to the serial monitor on the computer
// the Arduino will relay it to the Bluetooth module and display the result.
//

char serialByte = '0';
const byte  LEDPIN = 13;

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

    // communication with the host computer
    Serial.begin(9600);

    Serial.println("Do not power the BT module");
    Serial.println(" ");
    Serial.println("On the BT module, press the button switch (keep pressed, and at the same time power the BT module");
    Serial.println("The LED on the BT module should now flash on/off every 2 seconds");
    Serial.println("Can now release the button switch on the BT module");
    Serial.println(" ");
    Serial.println("After entering AT mode, type 1 and hit send");
    Serial.println(" ");

    // wait for the user to type "1" in the serial monitor
    while (serialByte !='1')
    {
        if ( Serial1.available() )   {  serialByte = Serial1.read();  }
    }

    // communication with the BT module on serial1
    Serial1.begin(38400);

    // LED to show we have started the serial channels
    digitalWrite(LEDPIN, HIGH);

    Serial.println(" ");
    Serial.println("AT mode.");
    Serial.println("Remember to to set Both NL & CR in the serial monitor.");
    Serial.println("The HC-05 accepts commands in both upper case and lower case");
    Serial.println(" ");
}

void loop()
{
    // listen for communication from the BT module and then write it to the serial monitor
    if ( Serial1.available() )   {  Serial.write( Serial1.read() );  }

    // listen for user input and send it to the HC-05
   if ( Serial.available() )   {  Serial1.write( Serial.read() );  }
}

I want to mention that the baud rate is set to 9600 and Both NL & CR is also set.

The problem is when I insert 1 in the Serial Monitor and nothing happens. How can I solve this problem?

Solution

Connection:

Bluetooth RXD to Arduino Mega pin 11
Bluetooth TXD to Arduino Mega pin 10
Bluetooth VCC to Arduino Mega 5V
Bluetooth GND to Arduino Mega GND

I used this code:

#include <SoftwareSerial.h>

#define RxD 10
#define TxD 11

SoftwareSerial BTSerial(RxD, TxD);

void setup(){
  // replace BAUDRATE as suggested
  BTSerial.begin(BAUDRATE);
  Serial.begin(9600);
  BTSerial.print("AT\r\n");
}

void loop(){

  if (BTSerial.available())
    Serial.write(BTSerial.read());

  if (Serial.available())
    BTSerial.write(Serial.read());

}

after setting AT mode as described in the tutorial above.

I tried running the code with BAUDRATE starting from 9600 to 460800:


Arduino Uno: external power supply +5V and serial communication with pc over USB I have connected to my Arduino Uno outputs relay module. Relay module has 16 relays (5VDC) which are controlled by transoptors pins (HIGH from Arduino = specific relay is off).

Link to relay module (lang: polish): https://botland.com.pl/pl/przekazniki/6940-modul-przekaznikow-16-kanalow-z-optoizolacja-styki-7a240vac-cewka-5v.html?search_query=modul+przekazniko&results=75 (SRD-05VDC-SL-C relays).

Arduino is supplied by +5V pin and GND pins with external power supply MDR-5-10. Relay module is supplied with the same power supply.

I control Arduino from PC using serial communication over USB (I send a command eg. 1;1;1;1;1;1;, then 6 outputs goes to HIGH). And now there is a problem. When I disconnect relay module control pins from Arduino outputs everything works fine. But when it is connected, I get serial com. error "device not found" (after some switches: sometimes it works for about 20 output switches, sometimes for 1 output switch) and I have to open serial communication again. Probably error appears only when I'm switching outputs.

I think the problem is because my external power supply +5V drops for a while when switching and then Arduino switches to +5V from USB (which doesn't drop), which has not enough power and then error occurs.

Am I right? Any suggestions to fix the problem?

EDIT #1:
Thank you for help. Answers:

@Jot, after disconnecting +5V Arduino pin, but with connected relay module, I get serial error immediately with first relay switch. If i dosconnect both +5V pin and relay module control pin, my application works fine.
My wires: external power supply - Arduino: 0,5 mm2; Arduino - relay module control pins: 23 AWG (~0,25 mm2); external power supply - relay module +5V and GND: 1,5 mm2. It flows through relays: 24VDC <30W or 230VAC ~20mA.

@CrossRoads, no I use A0-A4 and Q3-Q12 (for relay module: Q3-Q7, Q9-Q11, Q13).

@Duncan C: Currently, I use only 9 relays, other control pins are disconnected and off. Here - http://botland.com.pl/index.php?controller=attachment&id_attachment=244 (power consumption per relay - 0,36W 5VDC) - you can see relay datasheet. Relays are isolated from Arduino with opto-isolators (signal HIGH from Arduino = relay is off).
I never switch them all at once. In specific function I never use more then 5 relays together.

@Majenko, thank you, I'll give it a try in Tuesday!

Further informations:

Probably problems occur more often when I connect wires to relays pins (I use them all as NO: 7x 30W 24VDC - coils, 2x 230VAC ~20mA - contactor).
Serial communication error can occur during both reading or writing to serial.

I have a similar rig using a 4-channel optically isolated relay, but I use different power supplies for the Arduino and for the relay. (It works perfectly.) My guess is that the relays are causing the voltage on your arduino to droop when they switch on. I suggest using separate power supplies.

As @Majenko suggests, you might try adding a filtering cap (capacitor) between +5V and ground very near the Arduino. The cap should slow the drop in voltage to the Arduino long enough for the power supply to recover, but separate power supplies is the surest fix.


Spectrabloom LED light box I'm looking to make a DIY version of Dan Conrad's Spectrabloom. I've got an Arduinio Uno, a piece of code that uses PWM to randomly fade three 1w LEDs (one red, one blue and one green) and a PicoBuck LED driver.
Question is - do I have to have two power supplies? One to power the PicoBuck and one to power the Arduino or can I have them all running off one supply? If the latter - can anyone give me pointers on the way to hook everything up?

Question is - do I have to have two power supplies?

No, you can use one power supply for both. But you need to make sure, that the LED current is not flowing through the Arduino, since that can kill the Arduino. To do that, you need to connect the power supply to the LED driver and the Arduino in parallel. For example, lets assume you have bought a 5V wallwart/power supply, which is can provide enough current for your whole circuit (and some headroom for further development). Then you can connect the positive lead to the 5V pin of the Arduino and the Vin+ (positive supply voltage) pin of the LED driver. Also connect the negative lead of the power supply to ground on Arduino and Vin- (negative supply voltage) of the LED driver. That way the current for the LEDs comes directly from the power supply and doesn't need to flow through the Arduino, but past it.


Mega pin stuck high after driving optocoupler I have an Arduino Mega which is driving a board. On the board is a quad optocoupler (K847PH). Pins 42 - 45 of the Arduino are each attached to the Anode of a opto. The cathode goes to ground through a 50ohm resistor. I've used multiple boards and have had no issues with this part of the circuitry so far. I recently attached a new board (same circuit) and began testing. I noticed I had ~1.1V on pin 1 of the opto (Anode). After some debugging I checked the voltage coming out of the Arduino to that pin (42 on the Mega) and noticed it was 5V. I ran a new sketch to drive and hold the voltage low but the voltage remains at 5V.

void setup() {
  pinMode(42, OUTPUT);
  digitalWrite(42, LOW);
}

void loop() {
  digitalWrite(42, LOW);
}

Looking at the schematic of the Mega it appears pin 42 is directly connected to the ATMEGA1280-16AU. Is there anything I can do to fix the Mega? Should I just replace the ATMEGA1280-16AU? Is there something I can probe to check? It does appear there is > 1Mohm of isolation between pin 42 and the 5V rail.

Re “Is there anything I can do to fix the Mega?”, if the condition persists when trying it after removing power from the Mega and discharging it, probably not. (Aside from not using that pin.)

Note, the IR LEDs in the K847PH are rated at 60 mA max each, and typically drop 1.25 volts at 50 mA current.  If you drive them with 5 V through a 50Ω resistor, typical current will be 3.75/50 = 75 mA, which exceeds K847PH ratings and Mega2560 ratings (typically 40 mA max, 20 mA working).  Consider using a 125Ω or more resistor, to stress the Mega pins at 30 mA or less.

(From Fig. 8 - Collector Current vs. Forward Current, in the K847PH data sheet, you might be ok with 10 to 20 mA current through the IR LEDs.)


How can I program an ESP 10 module I buy an ESP-10 module and I want to upload custom room to its flash. The problem is that there is no way to access GPIO 0 pin! Is there some way around it to upload custom room without connecting GPIO 0 to the ground?
How in the earth should I program it without this pin?
here is an address to supplier's page which contains schematic and some other details.
https://www.tindie.com/products/George/esp8266-esp-10-module/#product-description

You can't.  Not without physical modification to the PCB itself (remove the chip, scratch off a pad and trace, replace pad with fine enamelled copper wire tinned at the end, replace chip).  All you can use is whatever firmware is currently installed in the module.


Two flow sensors, one ESP32, LCD and/or Arduino I want to build a flow meter but the Gal/Min rating of something like this flow meter is too low. I am thinking of strapping two side by side with suitable plenums for In and Out.

I have found some sketches like this but wondering how to use the two inputs to aggregate the results to GPM and Gallons total for display on an LCD screen. I am unsure what happens if two Hall-results arrive at or about the same time but on different Data Pins.

I have priced some single sensors with a higher flow rate for the pipe size but they run to several hundred dollars. Gallons are not critical as long as I can be within about 5% error over ten minutes, our average tank fill time.

Can someone please point me at some code to get me started for an ESP32 and LCD. I'd even consider adding a Nano if that makes things easier. I imagine that would certainly prevent collision issues. Basically I need to be able to handle the flow rate to a single LCD.

Thanks

A Hall Effect Sensor like that just gives you a pulse every rotation (or two pulses per rotation, etc) of the internal vanes.

If you use interrupts to count the pulses then two pulses arriving at the same time will be handled sequentially. The interrupt flag indicating a pulse has arrived is set in hardware the moment the pulse arrives, and the CPU checks all the interrupt flags between instructions. Each flag is handled sequentially, the order determined by interrupt priority settings and a "natural" order determined by the internal wiring of the CPU.

However there is a better way on the ESP32, and that is the Pulse Counter peripheral.  This is designed to count pulses like the signals from Hall Effect sensors.

You can just leave the Pulse Counter counting your pulses, then periodically read and reset the pulse count to see how much water has flowed in that period. It looks from the documentation that you can have two inputs both making the same counter increment, so it will do the aggregating for you.


Output 12-25V from Arduino Mega I am currently building my first Arduino project : a car that you can control from your computer. I have my Arduino Mega that outputs 3.3 or 5V and my stepper that receives 12-25V, how can I make my Arduino digitally write something to that stepper?

Use an H-bridge motor driver. They can use arduino signals to control higher voltages without damaging the arduino. Check out the  L298N from gearbest. It's cheap but will probably do the trick if you're not using too much current.

It can supply about 1A through each gate at 5-30V.

this video should help explain it. (I haven't watched the video but it seems like it got good feedback).


Why does a function inside void set up is repeating after some minutes I am trying to time sync my arduino hardware to NTP server. I have a `setSyncProvider(getNtpTime)´ function to do it and called inside the void setup. I have another function (mainFunction) inside the main loop, that calls every minute. I have added a function to display time inside this mainFunction so that time will update every minutes.  Code works fine for first five minutes. Then it calls the getNtpTime again even though it is not inside the loop. Why is it happening?

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

The setSyncProvider function of the TimeLib sets a function which will be called by the library every interval seconds. The interval is set with setSyncInterval. Default interval is 300 seconds.


Random data sending integers between two Arduinos I'm trying to do something seemingly simple, but I'm running into difficulties. I want to send about 5 separate integers between two Arduinos over software serial. I have written the following, but I rarely get the two numbers on the receiving end - they're usually garbled or in the wrong order. I'm sure that I'm missing something obvious, but I can't work it out no matter how hard I try. Any help would be greatly appreciated.

Sender:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

int val, val2;

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

void loop()
{
  val = 123;
  val2 = 456;
  if(mySerial.read()=='#')
  {
    mySerial.write(highByte(val));
    mySerial.write(lowByte(val));
    delay(3);
  }
  if(mySerial.read() == '~')
  {
    mySerial.write(highByte(val2));
    mySerial.write(lowByte(val2));
    delay(3);
  }
}

Receiver:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

byte val;
byte low, high;

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

void loop()
{
  mySerial.write('#');
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}

You are being too impatient.

The receiver needs to wait until there is some data available.  if (mySerial.Available() > 0).  So before every read add that line and it should work.


Buffering output stream I'm looking to toggle a pin on and off in a fast and timing-sensitive manner, and I'm wondering if the Arduino Uno has any built in "buffers" that would be able to hold a set of values and send them sequentially to the output pin at high speed, separately from the rest of the loop. I could then refill the buffer with the next set to be outputted, and so on.
Is this even possible? If anyone has any documentation on what's involved, I'd really appreciate some links (or tips!) :) thanks

The closest thing to what you describe is DMA (Direct Memory Access). The Arduino doesn't have DMA. More powerful microcontrollers often do, but not little 8 bit ones.

The closest you could do is to use a timer interrupt to run a small function periodically which reads the next value from an array and sets the pin to that state.

The TimerOne or TimerThree libraries can be of help to you here.


XBee: How do I create a packet? I am currently using a simple protocol I created to send three bytes (unit information, data, and XOR) individually over an XBee radio (3 bytes are considered a single transmission). However, this is not always reliable if a byte is dropped. For this reason I'd like to encapsulate each individual byte as a packet in a way that the Arduino could identify which byte is which and if a byte is lost then just wait for the next transmission. What I am not sure about is creating a packet. I haven't been able to find any tutorials or example code.

The biggest mistake people always make with serial communications of any form is to just send raw data over the connection. While you might just about get away with that on a 100% reliable direct serial connection over a short distance, as soon as you introduce anything with any form of uncertainty to it you are, as you have seen, doomed to failure.

So you have to come up with a reliable method of transferring data in such a way that the receiver knows that it has received valid data, and how to find valid data.

So you need to create a packet. That's not something where you just wave a magic wand and a packet is created. A packet starts it's life in your own head.

In order to reliably transfer data there are a few things you need to consider from the point of view of the receiver:

Where is the start of my data?
How much data is there?
Is this data correct?

The receiver has to have some way of knowing where the start of a packet is amid the torrent of bytes it is being sent. It needs to look out for something unique, something it cannot mistake for anything else. This is called synchronisation. It is often done with a specific sequence of bytes (known as a preamble) that can, through various means, never appear anywhere else.

And at that point things start to get a little more complex, for now you need some way of wrestling that kind of thing into a system that can only send bytes of 0 to 255 with no way of distinguishing raw data from control information like this synchronisation sequence. And that is where the concept of escaping comes in. This is where you nominate certain byte values as control bytes and decide that these bytes will never appear in your data without some kind of marker to say they are data bytes. A common escape marker is 255 (used in the telnet protocol) or 27 (the ANSI ESC character) although any character can be chosen.

For instance if you choose to have a synchronisation sequence of 0xAA, 0x55, you can then decide that neither of those bytes will ever appear in your data without first being preceeded by character 0xFF. So if you happened to have that sequence in your data you would expand it out to 0xFF, 0xAA, 0xFF, 0x55.  But what if you want to send the value 0xFF, in your data? How do you handle that? Well, you also escape 0xFF as well. 0xFF, being the escape character, has no actual value in the data. It only says that the next character must be interpreted as data. So to send 0xFF you would actually send 0xFF, 0xFF. Your receiver sees the first 0xFF and thinks "ah, the next byte that arrives, whatever it is, just be data." It then gets a second 0xFF and knows it is data. (Actually this is the opposite of escaping which says the next character is a control character, but the underlying concept is the same).

If it ever sees 0xAA, 0x55 then it knows, without a shadow of a doubt, that this is the start of a packet, or random noise. And that is where the next two points above come in: Validating your packet.

If your packets are always the same size then all you need to know is how many bytes to expect, which can be hard coded into your software. If you have different sizes of data to send then you also need to tell the receiver how big the data is. This forms part of the packet header. A small block of meta data that preceeds the actual data that holds information about the packet. Depending on your topology that could be things like the size of the data, where the packet came from, where it is going, etc, and maybe a checksum, though some people like to put the checksum after the data since it simplifies sending.

And then there is the checksum. Possibly the most important thing next to the synchronisation. And so easy to get wrong.

Having a checksum that is too simple is not so good. It can be fooled. That is, if values get corrupted in the data with a simple checksum it is far more likely that the checksum still says it's correct than with a more complex checksum. You should read up on existing checksum algoritms, such as Cyclic Redundancy Check (CRC) and things like the checksums used in IP packets. All are good lessons on how to deal with checksums properly.

So far we have just tackled the serial equivalent of UDP - throw a packet at a receiver and hope it gets there. Doing anything more reliable becomes much more complex. If you want to know if your packet actually got there you will need your receiver to acknowledge reception, possibly including some information about the packet it received, such as a sequence number. If the transmitter never receives that acknowledgement it needs to send the packet again, which means it needs to remember what the packet is that it sent. So you need a packet buffer, or even better, a packet queue. And timeouts. And sequence numbers.

That latter is most important. A sequence number is a unique (or unique over a reasonable period of time) identifier for a packet. When a transmitter doesn't receive an acknowledgement is it because the receiver never got the packet, or that the receiver did get the packet but the acknowledgement never made it back to the transmitter? If the latter then the receiver is liable to get the same packet multiple times through retransmission. By including a sequence number the receiver can go "hang on a moment, I have seen this packet already" and it can throw it away sending a new acknowledgement in the process.

So as you can see, reliable communication isn't as simple as just sending data, or even sending data in the form of a struct. There is a whole lot more to learn and understand.

I suggest you read some of the IP networking RFCs to learn more about reliable packet transmission and reception.

Oh, and I haven't even touched on sliding window reception and such like for how to best program your receiver software...


Using different processors when it comes to arduino I decided to learn Arduino in this quarantine so I am still a newbie when it comes to micro controllers. Basically I been doing all my projects based on the ATMEGA328P-PU:

I even converted my breadboard designs to custom PCBs like this one:

I am running out of Atmega328P-PU processors and I am about to buy more. But instead of going with the traditional Atmega328P should I buy other processors?
This are my alternatives:

They all are about the same price. For example the ESP32 is 10 times faster and it was a lot more sram and pins. Anyways this are my questions:

Why do people buy the Atmega328P when there are faster and more powerfull processors for the same price?

I been saving a lot of money by buying the Atmega328P processor by itself and then building Arduino using the crystal, ceramic capacitors etc. There are so many tutorials on how to build that such as on THIS LINK and many more. But how can I build an ESP32 running arduino code on a breadboard? I have not been able to find that tutorial. All the tutorials I find use the ESP32 already soldered to a PCB. I want to build my custom PCB using a ESP32 for example. Where can I find that tutorial?

If I decide to buy the ESP32 or ESP8266 should I build my code using the arduino IDE? I will have to add stuff to arduino IDE so it works with the ESP32. What are the benefits of using other IDEs?

I am thinking about the ESP32 and ESP8266 because I see a lot of people using them on the internet and they are much more powerfull than the Atmega328P for the same price. What other processors do you guys recommend?

Sometimes faster and more powerful is not needed. If you just needed a simple timer, and it needed to be battery operated, a processor like the ATmega328 would be the better choice. It really depends on the application.

The ESP32 is a great device. But the A/D converter on it is less than stellar. It is not as consistent compared to the A/D in the Atmega328P.

The ESP32 is more fussy about the power supply requirements compared to the Atmega328P. Lots of people get themselves into trouble when they use poor design practices with the ESP32/ESP8266 modules. Poor practices that worked well enough for lower power and lower speed processors like the Atmega328P. Most people don't bother with reading the datasheet for the processors. They just try and copy stuff they fine on the Internet. And the Internet is full of poor quality information by people who don't really understand much of what they are working with.

If you want to start using the ESP32, then do yourself a favor and buy a working board with a power supply and not just buy a module. It will save you many hours of grief.

The Arduino IDE makes it easy to get stuff working. There also is Python, but it is less popular. There is a lot more information available for the Arduino IDE, and available libraries. And that makes development a lot easier. There are other ways, but the learning curve is much steeper.

The "Blue Pill" STM32F103C8T6 based board is a lot of capability for little money. The CPU runs on 3.3 volts like the ESP devices. It has gain a lot of popularity in the last few years but there isn't as much information as for the Atmega328P.

The STM32F103C8T6 and the ESP devices are 3.3 volt based designs. And they require 3.3 volt devices to interact with. There are some devices that are mostly 5 volt only devices. Like a character LCD. It is easier to interface that to a 5 volt processor.
There is lots that I could still say but it would take hours. But what you should do before deciding on a part is to decide what the needs of the project are. That will often guide you towards the part you should use.
One more note. The ESP devices are running a lot of code on top of the Setup and Loop functions. There is lots of stuff going on in the background to support the WiFi capability. And you don't have the kind of control that you could have with a non-ESP device. But if you want that part then you need to accept that limitation.


Pin 13 fires relay when powering on... How to disable? Pin 13 fires relay when powering on... How to disable?
I'm using pro mini 5v 16MHz and a DC 12V 2 Channel Relay Module Optocoupler. The relay Jd-VCC is powered by a 12V and it's VCC is 5V (the same as Arduino VCC). The relay is active low and I soldered pins 12 and 13 of the pro mini to IN1 and IN2 of the relay.

When I power the board up it cycles Pin 13(and the on-board LED) ON and then OFF before resuming to the code I uploaded. I believe that this can be fixed by disabling this blinking function in the startup process.

I understand that I can use other pins. Why not learn how to remove this from startup, if I prefer to use this pin for circuit layout purposes?

Any help would be much appreciated. Most of my searches ended up with people using the pin as an input... My issue is when using D13 as an active low pin it has some funky behavior at startup but then works as programmed.

Thanks!!!

There are three things you can do:

Remove the bootloader entirely and program the board with a hardware programmer (USB-ASP, Another Arduino, etc).
Edit the bootloader source, recompile, and reinstall it to the board using a hardware programmer (as in option 1).
Just don't use pin 13 for the relay.

Of the three options the third one is by far the simplest.


Connect multiple I2C to an Uno Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?
Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?

Yes, provided they have unique I2C addresses.

  Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

No. All of the devices must be tied to both SDA and SCL. You may need a smaller resistor depending on how many devices there are; see NXP document UM10204 for details.


Setting Up a JavaEE app on an Arduino Yun Board I'm looking for some reference material to start on a project I'd like to do.

I have an Open House at my school. My group project has been to create a little timesheet app using JavaEE. I just started looking for how to do this and if I can. But I would like to wow people a bit by setting this up using an Arduino Yun board. I know it has WiFi and I'm pretty sure I can run Linux on the little guy.

Any help would be greatly appreciated.

Sorry, forget it. 64Mb ram, 16Mb flash what the Yun has.
Java EE is magnitudes bigger (and bugger) than that.

You might try with Java SE embedded, the smallest profile might fit to 11Mb:
http://www.oracle.com/us/technologies/java/oracle-javase-embedded-ds-365290.pdf
and then you can roll your own web server.

(Personal comments: For little timesheets JavaEE is overkill, for anything modern JavaEE is obsolete - consider modern Java micro web frameworks, which offer magnitudes better performance than JavaEE).

What you can try is Raspberry PI, which works well with network, and Java (SE).
Not that well but also Java EE works: https://blogs.oracle.com/theaquarium/entry/glassfish_4_on_the_raspberry


connection issues with 3 arduinos any suggestions? I have 3 arduinos that I want to program on, all of them with their own cable and I have tried to connect them to my laptop on several different usb ports, my usb ports work with mouses so that's unlikely to be the problem. However I just cannot connect to them they just don't appear under /dev/ttyACM* and the arduino IDE cannot find them either. I'm running ubuntu 14.04 any suggestions for finding out what is likely to be wrong with my system or the arduinos?

For some odd reason they now all appear to be seen as /dev/ttyACM* but they now all give me a

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

error

Anybody have any idea how to fix? The arduino's do not have any wires in them except usb (nothing in reset or any other pin), I'm on ubuntu so the drivers shouldn't be an issue? And pin 13 flashes when I reset the arduino.

it's been a while but a long time later I found that the cable I was using was broken. A different cable worked.


Beginner problem with DC motor I am new to electronics and I'm having a problem when creating my project. I have created a Bluetooth controlled rover using HC-06, Dual H-bridge motor driver and 4 DC motors.
However, only two of the DC Motors are moving and the other two remain still.

Could you please suggest what happened?

Attached is the wiring of the motors and code.

char t;

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

void loop() {
  if(Serial.available()) {
    t = Serial.read();
    Serial.println(t);
  }

  if(t == '1') {
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
  }

  else if(t == '2') {
    digitalWrite(9,LOW);
    digitalWrite(10,HIGH);
    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);
  }

  else if(t == '3') {
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
  }

  else if(t == '4'){
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
    digitalWrite(12,LOW);
  }

  else if(t == '5') {
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
    digitalWrite(12,LOW);
  }

  delay(100);
}

To analyze your problem:

Switch two wires between two motors (and repeat this to get all combinations), to find out if the code/wiring until the motors is wrong, or there is a problem with the motors.
Print out the values of pins 9, 10, 11 and 12 and the value of t/input to see if the pins are controlled as you expect.
Remove all but one motors, for all motors one at a time, to see if there is no influence between them.

Below is not an answer to your question, but I can only align the code as answer.

It is better coding style to use the following form:

void loop() {
  if(Serial.available()){
    t = Serial.read();
    Serial.println(t);
  }

  if ((t >= '1') && (t <= '5'))
  {
    int input = (int) t - (int)'0';

    digitalWrite( 9, (input == 1) || (input == 4) ? HIGH : LOW);
    digitalWrite(10, (input == 2)                 ? HIGH : LOW);
    digitalWrite(11, (input == 1) || (input == 3) ? HIGH : LOW);
    digitalWrite(12, (input == 2)                 ? HIGH : LOW);
  }

  delay(100);
}

Note: ? : is a ternary operator which means : a ? b : c => if a then b else c.

Instead of using 9, 10, 11, 12 define pin numbers (e.g. PIN_MOTOR_X), and for 1, 2, 3, 4, 5 input numbers define LEFT, RIGHT, UP/FORWARD, DOWN/BACKWARD, STOP.


Millis() does not back to zero after woke up from deep sleep mode I am going to make a project that needs four boards of Arduino which synchronization in time is needed. The project is about capturing the timestamp (in ms resolution) whenever something is crossing ultrasonic proximity sensor. The following are the modules I am going to use:

Arduino Uno R3 4 units
Ultrasonic Proximity sensor 4 units
DS1302 RTC modules 4 units
Micro SD Card modules 4 units

The boards will be placed in 4 different places which it is quite far from each other that makes it is hard to make wired connection. The detecting object will move back and forth during a certain interval of time, so that is why the time synchronization is needed.

My idea is, by using the timestamp from RTC modules, I turn all the boards together into deep sleep mode at the time I have set in the code and wake them up together after 10 seconds. I don't have any problem with RTC modules, but my problem lies in the millis() function which did not back to zero after woke up from deep sleep mode. I need this function since the DS1302 RTC does not provide ms resolution, yet I can not achieve sync if the millis() function does not back to zero.

I tried the code (edited with millis() added in the loop) from here:
https://www.youtube.com/watch?v=8fiYvnBDsDE

Do you have any solutions? Or another RTC module which provides ms resolution instead. Thank you

Store millis() at boot, and if (resetCause == "Deep-Sleep Wake") zero out the stored copy of millis().


CH34x board fails with avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 Atemel Mega328P AU1640 I have been given a board(Atmel ATmega328P-AU 1640) to program. I googled and found category of board Arduino Uno/ CH34x-based clone.

But when I program an empty program:

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

}

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

}

I get this error:

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

These are all the ports that are available to me. I have connected my Arduino with one of the USB ports on my Macbook running MacOS Sierra

You have an Arduino nano clone using a CH340G chip for serial communication. You to down load and install a driver for your computer to recognize it. I don't use OSX, so there's not one I can recommend.


Is it okay to short IN and GND pins of relay module with controller ground? I have this relay module that is attached to an ESP8266 (Wemos D1 Mini). Currently, I operate the relay by shorting the IN and GND pins to ground (relay module uses low state to energize) with a transistor hooked to my D1 pin. Relay 5V comes from an external power supply

The circuit diagram can be found here.

The module works fine and all but I am wondering: is it okay to operate it like this ?

It is not okay. The base-emitter of an NPN transistor acts as a diode. That means pin D1 is shorted to GND via a "diode". You need a resistor to the base of the transistor.

The relay module has already a transistor to drive the relay and also a flyback diode. The control signal that is needed depends on the relay module. The explanation "5VDC to 12VDC (some boards may work with 3.3)" on the page of the relay does not sound reliable.
The relay module on that page is not the module that you have. You have a different module that is activated with a low signal.
Nevertheless, I think that a transistor can be used when the IN and GND of the relay module are connected to the collector of the transistor.

Could you please not try to make the schematic as small as possible. A schematic should explain how everything is connected.

Could try to connect the collector only the IN pin? As in the schematic below.

In your circuit diagram, the mains "neutral" is connected to an earth ground symbol. I hope you are not going to connect a mains wire to ground.

When the IN and GND are connected, then the resistor to the transistor needs to be lower. The ESP8266 can output 12 mA. Let's use 10 mA for safety: (3.3V - 0.5V)/10mA = 280 Ω. I suggest using a resistor of 330 Ω or more.


How to measure voltage with Arduino analog input I'm totally new to Arduino and to electrodynamics in general.

I'm wondering what happens if I connect my digital pin to an analog input on Arduino, and make digitalWrite and analogRead on the according pins. Here are the options I can think about:

Just connect them directly - it is not a short circuit, is it?
Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?
Make a circuit: digital output -> resistor -> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

As you see, I'm really confused now. I would highly appreciate if someone could explain in detail what is happening in all the cases, with corresponding values for the current, voltage and resistance.

You can connect digital pin to analog input directly. That's not very interesting though, since you'll only see two values from the analog input (at least theoretically).

The digital pin gives out 0 or 5 Volts. The analog pin expects 0 to 5 Volts input. The only thing that matters to the analog input is the voltage with respect to ground. That can be between 0 to 5 volts (returned as 0...1023 by analogRead function).

  Just connect them directly - it is not a short circuit, is it?

No, it's not a short circuit. In general, connecting anything to an input is not a short circuit. Connecting output to another output is potentially a short circuit.

  Connect a resistor in between - the voltage should still be 5v, right? Whatever resistor I use?

This makes no difference compared to connecting them directly, unless the resistor value is very high (should be hundreds of kOhms or even MOhms to see a difference, I suppose), because almost no current flows to the input.

  Make a circuit: digital output -> resistor -> ground, and connect the analog input in parallel (in between the resistor and ground) - Does it make sense? What is the difference with the previous option?

This makes no other difference than that the resistor loads, i.e. draws current from, the digital output. If the resistor value is too small, then the digital output is unable to supply enough current so the 5 V voltage could become less than 5 V, or you could even burn the chip.


Arduino Mega and other modules power consumption I have an Arduino Mega 2560 to which I have connected:

Arduino GSM Shield 2
Waveshare 10 DOF IMU sensor
Waveshare NEO-7M-C (B) GPS module
HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.

My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.

You can't fix it with more voltage. The board you are using (schematic here) uses a linear voltage regulator. All increasing the voltage does is make the regulator run hotter.

You could try running from around 7V, this will minimize the heat dissipation in the regulator and may allow you to pull more current through it but I suspect you've simply hit the design limits of the power supply circuits.

Instead of using the Arduino's built in power supply to convert from 12V to 5V you could try using an external 5V supply with a greater current capability connected directly to the Arduino 5V rail.


How can I generate a sinewave with Arduino Uno? I would like to generate a sine wave with my Arduino Uno. As far as I know, there is no library for Uno to generate such a signal (correct me if I'm wrong), so the only option available is to write a function to generate the signal from scratch.

As far as my understanding of digital electronics goes, I believe it is possible to generate a sine wave signal by using PWM and varying the duty cycle accordingly. However, this route seems to me quite long, what other options do I have?

As far as I know, there is no library for Uno to generate such a
  signal (correct me if I'm wrong)

You are wrong, there is Mozzi, the sound synthesis library for
Arduino. It works essentially along the lines sketched by uint128_t.
Take a look at the Sinewave.ino for an example on how to make a
(lookup table-based) sine wave. It can also do much more.

In its default mode, Mozzi works with a 16,384 Hz sample rate and a
32,768 Hz (not audible) PWM frequency.


Using dynamic variables in URL I am trying to upload longitude and latitude data into MySQK using a GPRS shield, Arduino Uno R3 and a GPS module. The idea is to get longitude and latitude data from the GPS and use the GPRS to post the information into my database.

I have to insert the latitude and longitude data into the URL like  this steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785. Values for longitude and latitude have to be dynamic not static. How do I go about this?

It looks like you need to know how to create a string that contains:
steetalert.co.zw/write_data.php?Longitude=12.124311,Latitude=27,766785

Its quite easy (I think) try this:

const int cDecimalPlaces(6);
String szLon = String(fLongitude, cDecimalPlaces);
String szLat = String(fLatitude, cDecimalPlaces);
String szUrl = "steetalert.co.zw/write_data.php?Longitude=" + szLon ",Latitude=" + szLat;

Normally I would use sprint or a Format function, but I can't find those in the reference.


How can I use stepper for specific degree? I use Arduino and I'm beginner. I use the code below, but I don't understand what stepper.step(num) and STEPS in Stepper stepper(STEPS, 2,3,4,5) are, and I want to use stepper for specific degree and I don't know what I can do. for example if I want to use stepper for 40 degree what are STEP and num?

#include <Stepper.h>

// change this to the number of steps on your motor
#define STEPS 100

// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to
Stepper stepper(STEPS, 2,3,4,5);

// the previous reading from the analog input
int previous = 0;

void setup()
{
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop()
{
  // get the sensor value
  //int val = analogRead(0);

  // move a number of steps equal to the change in the
  // sensor reading
  //stepper.step(val - previous);
  stepper.step(25);
  delay(1000000);
 // stepper.step(-5);

  // remember the previous value of the sensor
  //previous = val;
}

-----------------------------------------EDIT #2-----------------------------
my stepper is the first one in this link:
https://grahamwideman.wikispaces.com/file/view/28byj48_models_table.jpg/538898220/604x265/28byj48_models_table.jpg
( I think! )
and I don't know what it means?
------------------------------------------EDIT #3----------------------------
Thank you very much, I saw the link.

  Step Angle (8-Step sequence: Internal Motor alone): 5.625° (64 steps
  per revolution)

and I run this code for 45deg :

#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  //2048
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 2, 3, 4, 5);

int  Steps2Take;

void setup()
{

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 8.11;
  small_stepper.setSpeed(100);
  small_stepper.step(Steps2Take);
  delay(10000);
}

because I understand each turn has 2048 steps, for example if I want to have 1/2 turn, I have to have num=1024 ( 2048/2). ok, So, for 45deg, it's 1/8 turn so I have to set num=2048/8. but for example for 33 deg what should I do?
I thought num= 33*5.61
so for 45deg I use num=45*5.61
you know we have a lot of floating point and I'm not sure we do it correct. right? I'm a little confused.

stepper.step(num)is used to rotate your motor 'num'-step. i.e. num=25, then calling stepper.step will cause your motor do 25-step.

STEPS is number of steps per revolution for your motor. It will be depending on the motor you used. For more information, you can check here.

You have to check for your motor stepper resolution. Most common motor stepper has 200 steps per revolution, which means 1 step is 360/200 = 1.8 degree. If you try Stepper.step(1), your motor will rotate 1.8 degree.

So in your case, if you already found out the resolution of your motor stepper, just do a simple conversion task:

const float resolution  = xx.xx; // put your step resolution here
int step_degree(float desired_degree){
    return (desired_degree/resolution);}

This can be use by calling

stepper.step(step_degree(40)); //rotate 40 degree.

--EDIT--
You can check this link, since it (perhaps) using same motor stepper (24BYJ48)

Based on 24BYJ48 datasheet, it has 5.625 degree resolution / 64 steps per revolution.


Issue in installing Arduino unit library and running with Firmata test application I am trying to update the Arduino library via the library manager and I tried to download it from the link given in the firmata_test program:

  WARNING: Category '' in library ArduinoUnit is not valid. Setting to
  'Uncategorized'
  C:\Users\SAURAB~1\AppData\Local\Temp\arduino_c8217a5b56c170d64dfe4c80a1a205dc\firmata_test.ino:
  In member function 'virtual void test_beginPrintsVersion::once()':

  C:\Users\SAURAB~1\AppData\Local\Temp\arduino_c8217a5b56c170d64dfe4c80a1a205dc\firmata_test.ino:32:3:
  warning: narrowing conversion of '249' from 'int' to 'char' inside { }
  [-Wnarrowing]

  };

  ^

  Multiple libraries were found for "Firmata.h"  Used:
  C:\Users\saurabh2836\Documents\Arduino\libraries\Firmata  Not used:
  C:\Program Files (x86)\Arduino\libraries\Firmata

I'm getting this error. I searched but found no conclusive answer. I'm using Windows 8 64bit and Firmata downloaded from http://www.firmata.org/.

Am I doing something wrong?

The compiler is giving a lot of information. The warnings can be ignored but the "multiple libraries" indicates that there is at least two copies of Firmata installed. Check (search) that you have not got several downloads of Firmata. Worst case reinstall to clean up that.

Cheers!


Adding esp32_komoot_ble library to Arduino IDE I am an absolute beginner with Arduino IDE and I want to build an interesting device I stumbled upon on github
https://github.com/jstiefel/esp32_komoot_ble
Problem is I really can not add it to Arduino IDE. I did the wiring for the lcd and all, but please bear in mind i'm an electrician, with a very basic understanding of arduino/ absolute beginner.
What i'm asking is which is  the "main file" in the src folder so i can rename it 'ino' to work with the arduino IDE  and upload it to the esp32 board?
I downloaded the esp32 library and all the dependencies that says in the readme.md file. I download the esp32_komoot_ble.zip file. Now how do I get the  .cpp and .h files on the arduino IDE and finally my esp32 device. I have been watching tutorial for 1 week now  but could not figure it out yet!
Thank you for everything guys!

The file, that you are searching, is the one, which contains the setup() and loop functions: esp32_komoot_ble.cpp

These functions are part of the Arduino framework and wrap the classic main() function. setup() is called once at startup, loop() after it repeating forever.


Control external device using Java Web Servlet -> Pi -> Arduino -> Device I'm new to the world of Arduino & PI, so far it's been a fantastic experience but I'm now looking to build something a bit more practical.

My plan is for the PI to host a JSP Servlet website.  I'd like to go to a certain page of this site: 'powerCycleDevice' for example where it would pass a parameter in '?=on' or something similar.  This would then be picked up by the Arduino which in turn would then power said device.

It's also be nice to just use it as a monitoring station.  If I have several Arduinos hooked up (and I plan to - think Wallace & Gromit :)) then it'd be nice to view the statistics of each of the sensors.

My problem is not knowing if a: it's possible (I'm certain it is) and b: where to start.

If anyone can lend any advice, hints or tips on where to get started it would be fantastic.  A noob guide or tutorial would be great as I'd then use the info and expand upon it.

Thanks in advance.

You can use Ardulink. It's a java open source project of mine. It can control an Arduino boad. So you have just to write a servlet that call my library. That's it.

See this post to understand how install ardulink in a PI: http://www.ardulink.org/how-to-install-arduino-pc-link-on-raspberry-pi/

You can read a sample code that sends some messages to Arduino you can read this post:
http://www.ardulink.org/how-to-blink-a-led/

The most important statement is Link link = Link.getDefaultInstance();

Link is the Ardulink class you need to send (and receive) messages.


WS2812B strip stopped responding to control I have a WS2812B LED strip (A clone of the Adafruit one I assume, it's from China via eBay) of 60 LEDs. When I got it, it was all fine - I could load the FastLED examples and they would work perfectly. I then tried to write something more custom, which didn't work for whatever reason. Upon re-loading the FastLED examples, I now get absolutely nothing from the strip.

It's being powered by an ATX computer power supply with ample amperage on 5V, and when I remove and then re-add the power connectors the strip does flash, indicating it's getting power and is capable of lighting up. It just feels like something I have done has caused it to enter a state where it won't respond to control.

I've also made sure my sketches are making it to the arduino by loading the inbuilt LED blink sketch, which works, then trying to switch back to a FastLED example which does nothing.

I'm kind of lost as to what could be wrong here.

Did you follow the Adafruit NeoPixels best practices guide?

You may have zapped the first NeoPixel in the group. You should be able to, fairly easily, bypass that. Each NeoPixel has to "reshape" the data for the next one along, so if you damage the first one, no data will reach the others.

I strongly suggest you follow the guidelines in the link, including the capacitor and resistor.


I am new to arduino please help me in understanding this code while (client.connected()) {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);

Why we require char c and what is the use of using this command Serial.write(c)

client.read() returns exactly one byte from the serial input buffer for the port connected with object client. That is why you use a char variable. The name c is not relevant.

The next line, Serial.write(c) then writes that same character to the main serial port.

The code basically reads from one serial port and writes the same data immediately to the other serial port.