Newbie and string of 300 WS2811s I’m trying to make a string of 300 Christmas tree lights where the colour of each of the lights is entirely controllable by my own code. I am a programmer so that side of things is the easy part as far as I’m concerned.

My researches so far have led me (no pun intended) to WS2811s driven by an Arduino. I prefer the look of these to the flat Adafruit-type ones. I don’t own an Arduino yet but have been dipping my toe into this site for quite a while now so am beginning to understand the basics.

I’ve established that I will need to have a fairly hefty 5volt power supply for the LEDs but that the Arduino itself can then run happily on its own USB supply.

Some of the things I’ve read seem to imply that the Arduino will struggle to process my program and supply the data to 300 LEDs at the same time, but it’s not clear what the problem will be. I assume each LED will continue to glow with the same colour until it receives the data for its next colour and the code for “Fire!” which then prompts all of them to switch to their next colour. Is this wrong?

I realise that 3 bytes per LED for 300 LEDs is a fair amount of data to keep having to send up the wire. I will also be having an array in the program to keep track of all 300 colour values.

Will this work? Can you offer any advice that might mean I don’t hit a brick wall somewhere when putting all this together?

I don't think you'll have any problems. The LED's have a data rate of 800kbps, so you can theoretically push out 110 frames per second if your Arduino does nothing but transmit data. If you keep the routine that updates the colors fairly efficient then you'll have nothing to worry about.

Note that the array storing the colors would take up 900 bytes of memory, leaving you with only 1100 bytes for everything else your program would need to store (which should be fine).


Arduino DUE deadlock problem, watchdog not working I am using Arduino DUE in my project. The project is massive (about 7000 lines of code in total, with massive schematic), so I decided not to post the whole code and schematic, except explain the hardware and configuration I am working with:

Arduino DUE;
12V switching power supply;
LTC1660 DAC (used withstandard SPI library);
Nextion HMI (Used with standard library #include Nextion.h        //INCLUDE NEXTION LIBRARY);
DS3231 RTC module on I2C bus (Library used: Wire  #include <DS3231.h>)
24LC256 EEPROM on same I2C bus (Library used: Ext EEPROM #include <extEEPROM.h>)

The base line, is that on power-on the controller just freezes besides, it can't be the problem with power as I get this problem using both 12 V from switching PSU and 5 V USB cable. I can not really analyse the problem, as the deadlock occurs even before the program start to execute content of void setup(). My best guess is that the deadlock occurs due to infinite loops in the Arduino's twi.cpp where infinite loop can occur if the controller receives no acknowledge
bit. But then again I can not be sure here. However when I push restart button on the Arduino or enable Serial monitor in Arduino IDE when the circuit is powered on , it starts to work, and it works just as expected.

After reading the datasheet for the DUE's μC, I've found that it have the watchdog option embedded:

  After a Processor Reset, the value of WDV is 0xFFF, corresponding to
  the maximum value of the counter with the external reset generation
  enabled (field WDRSTEN at 1 after a Backup Reset). This means that a
  default Watchdog is running at reset, i.e., at power-up. The user must
  either disable it (by setting the WDDIS bit in WDT_MR) if he does
  not expect to use it or must reprogram it to meet the maximum Watchdog
  period the application requires. The Watchdog Mode Register (WDT_MR)
  can be written only once. Only a processor reset resets it. Writing
  the WDT_MR register reloads the timer with the newly programmed mode
  parameters.

I've started to explore it, and as I got it, the watchdog is ON by default, and its timer period is 16 seconds by default, so as it is not normally used in DUE, I assumed, that somewhere it is just disabled, and in main.cpp I found the following:

int main( void )
{
   // Initialize watchdog
   watchdogSetup();
   init();
   initVariant();

where watchdogSetup() led to:

void watchdogDisable(void)
{
   WDT_Disable (WDT);
}
void watchdogReset(void)
{
   WDT_Restart (WDT);
}
extern "C"
void _watchdogDefaultSetup (void)
{
   WDT_Disable (WDT);
}
void watchdogSetup (void) __attribute__ ((weak, alias("_watchdogDefaultSetup")));

As I got it, due to this, the watchdog was disabled for DUE by default, and commenting out watchdogSetup(); in int main() would allow the watchdog to work (as watchdog is on at power on by default, according to datasheet).

I've also added the WDT_Restart (WDT); to void loop() of the program in order to kick watchdog every program cycle.

Well, for some reason, that did not help me, and I'm still receiving the deadlock when I power on the controller, even through the watchdog is technically not disabled, after 16 seconds it still do not restart the system. And, pressing the reset button or the Serial monitor in Arduino IDE makes the system run as expected. Am I missing something out? Your help and suggestions are appreciated, shall any additional info be needed, just let me know, I need to get this project running so badly.

By the way, my void setup() function is quite long, and if I set the watchdog to 1 second, using
void watchdogEnable (uint32_t timeout) instead of commenting out watchdogSetup() in main.cpp, and use reset button after power on, I can see the watchdog working as it can't get to void loop() in time in order to reset watchdog (as void setup() takes about 3 seconds due to delays).

Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on.

There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.

The ATmega16u2 can be reprogrammed so that on power-on it provide short "HIGH" period to AT91SAM3X8E reset pin. The program for ATmega16U2 can be found here:
https://forum.arduino.cc/index.php?action=dlattach;topic=167492.0;attach=52901

The updating precision is given here:
https://www.arduino.cc/en/Hacking/Upgrading16U2Due

I've performed the given precision using Arduino UNO as programmer and can confirm that it worked properly.The problem's gone now.


Having trouble assigning colour to my neopixels Hi I was wondering if someone is able to help me! I am currently trying to get a strip of 10 neopixels to change colour. I want to be able to code a random neopixel in the strip to change to either red, blue, green and yellow consecutively after 2 seconds. I am relatively new to Arduino so I'm still learning. I have been using the code below and it does everything that I want it to but I would like to set the colour so they're not as randomised. I found this code online.

#include <Adafruit_NeoPixel.h>

#define PIN 6
#define LED_COUNT 50
Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_RGB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop()
{
  randomPixelColor(100);

}

void randomPixelColor(int wait)
{
  int i= random(strip.numPixels());

  uint32_t c = random(2147483647); // I have no idea what this crazy number does.
  strip.setPixelColor(i, c);
  strip.show();
  delay(1000);

}    // end void randomPixelColor()

I don't even know if this is the right code to be using! Hopefully someone can help me cause I'm so confused.

You already are choosing a random LED. Now you only need to define and use the colors, that you need. Define an array with the colors:

#define COLOR_N 4
uint32_t colors[COLOR_N] = {0x00FF0000, 0x000000FF, 0x0000FF00, 0x00FFFF00};

Also define a static or global variable to hold the current color:

uint8_t current_color = 0;

Then use this array in strip.setPixelColor() with the current_color variable as index:

strip.setPixelColor(i, colors[current_color]);

Now increment current_color for the next color. To go from yellow to red again, you can use the modulo operator %:

current_color = (current_color + 1) % COLOR_N;

You can easily extend to more colors, by writing the new colors into the colors array and setting COLOR_N to the corresponding value.

About the color values: The neopixels use an RGB color model with 8 bit depth. That means, that each component (red, green and blue) occupies exactly 1 byte. Thus there are 256 steps for each component. To describe a full color, you need all three components, thus 3 bytes or 24 bits. The data type, that fits this uint32_t (unsigned integer with 32 bit), though the most significant byte is unused here (if you use an RGBW strip, this byte is the component for the white LEDs).

We can write the number, that is representing a full color, as a hexadecimal value. Each component occupies 2 hexadecimal digits:

0x00RRGGBB

where 0x is the prefix, which marks a hexadecimal number, and RR, GG and BB are the components red, green and blue of the color. So a full red is 0x00FF0000, a full blue is 0x000000FF (the leading zeros are not mandatory, but I think they help readability and comparability).

The color mixing works additive here, just like light does. All components mixed together at the same ratio gives you white, all components to zero means black. Thus you get yellow from mixing red and green the same ratio. So a full yellow is 0x00FFFF00.


Arduino Uno not working after Short-circuit While wiring up my new Arduino Uno R3, I accidentally shorted the 5V pin and the GND pin (for less than a sec). It was powered by a 12V 500mAh power supply through the Arduino DC power jack. . The ON, Rx, X1 and L LED's are glowing continuously, and also, pressing the reset button doesn't have any effect on the LED's and arduino doesn't restarts. How can I get my arduino working again?

The regualator of that 5V Blew up or the diode you need to read the schemtics of the Arduino Uno and check the circuits.

https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf


How to store a string in an object and retrieve it safely later? I'm writing a program where I will be able to toggle between multiple banks, and each bank has 4 presets on it. Right now, I'm trying to give each preset a name that is assigned on creation.

I have an object I called StoredDataManager, which will handle all the banks. In its constructor, I do this:

for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
  Bank bank;
  _banks[i] = &bank;
}

_banks is declared like this: Bank* _banks[NUMBER_OF_BANKS]; in the .hfile of StoredDataManager.

A bank has 4 presets, like this:

Preset* _A;
Preset* _B;
Preset* _C;
Preset* _D;

Which I initialize as this:

Preset preset(presetName, presetData);
...
_A = &preset; ...

Where presetName is "CHR", and presetData doesn't matter, because I'm just trying to get the name to work.

In the preset, the name is saved like this: char _presetName[4];.
It is returned like this:

char* Preset::getPresetName() {
  return _presetName;
}

I try to print a preset's name like this:

Serial.println(_banks[0]->getPreset('A')->getPresetName());

But, right now it simply returns C§.

Why is that? I suspect it has to do with the memory being erased or overwritten.

EDIT:
Here is the code of getPreset:

Preset* Bank::getPreset(char presetLocation) {
  switch (presetLocation) {
    case PRESET_LOCATION_1:
      return _A;
    case PRESET_LOCATION_2:
      return _B;
    case PRESET_LOCATION_3:
      return _C;
    case PRESET_LOCATION_4:
      return _D;
    default:
      return NULL;
  }
}

I think now that I'll turn this into 4 separate functions, like getA, getB and so on, but this what it is the moment. PRESET_LOCATION_1 is just a #define PRESET_LOCATION_1 'A'.

EDIT 2:
I start in the main arduino .ino file with this:

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

This triggers this constructor:

StoredDataManager::StoredDataManager() {
  for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
    Bank bank;
    _banks[i] = &bank;
  }
  _currentBankIndex = 0;
  Serial.println(_banks[0]->getPreset('A')->getPresetName());
}

This is _banks: Bank* _banks[NUMBER_OF_BANKS];.
The initializing of the bank object runs this constructor: (PRESET_LOCATION_1, 2, 3, and 4 just being 'A', 'B', 'C', 'D')

Bank::Bank() {
  addPreset("CHR", "Some data", PRESET_LOCATION_1);
  addPreset("CHR", "Some data", PRESET_LOCATION_2);
  addPreset("CHR", "Some data", PRESET_LOCATION_3);
  addPreset("CHR", "Some data", PRESET_LOCATION_4);
}

Which calls this function:

void Bank::addPreset(const char* presetName, String presetData, char presetLocaton) {
  Preset preset(presetName, presetData);
  switch (presetLocaton) {
    case PRESET_LOCATION_1:
      _A = &preset; break;
    case PRESET_LOCATION_2:
      _B = &preset; break;
    case PRESET_LOCATION_3:
      _C = &preset; break;
    case PRESET_LOCATION_4:
      _D = &preset; break;
  }
}

Then, above in the StoredDataManages constructor, this line is hit:

Serial.println(_banks[0]->getPreset('A')->getPresetName());

And that's where I try to log out the preset name.

void Bank::addPreset(const char* presetName, String presetData, char presetLocaton)
{
  Preset preset(presetName, presetData);

  switch (presetLocaton)
  {
    case PRESET_LOCATION_1:
      _A = &preset; break;
    case PRESET_LOCATION_2:
      _B = &preset; break;
    case PRESET_LOCATION_3:
      _C = &preset; break;
    case PRESET_LOCATION_4:
      _D = &preset; break;
  }
}

I can't see how this is going to work because you are storing somewhere outside a function a pointer to a local variable inside the function. As soon as addPreset exits the variable preset will go out of scope, and a pointer to it will be undefined.

You should probably do a new to make a new instance of Preset which it is then valid to store outside the scope of the function.


Sampling/transmission limits for USB and Arduino UNO R3 I'm very new at this and I need some help. This is a college project that I must do and not even the professor knows for certain if it is possible.

I have to sample two signals at a fixed sampling rate so there is no aliasing effect and it must be done at the same time (switching the ADC from one analog input to another)..

The signal would be then transmitted via USB to my computer. I guess that the transmission rate would be too slow to do this in real time. I will have to store this somewhere in the Arduino board so it can be transmitted afterwards.

Requirements:

It could be done with 8 bit resolution.
Sampling rate of at least 4.8kHz.
Record both signals for at least 0.1 second.

Is this even possible to do with my Arduino UNO R3? If it isn't, it would be with a sampling rate of 1.2kHz?

PS: I could try to lower the sampling frequency necessary by changing the aliasing filter that I built. The theoretical limit would be at about 1.2kHz for the best filter possible.

It is not possible to sample two signals at the exact same time with an
Arduino Uno. The Arduino has only one ADC, so you have to sample one
signal, switch channels, sample the other, switch channels again, etc.
If this is acceptable for your project, then yes, it is perfectly
feasible with an Arduino Uno. But you will have to dig into the
datasheet and program the ATmega328P low-level.

Regarding the sampling rate, you want the ADC to take 9600 samples
per second (4.8 kS/s × 2 channels). This means one sample
every 104 µs. You are lucky: in the default Arduino configuration,
the ADC conversions take exactly 104 µs. frarugi87 and Jot suggest
you reconfigure the ADC for faster sampling. This is useless: the
default sampling speed is already optimal for you application. Leave it
as is.

You also require a fixed sampling rate. This is not possible to do
with software. Configuring the ADC in auto trigger mode is the only
way to get a really steady rate. The ADC can be triggered by a timer,
but in your particular case, it is just simpler to have it trigger
itself. This is called free running mode and it gives a sampling rate
of exactly one sample every 104 µs. Perfect for your application.

Jot also suggests disabling interrupts. Do not do that! Interrupts are
harmless because the ADC manages its own timing. And they are actually
useful: I would use the ADC interrupt to retrieve the conversion result,
send it through the serial port and switch channels in the multiplexer.

If you are happy with 8-bit resolution, I recommend you enable the left
adjust result mode. This way you can retrieve the 8-bit result from the
ADCH register and you won't need to do bit shifts.

  I guess that the transmission rate would be too slow to do this in
  real time. I will have to store this somewhere in the Arduino board so
  it can be transmitted afterwards.

Both options are possible. If you send the data in binary, you will need
a baud rate of at least 9600 bytes/s × 10 bits/byte
= 96 kb/s. You can opt for 115.2 kb/s, which is standard
and widely supported. If you want to store the data, then you will need
9600 bytes/s × 0.1 s = 960 bytes, or about half
the Arduino RAM. This is fine, as the program can be quite simple, so it
won't need more than half the available RAM.

Just to give you some inspiration, I suggest you take a look at this
sound-meter
sketch of
mine. It configures the ADC in free-running mode at 9.6 kS/s and
retrieves the result using the ADC interrupt. I would use the same ADC
configuration for your project, only with left-adjust and with channel
switching performed by the interrupt handler.

Edit: I just wrote a “dual channel oscilloscope” program along the
lines of this answer: dual-scope.c. It's written in plain C, but it
can also be compiled as a regular .ino file. I only tested it with
constant voltage inputs though.

The program ended up being tiny: it uses about 1% of the flash, 1.4% of
the RAM and 3.4% of the CPU power on an Arduino Uno. Meaning you could
add stuff to it if you feel so inclined.


Is EEPROM persisted across program flashes? If I use EEPROM.write(someAddr, someValue) to write a value to an address, how long will that value "stick" to that address before being lost?

If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?

Only if the EESAVE fuse is programmed (it is unprogrammed by default). If not then the EEPROM will be erased when a chip erase command is performed.


Why doesn't my 1602A LCD display text with this code? #include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <Servo.h>

#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo myservo; // create servo object to control a servo

String read_rfid;
String ok_rfid_1 = "6722323b";
String ok_rfid_2 = "99be859e";
int posClosed = 180; // variable to store the servo position for locked
int posOpen = 0; //same for open...

/*
  Initialize.
*/
void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("Scan your card:");
  Serial.println("Scan your card:");
  //Choose which lock below:
  myservo.attach(7); // attaches the servo on pin 7 to the servo object
}

/*
  Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
  read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
}

void open_lock() {
  //Use this routine when working with Servos.
  lcd.print("Servo Unlocking");
  myservo.write(posOpen);
  Serial.println("Servo Unlocking");
  delay(10000);
  myservo.write(posClosed);
  lcd.clear();
  lcd.print("Servo Locking");
  Serial.println("Servo Locking");
}

void loop() {
  lcd.clear();
  lcd.print("test");
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent())
    return;
  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial())
    return;
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  if (read_rfid == ok_rfid_1) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (FRED FARMER)" + " -Access Granted");
    Serial.println(read_rfid + " (FRED FARMER)" + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  }
  if (read_rfid == ok_rfid_2) {
    open_lock();
    lcd.clear();
    lcd.print(read_rfid + " (JOHN DOE) " + " -Access Granted");
    Serial.println(read_rfid + " (JOHN DOE) " + " -Access Granted");
    delay(10000);
    lcd.clear();
    lcd.print("Scan a card:");
    Serial.println("Scan a card:");
  } else {
    lcd.clear();
    lcd.print(read_rfid + " -Access Denied");
    Serial.println(read_rfid + " -Access Denied");
    delay(10000);
    lcd.clear();
    lcd.print("Scan your card:");
    Serial.println("Scan your card:");
  }
}

I have tried running the Arduino library's "Hello World" example, and it successfully runs the text onto the screen. Therefore I have determined that it is not a hardware problem, rather a code problem. It occasionally does display "ff" on the LCD, but that's it.

Pins number 12, 11 are used by some other library in your code. And that's the reason there is no LCD output. Change pins/connections from 12, 11 to 7, 6.

Then your code uses lcd.clear() too often, so whatever data you display vanishes before you were able to read. Don't clear the display unnecessarily.


Why are the files not being created correctly? I have been through http://arduino.cc/en/Hacking/LibraryTutorial but I can't do it. Whenever I create a new sketch and try to save it as .cpp or .h from the Save As button in the Arduino IDE, it gets saved as _cpp and _h. I am not able to create a library this way. How do I create a new library? What am I missing here?

When you save a file using the Save As button from the Arduino IDE, it saves the current file as a sketch i.e. as an .ino file.

To create a .cpp and .h files for working on a new library, you need to create the files alongside a sketch. For this, you can use the Tab button on the top right (circled in red).

Click on it, and select New Tab. You will get a bar at the bottom of the screen asking for a file name. Enter the name with extension (test.cpp) and press Enter.

Your file has now been added to the current directory.

Similarly, follow the same steps for creating the .h file.

Once your library is complete and ready to ship, you can move the .cpp and .h files to a separate directory and then add it under libraries.


Interface a mobile phone's finger print scanner with arduino Is it possible to salvage a fingerprint scanner from an old and dead smartphone and use it with Arduino? I am not talking about writing an android program and send data to Arduino over Bluetooth or WiFi, I am talking about wiring up fingerprint scanner of a mobile phone to Arduino.

In general: It depends. We can only talk about the general situation, not about details, because we don't know the exact sensor type. You are facing some serious problems when doing this.

Without a part number or something like this, we cannot say, how the sensor communicates with the phones mainboard. It might or might not be a communication interface, that the Arduino has or can be made capable of.
The sensor and it's interface might be proprietary, which would mean, that there is no public documentation about the interface and how it works. Reverse Engineering something like this need mostly a big amount of time and experience with various electronical systems.
As Shyam Singla already pointed out in his/her answer, most (if not all) Arduino compatible fingerprint sensors don't send the actual fingerprint image, but do the difficult image handling and recognition by themselves. The Arduino only get's status information (for example if a previously saved fingerprint was detected). On a phone, this is most likely not the case. The main processor of the phone has way enough power to do the calculation by itself. It doesn't need to offload them to an external chip like the Arduino needs to. (Also this gives the vendor the opportunity to update the recognition software later on with a simple OS update.) That means, that the sensor will most likely only send images and you would need to do the image handling and recognition on the Arduino. AVR based Arduinos (like the Uno or Nano) are totally undersized for this.
The connection pins of the sensor will be very small and difficult to connect, especially if you are a beginner.
You would have to use level shifters and voltage regulators to interface between the 5V devices Uno/Nano and the sensor, which will most likely work with a significantly lower voltage (at max 3.3V, most likely less).

Using FPGAs to tackle some of these problems is possible, but also very challening. If you need to ask this question, this is most likely out of scope. (A friend of mine did program a FPGA for his physics master on university. It can be very difficult.)

All in all I would say, it is not worth the effort to even try this. Instead buy an Arduino compatible fingerprint sensor.


Do I need 3 voltage dividers to control ESP8266 I am buying an ESP8266 and the plan is to control it serially from an Arduino. I am going to use a voltage divider(Using a voltage divider is temporary and I know the cons of using voltage dividers).

I calculated out the values of the voltage divider and I am going to use 220 ohm and 440 ohm value resistors to get 3.3 volts and 250 ma from the Arduino 5v pin so I can power vcc and ch_pd on the ESP8266.

The question is do I need to use a separate voltage divider to connect Arduino TX to ESP8266 RX and Arduino RX to ESP8266 TX. Or will it be safe to connect RX and TX directly to Arduino RX and TX.

Honestly I am extremely new to this and I don't even know if I am going at this right. If I am tell me.

For ESP 3.3V power supply, I'd recommend a distinct 3.3V regulated supply.

Of course, the Arduino UNO already has a 3.3V output but it may not supply enough current to the ESP (current consumption can go up to almost 200mA): UNO 3.3V pin is limited to 50mA. So do not use it or you may roast your UNO.

Using resistors to output 3.3V from Arduino 5V might be possible (the UNO 5V pin can provide ~400mA) but it would be a big waste of energy because you'd have to use low resistor values to be able to supply 200mA for instance.

You might possibly use a 7833 regulator with additional caps to provide 3.3V from Arduino 5V pin (or Vin directly if your UNO is powered through the DC power jack, not USB)

For ESP RX a voltage divider is foreseeable but it may trigger issues due its switching response time, which may be too slow when transmitting data at high baud rates. I recommend using a MOSFET based level shifter:

The advantages of this circuit are:

it has the fastest switching response time
it can work in both directions (3.3V -> 5V and 5V -> 3.3V)

You can also buy some cheap ready-made breakouts using this circuit and offering several level shifters.

For ESP TX, I'd also recommend the same level shifter circuit as for RX (if you can make one, you can make two).


PHP/My SQL Database -> to Arduino Serial Monitor I'm using this domain http://www.decathlon.commonarchitecture.ca/ to host my phpmyadmin database and php code. I would like to read a specific column of the database in the serial monitor, displaying each number one right after the other. I'm unsure of whether to work with a GSM shield, an Ethernet shield or an Arduino wifi shield. Here is my php code (indents are off I know):

<?php

 $dbhost = "mysql.commonarchitecture.ca";
 $username = "arduinodb";
 $password = "*******";
 $db = "arduinodb" ;

    mysql_connect("$dbhost" , "$username" , "$password");
     //echo "Connected" ;

    //select db
    mysql_select_db($db);
    //echo "Connected to db" ;

  $sql="SELECT * FROM data";

  $records=mysql_query($sql);

 ?>

 <!DOCTYPE html>

 <title> Consumption Data </title>

 Day
 Date
 Water Consumption (liters per person)

 <?php

    while($data=mysql_fetch_assoc($records)) {

         echo "
";

         echo "".$data['id']."	";

         echo "".$data['date']."	";

         echo "".$data['value']."	";

         echo "
";

     }//end while

     ?>

The code works, however I'm unsure of how to go about reading the data on an Arduino (very new to Arduino)

Here's my Arduino code paired with an ethernet shield

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192, 168, *, *);

EthernetClient client;

char server[] = "www.decathlon.commonarchitecture.ca";

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

  // attempt a DHCP connection:
  Serial.println("Attempting to get an IP address using DHCP:");
  if (!Ethernet.begin(mac)) {
  // if DHCP fails, start with a hard-coded address:
  Serial.println("failed to get an IP address using DHCP, trying
  manually");
     Ethernet.begin(mac, ip);
  }

  Serial.print("My address:");
  Serial.println(Ethernet.localIP());
}

void loop()
{
    // connect to the server
    if (client.connect(server, 80))
    {
        // print to serial monitor
        Serial.println("connected...");
        Serial.println("ARDUINO: forming HTTP request message");

        // send data the server through GET request
        client.print("GET /index.php?value");
        client.println(" HTTP/1.1");
        client.print("HOST:  ");
        client.println(server);

        Serial.println("ARDUINO: HTTP message sent");

        // give server time to receive request
        delay(1000);

        // get the response from the page and print it to serial port
        // to ascertain that request was received properly
        if(client.available())
        {
            Serial.println("ARDUINO: HTTP message received");
            Serial.println("ARDUINO: printing received headers and
script response...\n");

            while(client.available())
            {
                char c = client.read();
                Serial.print(c);
            }
        }
        else
        {
            Serial.println("ARDUINO: no response received / no response
received in time");
        }

        client.stop();
    }
    // do nothing forever after:
    while(true);
}

My issue now is in getting the Arduino to read my php data, can I not use an http GET request to display data in my serial monitor? Am I using this function properly? There's a ton of documentation on posting Arduino sensor data to the web using php/my sql but not as much on retrieval of set data back into the serial monitor. Here's what the monitor reads currently...

Attempting to get an IP address using DHCP:
My address:192.168.*.*
connected...
ARDUINO: forming HTTP request message
ARDUINO: HTTP message sent
ARDUINO: no response received / no response received in time

Firstly if you really are using an Uno then you cant read the data without putting the uno on a network (obviously).  To do this you could get either a Ethernet shield of a Wifi shield.  A wifi shield is probably based on an ESP8266 and you talk to it by creating a serial connection (using a software serial port).  There are plenty of examples and messages on here to get you started.

Once that's working you need to write a web client (note that this is much easier if you program the ESP8266 rather than the Arduino).  Your client needs to request the page from your server and then parse the returned data and extract the field you want.

While you are waiting for you network shield to arrive you could practice doing it on a Windows PC with Visual Studio, it will be easier to debug.


Honeywell HPMA115S0, sensor not start again after stop I use HPMA115S0 sensor with Arduino for Nodemcu, i can read it value but face one problem. The sensor not work after send stop measure command (fan not start too).

const int StartPmMeasure[4] = {0x68, 0x01, 0x01, 0x96};
const int StopPmMeasure[4] =  {0x68, 0x01, 0x02, 0x95};
...
void stopSensor() {
  if (isSensorStart) {
   Serial.println("INFO: Stop sensor");
   sendCommand(AutoSendOff);
   sendCommand(StopPmMeasure);
   isSensorStart = false;
 }
}

void startSensor() {
 if (!isSensorStart) {
  Serial.println("INFO: Start sensor");
  sendCommand(StartPmMeasure);
  sendCommand(AutoSendOn);
  isSensorStart = true;
 }
}

I have the same problem here. I'm using a HPMA115S0 with an ESP8266 and found out that the sensor don't respond in general if you are doing a deep sleep with the ESP. If the ESP wakes up, the sensor does not respond on commands till you remove the 5 volts of the HPMA for a short time to make an "hard reset" of the sensor.

I think there is a problem with the ttl-level on the UART-RX-line of the HPMA. Because if you're pulling the rx-line of the sensor manually to ground (maby the ESP is doing this if he goes to deep sleep or wakes up), the sensor does not respond after that.

I spend very much time in this phenomenon. I used different pins on the ESP for software UART and used the hardware UART, problem still exists.
I assume that the ESP pulls all his pins on ground level for too long. That means that the stop bit (high-level), which the sensor wants after 8 bits are transmitted, is not present. This leads to strange behavior of the sensor.
I don't have a digital storage scope to see the level on rx-line, so this is only a presumption. But I don't have this problem, if the ESP idles with an sleep-command.
Maby you are also doing a deepsleep with your ESP which results in the same problem?

Best regards


HC-05 bluetooth module I was able to connect my HC-05, pair it with my phone, and I can see data in the Serial Bluetooth Terminal Android App.  But when I try to connect it to a certain application it says it cannot find it.  Can the application force a certain version of Bluetooth?  Am I missing something?  Thanks.

The HC-05 modules use bluetooth 2.0. Certain apps would only be compatible with bluetooth 4.0 devices (BLE - Bluetooth Low Energy), such as an HM10 or AT09.

It could be that your app requires the device to use v4.0+. Are you able to find, and pair with the device using your android's default bluetooth device scanning/pairing features?

Assuming that your app does not require v4.0+, have you removed the connection from 'en'/'ch_pd' to 3.3v? If that was still connected (which is a required connection to enter AT command mode), then your bt module would not be able to accept incoming pair requests etc.

hope this has helped. :)


Wireless Communication Between Raspberry Pi 2 and multiple Arduinos I have about 10 Arduinos that have sensors attached, which report information back around my house. I would like to have a RPi 2, because they have nice screen and GUI options, to collect the information and display it accordingly.

I am looking for success stories on what wireless parts you used to get these two working. The the wireless must be able to penetrate a brick wall about 120ft away.

Thanks for replying, I edited the response above.

There's many options you could use.

The simplest, though most expensive, would be to equip all your Arduinos with WiFi shields and connect a USB WiFi dongle to the Pi.  The Pi could run in AP mode (investigate hostapd) so you don't have to connect them all to your internet router.

A cheaper option, though harder to work with on the Pi, would be to use the incredibly cheap but popular nRF24L01+ modules.  There are libraries aplenty for the Arduino, but I am not aware of code for the Pi (though there probably is somewhere if you google for it).

And then there are options in between which vary in price and complexity.

Of course, you haven't mentioned range, only a brick wall.  The right choice could well be affected by the range of communication you need - do you go for the bare nRF28L01+ with a range of maybe 10m, or the one with the power amplifier and SMA antenna with a range of many hundreds of meters? Is WiFi going to be long enough range? Would a 433mHz module be a better choice?  All these questions and more need to be answered, and the best way is for you to describe your setup in detail, including what the longest range is you need to deal with, what amount of data you will be sending, do you need ultra low power to save batteries, etc.


Help understanding how to drive Step motors with Arduino I am building a 2-Axis gantry system to dispense some thermal paste on boards. I was given two stepper motors in order to do so along with a gantry already built that will arrive in two weeks. So basically I just need to figure out how to drive them on the software side. However the boss demands testable code to be finished by EOB tomorrow, despite the hardware not being here yet. So I drafted some quick code that should drive a stepper motor, it's an easy open loop system, but I'm struggling. The operator will home the gantry after each cycle so it's just a matter of getting the motors moving.

My method was as follows:

#include <Stepper.h>
*declaring the stepper and all that goes here*
void loop(){ etc.
   basic logic flow stuff
   stepper.step(20); // to move forward twenty steps
   stepper.step(-20) // to move back twenty steps

However my boss says this is incorrect as I need to be giving the steppers both step and direction.

After some tenuous google searching he recommended I use the AccelStepper library to fix this problem. After looking through this library I'm unsure how this will give me anything I need (distances are so small acceleration is useless) and how I am not giving it both step and direction in my original example code, I give it steps (20) and a direction with my negative/positive coefficient.

Am I correct in my thinking? Is there a better solution neither of us have found? I'd love to understand not just that I'm wrong, but why I am.

I think there is some mis-communication between you and your boss. I do not think your boss is stupid, but I do think he's talking on a different level as you do. You're using arduino which covers up a lot of hardware-interfacing, especially with steppers.
I suggest you check out this video: https://www.youtube.com/watch?v=bngx2dKl5jU
(I haven't watched it, but It will help you get more into the ideas of your boss)

Now you understand your boss's view, you can try to show him your view. When talking about steppers/arduino and how you can put in negative steps, he might think you're talking trash, as steppers require different pairs of coils to be active depending on the direction. (which is all handled by arduino)
The best way is to provide him a visual guidance, so that he can see the relation with his (hardware-view) on the issue and your software/arduino solution.

You could make something like the image below.
I'm not sure if this is what you're trying to tell him.
I guess you should mention/add that the software on the arduino takes integer values, with negative values being clockwise or such. And that the arduino will convert this to the right coil pairs or direction and step.

P.S:with direct driving, I think he meant toggling the right pins at the right moments so that the stepper will rotate, basically what the stepper library does for you. Maybe he wants you to implement something like the stepper library (is it an internship? so that you can learn?) I suggest you check some tutorials on how stepper motors work, and how you can drive them 'directly' withouth the use of libraries.


Blew my arduino pro mini s4 named component While working on my project I supplied 12v to my pro mini through raw input and then a s4 named component smoked and my pro mini  stopped working . It didn't turn on either through vcc or raw. The voltage regulator seems completely fine. Can I repair my pro mini. Please help.

Many Arduinos have a Schottky diode between the power connector and the voltage regulator as a protection against accidental reverse polarity connection. The official Pro Mini, or the Sparkfun variant, does not.
So you can either de-solder the diode or break it off the board using diagonal cutters and then replace it with either a similar diode -- or with a solder-bridge if you are confident about never connecting power the wrong way around.
It's possible (likely even) that other components that look OK visually are actually damaged. Especially if you can't power the board by connecting a regulated 5V supply to the VCC pin.


MPU-6050 with Arduino - postmortem I'm working with MPU-6050 with Arduino Uno.

I copied the code below from Arduino Playground - MPU6050.

Code :

  // MPU-6050 Short Example Sketch
  // By Arduino User JohnChi
  // August 17, 2014
  // Public Domain
  #include<Wire.h>
  const int MPU_addr = 0x68; // I2C address of the MPU-6050
  int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
  void setup() {
    Wire.begin();
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    Serial.begin(9600);
  }
  void loop() {
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    Serial.print("AcX = "); Serial.print(AcX);
    Serial.print(" | AcY = "); Serial.print(AcY);
    Serial.print(" | AcZ = "); Serial.print(AcZ);
    Serial.print(" | Tmp = "); Serial.print(Tmp / 340.00 + 36.53); //equation for temperature in degrees C from datasheet
    Serial.print(" | GyX = "); Serial.print(GyX);
    Serial.print(" | GyY = "); Serial.print(GyY);
    Serial.print(" | GyZ = "); Serial.println(GyZ);
    delay(333);
  }

Firstly, I want to know every details about this code, AcX, AcY, AcZ, GyX, GyY, GyZ what all these mean ?

It will be nice with some visual representation.

Secondly, If I change the delay to 500 from 333, will it cause a problem ?

This type of stupid question because, I can't find any relatable figure with 333 except 1000/3

I think that  AcX, AcY, AcZ, GyX, GyY, GyZ are raw acceleration and gyroscopic values recieved from mpu6050 in the corresponding directions. in order to recieve them a procedure is followed.

 Wire.read();

means two registers are read and stored in the same variable

   accelerometer_x = Wire.read()<<8 | Wire.read();

reads registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L) that is ,
it deals with bitwise operation to shift the values 8 bits left (multiplying it by 256).
This enables addition ("|" or "ored") of two datas in order to continuously output the accelerometer data !! Without this you would not be able to see the increasing and decreasing sloping values .
Further, the print just displays the instantaneous values on screen.

If you want to go in deapth of the code, you can visit this site for line to line description !!

https://www.mschoeffler.de/2017/12/09/example-application-gy-521-module-mpu-6050-breakout-board-and-arduino-uno/

 delay(500);

Totally depends on your project, i don't see any forecoming issues if you will make 333 go 500 !! It will just stablize the output on screen there for a bit longer (for .5 seconds)


Arduino stk500_getsync(): not in sync We have an arduino pro mini, we are trying to trying to upload sketch the controller but we are prohibited, as the arduino attempt to upload the sketch, it display an error of: not in sync.

We are pretty new in this are, so any help would be much appreciated.

Our setup is: -Breadboard -Connection to adapter: USB Serial. -Arduino Pro Mini as a controller

Through the Arduino Programming Client.

The processor and the port are setup op properly.

The strange thing is, it has worked sometimes these past days..

Much Thanks.

Mieer

If your error is intermittent, check all of your wiring to ensure there is nothing loose, and try hitting the 'reset' button the Arduino as the compile message changes to uploading, in case your serial adapter isn't resetting the Arduino properly.


Blynk, but continue program if Blynk connection fails I'm having an issue with Blynk.begin(auth, ssid, pass);
The problem is, when it fails to connect to the wifi, the rest of the program does not continue.
I'm using a Wemos D1 and it is also controlling some relays based on a temperature sensor.
But when there was a power outage and power comes back on, the programs should continue whether the wifi is working or not, so that relays can still be controlled by the temperature sensor reading.
What happens now is if there is a wifi issue when Wemos D1 is starting up again, the program simply stops in the void setup() at Blynk.begin(auth, ssid, pass); and the rest of the program cannot be executed.
Anyone knows how to avoid this?
Kind regards,
Peter

You can try my Blynk_WM or Blynk_Async_WM library with their Blynk.begin() functions are not blocking.

Check Why using this Blynk_WiFiManager with MultiWiFi-MultiBlynk features
Why using this Blynk_WiFiManager with MultiWiFi-MultiBlynk features
You can see that the system automatically detects and connects to the best or avaiable WiFi APs and/or Blynk Servers, whenever interruption happens. This feature is very useful for systems requiring high degree of reliability.
Moreover, this Blynk.begin() is not a blocking call, so you can use it for critical functions requiring in loop().
Anyway, this is better for projects using Blynk just for GUI (graphical user interface).
In operation, if WiFi or Blynk connection is lost, Blynk.run() will try reconnecting automatically. Therefore, Blynk.run() must be called in the loop() function. Don't use:
void loop()
{
  if (Blynk.connected())
     Blynk.run();

  ...
}

just
void loop()
{
  Blynk.run();
  ...
}

It's also beneficial to search in Blynk Forum for more information and examples


Which are the unused digital pins after L293D motor shield is installed on a Arduino Uno board? I have just started my first project on Arduino. I have an Arduino Uno and an L293D motor shield.
I have installed the motor shield on the Arduino Uno board and the motor shield covers all pins of the Arduino Uno board. The motor shield is connected with four gear motors and one servo motor.
Can I use digital pins 2-13 to make some LED flashing circuit?
Which digital pins are used by the Motor shield and which pins are not used?

It is L293D motor shield. A0 and A5 are used in the code. Four DC motors and one servo motor is used.

If this is the same board as seen on Banggood Which may also be seen at Adafruit
The schematic shows most of the digital pins in use
D3  - PWM2B
D4  - DIR_CLK
D5  - PWM0B
D6  - PWM0A
D7  - DIR_EN
D8  - DIR_SER
D9  - PWM1A
D10 - PWM1B
D11 - PWM2A
D12 - DIR_LATCH

The analogue pins A0-A5 are still free - these can be used as digital pins.


Using OR with a while loop I am trying to get two limits to or on the same while statement. Can this be done?
while (digitalRead (home_limit)) {

This works for one(1) limit,
But when I try using two(2) limits  is does not work. I can't find the proper configuration. I tried this.
while (digitalRead (home_limit1) || (home_limit2)) {

I also tried other combinations with no luck.
Does anyone know how to do an or (||) statement with a while digital read?

digitalRead() is a function. It takes one parameter (the pin number) and returns the state of that pin.  It's that return value that you want to OR with another. Which means you have to read the state of both pins, separately, and OR the results together:
while (digitalRead(home_limit1) || digitalRead(home_limit2)) {
    ....
}


Using Arduino to create a countdown that unlock a box Am new to Arduino. So permit me if I sound so novice.
I want to create a countdown device (a clock that will countdown or something) that will unlock a box when the time is up.
As an example, let say, I set the clock to start counting down from 2hours, but when it remains 5mins for the countdown to elapse, the box will unlock
What are the things needed for it to work as all examples I see are mostly for opening the door or box when the temperature changes.

This sounds as an escape room puzzle.
From an electronic point of view you need something to lock/unlock the box like a servo motor, a stepper motor or (best option) a normally closed solenoid. You might need some components to drive such locking mechanism, like a mosfet or transistor (possibly a darlington), depending on which device you choose and what voltage it requires to operate. Simplest solution is a servo motor which doesn’t require anything, but has a low torque, meaning the box can easily be forced. Most robust and reliable solution is a NC solenoid, common ones are 12V so you’ll need a p-channel enhance mosfet and a couple of resistors to drive it from an Arduino.
To display the time you’ll probably want to go for an LCD, common ones are 16 col x 2 rows, most have an integrated chip to drive them using only a few wires.
Apart from that, you need a battery pack (voltage and power depending on your locking circuit choice) and may be a push button (for safety unlock).
From a software perspective you want to create a loop which starts by locking the box and then counts down the time: when the time left is less than 5 mins it activates the unlocking mechanism circuit.
int current = 0;
const int max = 2 * 60 * 60; // 2hrs in sec
const int grant = 5 * 60; // 5mins in sec
bool unlocked = false;

void setup() {
    lock();
}

// executed once every second
void loop() {
    // any safety open check should be performed here...
    // if still locked and less than 5 mins to end
    if (!unlocked && current > max - grant) {
        unlock();
    }

    display(current++);
    wait(1000);
}

// does what it is needed to unlock and sets the unlocked variable to true
void unlock() { ... }

// does what it is needed to lock and sets the unlocked variable to false
void lock() { ... }

void display(int secs) {
    int h = secs / (60 * 60);
    int m = (secs / 60) % 60;
    int s = secs % 60;
    // display on LCD the values above with the proper formatting
}

A couple of notes:

if you go for a normally closed solenoid be sure to have a way to get inside the box if something goes wrong with your circuit or if the batteries get drained
you might want to have a hidden button or other way to force the unlock, especially for debugging and testing


Turn Arduino on only by double tapping switch? I don't have much experience with electronics. I was wondering if it is possible to create a push button switch, which will turn on the device only if it is tapped twice in quick succession?

If it is tapped only once, then the device should behave as if nothing happened (i.e. tapping the switch again after a specified duration should have no effect).

You can use something like the ATtiny25/45/85 then have a button cell battery to power it, make it a sleeper that listens to the button, and when clicked it activates the Arduino.

The Arduino is then turned on keeping a capacitor alive holding a transistor active, then add another button that drains the capacitor, thus closing the transistor and turning the Arduino off. Or you can program the ATtiny to drain the capacitor if the button is held down.

A button cell on an ATtiny in sleepmode should last around a year or so.

Just some information to get you going further:

http://playground.arduino.cc/Learning/arduinoSleepCode : The sleeper code, it is power saving using interrupts.

http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/ : How to burn an ATtiny using Arduino. Fairly simple, did it myself a few times.


Can I speed up the Leonardo bootloader? Inspired by an example question before beta, can I make the Leonardo bootloader take less that 8 seconds to run? It is very slow and I want to speed it up somehow.

Detailed instructions on how to shorten the bootloader time of Leonardo etc. are explained [here] (as stated by @Chris Stratton).

The crux of the matter was to redefine the timeout period

/* ./arduino/hardware/arduino/bootloaders/caterina/Caterina.c */
#define TIMEOUT_PERIOD 8000

to a lower value.

However I do not have such issues with Leonardo it boots very fast.
So this issue depends on your environment.

There is also OptiBoot, an alternative bootloader that really boots faster link:


Time information from GPS receiver: how to tell whether it is fresh or stale? I see that TinyGPS++ library extracts time information from GxRMC and GxGGA NMEA sentences streamed by GPS receiver. However, in my experiments I observed that both of my GPS receivers generate GxRMC sentences with time data in them at least once a second even when they have no access to satellites.

I presume that the time data comes from the internal clock of the receiver (and is maintained between warm startups). This is perfectly OK. However, I would like to know what measures are required by NMEA specification to ensure the reliability of this time data.

Am I correct in assuming that the device itself is supposed to understand that after certain period of time its internal clock will diverge? And that after that period the device will by itself stop pumping out these GxRMC sentences, until it gets a chance to see a satellite and re-sync its internal clock? Or should I expect to see the next field in GxRMC sentence to change from A to V?

If not, then what is the proper way to ensure that I receive "satellite time" (or close to that) or nothing at all?

Most of the GPS modules keep on sending the data in the NMEA format whether they have a GPS fix or not, however, you can parse the GPS data to find whether the data is the latest data received from the GPS or not. If you look at the definition of the NMEA data here, there are a few variables in the data that you can use to find whether the data is the latest data from the GPS or not.

You can use the "Fix Quality" in GPGGA as well as "Validity/Receiver warning" in GPRMC for your module. The tinyGPS indeed has both of these variables being parsed.

In the tinyGPS library, if _gps_data_good is true then the data coming from the GPS module is the latest data it received from the GPS satellites. The program uses either the fix or validity to determine this (Refer to the library here and here).

You should just keep checking this variable to find whether the current data is the latest from the GPS or is it being calculated internally.


Oxygen sensor up to 50% Are there any oxygen sensors that measure up to 50%?.

As I understand, there are sensors that measure only in range 0-30%.

Is it possible to increase the threshold of sensitivity of the sensor?

You can try SO002 or DS-TR250.

  Is it possible to increase the threshold of sensitivity of the sensor?

I don't think its possible. Perhaps you can tweak the reading sensitivity, but since the sensor are mostly analog, it's not possible. And maybe that also the reason the 2 sensors I've mentioned above have several series based on their measuring threshold.


When i press a button to subtract 1 from 5 it skips to 3 When i press a button to subtract 1 from 5 it skips to 3, it's the same when I add 1 to -5 it skips displaying - 4 and goes straight to -3.

This is the code that i am using:

//Testing the use of addition and subtraction with the menu options.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;
int calc_total;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){
    adc_key_in = analogRead(0);

    if (adc_key_in > 1000) return btnNONE;

    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 150)  return btnUP;
    if (adc_key_in < 300)  return btnDOWN;
    if (adc_key_in < 450)  return btnLEFT;
    if (adc_key_in < 700)  return btnSELECT;

    return btnNONE;

}

void setup(){
   lcd.begin(16, 2);
   lcd.setCursor(0,0);
   lcd.print (calc_total);

}

void loop(){

   lcd_key = read_LCD_buttons();
   calc_total = constrain(calc_total, -4, 4);

   switch (lcd_key){

       case btnRIGHT:{
            lcd.clear();
            calc_total = calc_total - 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
       case btnLEFT:{
            lcd.clear();
            calc_total = calc_total + 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
     }
}

Your main problem is that you aren't looking for a change in buttons. You're only doing your adding or subtracting while a button is pressed.

That means, all the time you're holding btnLEFT in your total is incrementing until it hits your limit.

You need to remember the button state from the previous iteration of loop() and compare it to the current state - and only if they differ do you need to do anything.

Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.


ISR vs state change detection on button Hi I was wondering if a digitalRead state change detection could be saved in a variable like counter++, just like you can do with an interrupt function.

arent these two operations almost the same?

like have an external circuit with a  reed closed by a magnet, to take the place of a momentary push button,

The 2 techniques described in the question are commonly referred to as "polling" and "interrupt".  Either will work.  Polling is suggested for beginner programmers and when time is not important. Such as scanning an array of human controlled buttons. Whereas interrupts are usually reserved for when time is of the essence.  Such as synchronizing a camera's release switch with a strobe flash.

Also, consider polling as a simple to understand, easy to test sequence of events that will always happen in the expected order.  While interrupts can happen at any time and all interruptible code has to be written to tolerate being interrupted.

Often, debouncing is the more difficult problem when combining mechanical switches and microprocessors.  A good fundamental exercise is to write your own debounce program.  However, an Arduino debounce library is already available.


Using SoftwareSerial for the serial monitor Most programs follow this route: They have a Serial.begin() for the serial connection between PC and Arduino (the serial monitor) and they use SoftwareSerial for a device.

Can you go the other way around? Can you use SoftwareSerial for the communication between PC and Arduino, and Serial for a device?

Short answer: no.

Pins 0 and 1 an an Uno are directly wired to the PC communication chip. You could make a board that was wired differently and connected SoftwareSerial to the PC, but you would have to switch it back to pins 0 and 1 when uploading to the arduino somehow.

On an arduino leonardo "Serial" for communicating with PC over USB is different from "Serial1", which is connected to pins 0 and 1 on the board. You can use both simultaneously, so if you really need to use hardware serial and PC comms at the same time, I recommend you buy a leonardo.


Speaker-dependent Voice Recognition I would like to install speaker-dependent voice recognition in a robot equipped with Arduino Uno compatible boards.
Specifically, I want to record the robot's name beforehand and have it respond when I call the robot's name.
Although it is not an Arduino, there is a person who has developed a function that I would like to realize with the M5StickV.
This person used isolated_word.py, a library published by Sipeed, as a reference.
【K210】マイク搭載版M5StickV,Sipeed Maixシリーズで音声認識をする
After some research, I found Maix_Speech_Recognition in the library of Maixduino, which can use Arduino IDE.
Apparently, it uses Mel-frequency cepstrum coefficients analysis of speech input, and then uses dynamic time stretching to find the similarity.
The MFCC uses the K210 FFT on the Maixduino.
Arduino Uno does not have an FFT accelerator, but it can do FFT.
Therefore, I thought it would be possible to use Maix_Speech_Recognition for specific speaker speech recognition on ArduinoUno compatible devices.
Question

Is it possible to use Maix_Speech_Recognition for speaker-dependent voice recognition on Arduino Uno compatible boards?
What part of Maix_Speech_Recognition should I modify to make it work on Arduino Uno compatible boards?

Is it possible to use Maix_Speech_Recognition for speaker-dependent voice recognition on Arduino Uno compatible boards?

No. It's not.

What part of Maix_Speech_Recognition should I modify to make it work on Arduino Uno compatible boards?

Don't even think about it. The UNO cannot do anything even remotely like speech recognition of any form without adding extra specific speech recognition hardware.
Just get a K210 board - they're cheap enough.


Broken Arduino Uno, works over USB but cannot take DC in My Arduino Uno (r3) board seems to be broken. It can still be powered over USB, and can store/run code properly, but the DC power in system appears to be crippled. I'm not entirely sure what happened, but I was most likely being careless with the power in and the vin pin. I'm not sure what component(s) are broken, but when I plug in 12v into the barrel connector, the uno doesn't power on. I can read about 0.6 volts from the 5 volt pin, and at some other locations on the board. Besides the 0.6, the only other voltage I read is the 12 volt, although it is slightly lower than the power supply, which outputs about 12.2 volts. How can I go about fixing this? Or is it even worth it?

As you have noticed, measuring voltages is the first step. Here's some voltages for you and what they mean if they aren't there. These are all assuming precisely 12V in through the barrel jack. They are in order of "priority" - start at the top and work down, the first one that fails is your culpret (i.e., the barrel jack feeds VIN through the diode, VIN feeds 5V through the 5V regulator, and 5V feeds 3.3V through the 3.3V regulator).

Roughly 11.4V on VIN - if it's not there the input protection diode has blown
5V on the 5V pin - if it's not there the 5V regulator has blown
3.3V on the 3.3V pin - if it's not there the 3.3V regulator has blown

Fixing it may be as simple as replacing the faulty component identified above - although they are all surface mount and some are more tricky to replace than others.  That said, if it is (as it sounds) the 5V regulator that has gone, that is one of the larger components (SOT-223) so should be eaiser to replace. Also it's dirt cheap - I get them for a few cents each in bulk.


Getting the contacts/ storing contacts to SIM card I have the GSM shield and is there any ways to get the stored contacts on the SIM card? It seems that the GSM library does not support writing data onto/ reading data from the SIM card?

My aim is to store the SIM card's phone number and some variables onto the SIM card itself, such, I would not need to change the program from time to time.

All I need to do is enter all the variables in the SIM card via any mobile phone (perhaps by storing the variables as contacts, as phone book function should be very common on phones).

What have you researched so far? Following the link you have given for the shield, about the third line of the description is a reference to the AT Command Set used by the chip.
I just did a couple of quick searches through it and found:

2.2.4  ATD><n> Originate phone call to number in memory
3.2.26 AT+CPBF Find phone book entries
3.2.27 AT+CPBR Read current phone book entries
3.2.28 AT+CPBS Select phone book memory storage

probably a good place to start.


Using MPU-6050 without I2C My target is to use multiple MPU-6050 at once, I searched on the internet and found that they can be hooked up really simply. Just connect in parallel and use I2C-Scanner. Then get those addresses and use normally.

But I can't find another address, there appears to be just one address 0x68, that is the reason why, I want to connect my other MPU-6050 in other pins.

How this can be achieved ?

As you can read in the MPU-6050's datasheet, it uses the I2C address 0b110100X, where X is the state of the pin AD0. If you wire AD0 to ground, the address will be 0b1101000, whereas if you wire it to Vcc it will be 0b1101001. That is equivalent to the addresses 0x68 and 0x69.

That means, that - depending on how you wire AD0 - you can have 2 distinct MPU-6050's on the same I2C bus (you cannot have devices with the same address).

If you really need to connect more than 2 of them, you have to use an I2C multiplexer like PCA9544A, which will divide the bus down to sub-busses.

EDIT: Usually the address pins of I2C devices are set permanently by wiring them either to ground or Vcc. The sense of the address system is, that a slave device will stay at it's address, not changing it. But as Jot reported in the comments and as the Arduino Playground site of the MPU-6050 confirms, you can actually set the address pin of the MPU-6050 during operation.

You need 1 digital output pin on your Uno for each MPU, which then get's tied to the MPU's AD0 pin via a voltage divider. The last part is important: You need a voltage divider, because the MPU is a 3.3V device, while the Uno works with 5V. To avoid frying the address pin, you need to step down the voltage.

Then you would use the address pins to set all MPU's to one address (let's say 0x69). When you need to communicate with one of them, you toggle it's address pin, which will change it's address (in this case to 0x68). Then you can use the normal I2C workflow with this address (0x68). When you are done, you can put this MPU back to the other address by again toggling the address pin. You can repeat this with any of the connected MPU's, which can be many (I think the limit here is the I2C bus itself with it's wires capacity).

This is a workaround and not really, what the I2C bus is meant for. But it seems to be valid solution. Just be sure, that the addresses, that you communicate with, are always unique. Contacting an address, which belongs to more than 1 device, will block your I2C bus.


Rotary encoder on Uno and interrupts issue This question is regarding a project using an Arduino Uno.

I have one of these quadrature rotary encoders.

I'm using a slightly modified version of the code from the article, Quadrature Encoder too Fast for Arduino (with Solution), which uses a library called digitalwritefast.

My version of the code on pastebin - I modified to use different pins for the Uno and a single encoder:

#include <digitalWriteFast.h>  // library for high performance reads and writes by jrraines

#define c_LeftEncoderInterrupt 0
#define c_LeftEncoderPinA 2
#define c_LeftEncoderPinB 3

volatile bool _LeftEncoderBSet;
volatile long _LeftEncoderTicks = 0;

void setup()
{
  Serial.begin(115200);
  pinMode(c_LeftEncoderPinA, INPUT);
  digitalWrite(c_LeftEncoderPinA, LOW);
  pinMode(c_LeftEncoderPinB, INPUT);
  digitalWrite(c_LeftEncoderPinB, LOW);
  attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
}

// Interrupt service routines for the left motor's quadrature encoder
void HandleLeftMotorInterruptA()
{
  _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB);   // read the input pin
  _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
}

void loop()
{
  Serial.print(_LeftEncoderTicks);
  Serial.print("\n");
  delay(20);
}

I am attaching output A of the encoder to pin 2 and output B to pin 3.

This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying c_LeftEncoderPinB accordingly).

I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).

When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.

What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.


Communication with ESP, HTTP requests or WebSocket? Here is my problem. I'm working on making a wifi addressable RGB LED (like WS2812b) controller, I'm using an ESP8266 as the hardware. I'm also creating a phone application for controlling the device and setting different modes. What I'm doing right now is that I communicate with the module by sending GET commands from my phone app. For example to change the brightness I send http://192.168.4.1/I125I Then on the ESP side the code is as follows:

WiFiClient client = server.available();
  if (client) {
  String inData= client.readStringUntil('\r');
  if (inData.indexOf("I")!=-1){
 BRIGHTNESS=str2int(inData.substring(inData.indexOf("I")+1,inData.lastIndexOf("I")));
}}

It works, but I'm not sure if this way of sending data is efficient at all. if change colors too rapidly the ESP resets. I recently found another code that uses GET and POST commands but different methods are used, like the following

server.on("/brightness", HTTP_POST, []() {
    adjustBrightness();
  });

Then inside adjustBrightness function brightness is adjusted. This way it looks more professional but Is it more efficient?

I recently bought a commercial RGB LED controller that uses ESP8266 as its core. I tried to see what the phone app sends to the controller using the Drony app. For my app I could see all the get command the app was sending

192.168.4.1/I255I

192.168.4.1/R200RG90GB76B

...

but for the commercial controller I just saw one connection, something like "157.10.12.10:5172"

Is this using websockets?
Is using websocket a better way? is it more robust?

I'm writing the code in Arduino IDE.

This way it looks more professional but Is it more efficient?

No, the differences are minuscule. It's only really the location of any parameters that are different - either as part of the URL (GET) or as part of the body (POST).

  Is this using websockets? Is using websocket a better way? is it more robust?

No, it's just a TCP connection (or maybe UDP connection, it's hard to tell from your description) sending unknown data. It's impossible to tell what the data us from the port number, you would have to actively sniff the data and work out what it is.

Yes, it is generally more efficient doing that kind of thing (though not necessarily more "robust") - HTTP is a very generic system that can transfer many different kinds of data in a request so needs large amounts of superfluous information that is not applicable to controlling an LED, whereas a simple TCP or UDP socket only transfers the minimal amount of data needed to get the job done.


Controlling DC motor speed? I'm trying to control a DC motor through L293D motor controller

const int controlPin2 = 4; // connected to pin 2 on the H-bridge
    const int enablePin = 3;   // connected to pin 1 on the H-bridge

void setup(){

  pinMode(controlPin2, OUTPUT);
  pinMode(enablePin, OUTPUT);

  digitalWrite(enablePin, LOW);
  digitalWrite(controlPin2, LOW);

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

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

    switch (inByte) {
    case '0':
  digitalWrite(enablePin, LOW);
   digitalWrite(controlPin2, LOW);
 Serial.println("OFF");
      break;
    case '1':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 50);
    Serial.println("CW slow");
      break;
          case '2':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 100);
    Serial.println("CW slow +");
      break;
          case '3':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 150);
    Serial.println("CW medium");
      break;
          case '4':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 200);
    Serial.println("CW fast");
      break;
          case '5':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 250);
    Serial.println("CW fast +");
      break;
    case '6':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 50);
    Serial.println("CCW slow");
      break;
      case '7':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 100);
        Serial.println("CCW slow +");
      break;
      case '8':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 150);
        Serial.println("CCW medium");
      break;
       case '9':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 250);
        Serial.println("CCW fast");
      break;
}
}
}

It is working well except 1 to 5 are reversed:

1 should be the minimum speed
5 should be the maximum.

But it is back to front:

5 is the minimum speed
1 is the maximum speed

Any ideas?

So first thing, you should try to be more disciplined with your code formatting and the question...

FYI: it's best to use #define as it doesn't use memory for storing pin numbers... It's like Find and Replace in a text editor, this:

const int controlPin2 = 4; // connected to pin 2 on the H-bridge
const int enablePin = 3;   // connected to pin 1 on the H-bridge

Becomes this:

#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

So this is the tidied up code, you can see the problem is a lot more approachable when the code is indented consistently, and good use of spaces and new lines is used...

#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

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

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

        switch ( inByte ) {

            case '0':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '5':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}

So your actual problem is that you need to reverse cases 1, 2, 3, 4, 5 to be 5, 4, 3, 2, 1...

There are two solutions:

Inelegant: would be to simply change the case numbers, they don't have to be in-order.
Elegant: copy and paste the code in each of the 5 cases about.

The result of option 2 is as follows, please feel free to confirm this is working?

#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

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

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

        switch ( inByte ) {

            case '0':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '5':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}


Arduino network with minimum wiring For a parking management system I am going to create an Arduino network.

An Arduino with an ultrasonic sensor will be placed above each parking space. If car is parked at specific location Arduino will inform master (PC) and also turn RED light ON.

I am not sure how I can make network with minimum wiring. I think RS485 will be suitable for this purpose.

There will be almost 200 Arduinos in a network. I have following questions in mind:

Should I go for RS485 protocol or something else?
Can RS485 support 200 devices as there will be only short communication (i.e device ID and parking status)?
I am planning to lay CAT6 cable. Two pairs will be used for power transmission and two pairs will be available for communication.

This sounds, to me, like a job for CAN.  It's the current de-facto standard for industrial inter-MCU cabled connections. It's used, not only in automobiles, but also to control elevators and almost all other modern industrial distributed applications.

Note that CAN is designed to only support up to 30 nodes, so you would need to split your network into sections and have groups of nodes amalgamated together into a single sub-network.  For 200 nodes you may want 10 subnetworks - that is, 20 nodes connected together to one super-node, which is then connected to the "backbone" CAN bus.

However, CAN can be run at lower baud rates than normal, and that increases the number of nodes you can have on any one network segment. It potentially (bus capacitance permitting) support thousands of nodes.

Another option is to use CAN to connect multiple "master" nodes together into a backbone, and then those "master" nodes connect to a number of sub-nodes using LIN (which is cheaper to implement than CAN).

LIN can support a maximum of 15 nodes (plus one master node) per network, so you can get a theoretical maximum of 29*15 (assuming 1 CAN node is the connection to the PC), or 435 nodes.

You could also use RS-485, but that is also limited to around 30 "unit loads", and the number of nodes you could put on one segment is dependent on the "load" each node imposes. In practical terms it's rare to go over 30-40 nodes on a single segment, and grouping nodes together into sub-networks (as above with CAN/LIN) would be needed. So you may as well use the current standard for this kind of communication, and use CAN/LIN.


Arduino is not responding to a Tiny RTC I2C modules, How to fix? We have an arduino due with a Tiny RTC I2C module and we're trying to print the current time to the serial monitor. However its not working, currently its printing the time as 2165/165/165 (Monday) 165:165:85 (it should read something like 2016/3/3 (Thursday) 4:15:00). Interestingly it continues to read the same thing, it doesn't change, even if I remove the module from the breadboard completely. I have tried this with two of the modules and both have the same exact results. Does anyone know how to fix this?

My schematics are the same as shown here:
http://www.hobbyist.co.nz/?q=real_time_clock

This is my code, it's just the example code from the imported library for the clock.

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
   #define Serial SerialUSB
#endif

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

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

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(3000);
}

You have a couple of problems (although the lack of pull-up resistors is not one of them, because the board you linked has pull-up resistors on it).

The DS1307 needs to operate at a minimum of 4.5 volts, so you can't connect it to the 3.3V pin on the Due. (You need to supply it with 5V).
However the Due is a 3.3V device on its data pins, and thus you can't connect the DS1307 directly to SDA/SDL or you will damage the Due.

Thus you need to supply the clock board with 5V, and use a bi-directional logic-level converter, such as this (using two logic-level MOSFETs):

You can buy level-converter boards, but as you can see, one is easy enough to make up.

Now the clock chip runs at 5V, but the logic levels are converted to 3.3V for the Due.

I tested this with mine, and it worked OK.

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

RTC_DS1307 myclock;

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

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

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    Serial.println();
    delay(3000);
}

Output:

2016/3/6 12:0:20
 since midnight 1/1/1970 = 1457265620s = 16866d

2016/3/6 12:0:23
 since midnight 1/1/1970 = 1457265623s = 16866d

2016/3/6 12:0:26
 since midnight 1/1/1970 = 1457265626s = 16866d

A useful technique for debugging is to run the "I2C scanner" I have on my I2C page. The code is:

// I2C Scanner<!-- language-all: lang-none -->
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

If you don't see your device appear in the Serial Monitor, there is no point wondering why the date doesn't change, because it hasn't found the clock at all. You should see something like this:

I2C scanner. Scanning ...
Found address: 104 (0x68)
Done.
Found 1 device(s).

How the level converter works

For more information, read the Philips Application Note AN97055

In brief (taking SDA as an example):

If neither side is driving SDA low, then VGS is zero (they are both 3.3V) and the MOSFET does not conduct. Hence each side is "pulled-up" to their respective voltages. The low side is pulled up to 3.3V and the high side is pulled up to 5V.
If the low side drives SDA low, then VGS is 3.3V which is high enough for the MOSFET to conduct. Since it conducts it also drags the high side low as well (overpowering the 10k pull-up resistor).
If the high side drives SDA low, current initially flows through the drain substrate diode of the MOSFET (it will be a diode drop above 0V, namely 0.7V), lowering the voltage at the source, until VGS is high enough for the MOSFET to conduct. Once it starts conducting then the low side is pulled further lower.

  Do you have an actual photograph of this?

I've pulled it all apart days ago, however thankfully I took a snapshot before I did.

To be honest, the schematic is easier to follow. When looking at photos it can be hard to see exactly what is plugged into where.


Managing timer intervals using millis at random intervals I am doing a project which needs to meet the following specifications.

  On receiving an SMS arduino will start switching 1st relay on after some
  time duration(say 30 Seconds) relay 1 will be turned off and it will now turn on 2nd relay for (say 20seconds) so on 1>2>3>4.

The problem im facing is managing the time intervals between the switching process,i did think of using millis() i.e (currentMillis-previousMillisx>Intervalx) as in blinkWithoutDelay ,how ever this will work only once as i dont not know when will the next SMS come to the system ,if the user decides to send the message after 1hour currentMillis-previousMillisx will always return true so i cannot keep the motor on for (Say 30 seconds) and same will happen with all 4 cases.

If there is any alternative logic for this problem please suggest me or can i just add RTC for my project to manage time easily

Thank You

I do not really understand your problem. More specifically,
“currentMillis-previousMillisx will always return true” does not make
sense, as it is not a boolean expression (it's unsigned long).

Anyway, the technique shown in blinkWithoutDelay is the way to go. Here
is my (untested) version:

const int relay_count = 4;  // we have 4 relays
const int relay_pins[relay_count] = {2, 3, 4, 5};
const unsigned long durations[relay_count] = {30000, 20000, 15000, 10000};
bool sms_received();  // you implement this one

void loop()
{
    static int current_relay = -1;  // meaning: no active relay
    static unsigned long last_switch;
    unsigned long now = millis();

    // If no relay is active, wait for an SMS.
    if (current_relay == -1) {
        if (sms_received()) {
            // Switch on first relay.
            current_relay = 0;
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }

    // Otherwise, switch relays when it is time to do so.
    else if (now - last_switch >= durations[current_relay]) {
        digitalWrite(relay_pins[current_relay], LOW);
        if (++current_relay == relay_count) {
            current_relay = -1;  // no active relay
        } else {
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }
}

BTW, you did not specify what should happen if you receive an SMS while
one of the relays is active. I assume the SMS are only acknowledged when
no relay is active. Otherwise you would have to change the code.


Problem in defining a variable as multiplication I have a simplest code to turn on and off a led. The variable holding time definition is onTime, using Arduino Nano.

When it is written as: onTime=1000*30, all is good.

When onTime is greater than this, if loop does not return true value when needed ( see code below ).

BUT when writing it implicit as onTime=60000, and not onTime=1000*60 code run OK.

I'm guessing that value of 30*1000 - has to be something with int value.

CODE:

int enbPin = 10;
bool onState = true;
unsigned long onPeriod = 60*1000; // <----
unsigned long startTime = millis();
void setup() {
  // put your setup code hee, to run once:
  Serial.begin(9600);
  pinMode(enbPin, OUTPUT);
  digitalWrite(enbPin, onState);
  Serial.println("START");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (millis() - startTime >= onPeriod ) {
    onState = !onState;
    startTime = millis();
    digitalWrite(enbPin, onState);
    Serial.println(onState);
  }
}

unsigned long onPeriod = 60ul * 1000;

ul makes 60 to unsigned long and then the calculation has place for result.

without ul the constants and the result are int and it overflows


Arduino PID controller for Triac I am designing a new soldering station which will use a 24 V ac soldering iron.

I started to make some research and I designed a few steps of the soldering station. I will use a 24Vac/100VA toroidal transformer. I will use a 24V/50W soldering iron with K type thermocouple. For the thermocouple I will use a LM358 amplifier. Please have a look at the attached schematic and code. The code is not ready yet and I need some help in making the connection between the PID library and output in the code.
The voltage on the soldering iron looks like: https://ibb.co/CMF1gQ0
If I rotate the pot, nothing happens on the screen of the scope.

https://ibb.co/vdDRmnJ

I wrote a few lines of code but I don't know how to make the connection between the PID library functions and the interruption function and the other variables in my code.

Please have a look at the code and at the schematic and tell me what you think...
I am waiting for your help.

#include <PID_v1.h>

int AC_LOAD = 1;    // Output to Opto Triac pin
double set_value = 0;
double input = 0;
double output = 0;

PID aaa_PID(&input, &output, &set_value, 1, 0.05, 0.25, DIRECT);

void setup()
{
  aaa_PID.SetOutputLimits(0, 128);
  aaa_PID.SetMode(AUTOMATIC);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65
  int dimtime = (75*output);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay (for 60Hz use 8.33)
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  int set_point = analogRead(A1);
  set_point = map(set_point, 0, 1023, 150, 400);
  int in = analogRead(A0);
  input = map(in, 0, 550, 25, 400);
  set_value = set_point;
  aaa_PID.Compute();

}

I see several issues here.

The most serious is in the wiring of the Arduino. The first argument of
attachInterrupt() is an interrupt number. On the Uno, “interrupt 0” is
wired to the pin “digital 2”. This is where you should connect the
output of the zero-crossing detector (ZERO_OUT).

Then, as noticed by Juraj, there is the issue of the interrupt handler
taking too long to execute. This is generally considered bad practice,
and it has some negative consequences on the working of the Arduino core
like, e.g., the millis() function will be completely off. I do not
think, however, that this is a serious issue for you. There is one
single time-critical bit in your program, which is the generation of the
triac trigger pulses. You really do not care about millis() or any
other time-related things. Thus, at least for the initial version of the
program, I would not care too much, and just let the interrupt handler
delay as needed.

The third issue has been noted by chrisl in a comment: there is a race
condition with both the main program and the interrupt handler accessing
the same output variable. Race conditions are a nasty kind of bug
because usually things work fine “most of the time” and then fail at
unexpected times. I would not recommend, however, to run
myPID.Compute() with interrupts disabled: that may throw off the
timing of your triac pulses. Instead, compute the delay required by the
interrupt, save it to a temporary variable, then copy it to a variable
shared with the handler. Only the copy needs to be done with interrupts
disabled, and that takes only a handful of CPU cycles:

// Variable used by zero_crosss_int().
// Do not forget the `volatile' qualifier.
volatile int dimtime;

void loop() {
    // PID and associated computations.
    set_value = map(analogRead(A1), 0, 1023, 150, 400);
    input = map(analogRead(A0), 0, 550, 25, 400);
    aaa_PID.Compute();
    int tmp_dim_time = 75*output;

    // Critical section executed with interrupts disabled.
    noInterrupts();
    dimtime = tmp_dim_time;
    interrupts();
}

Edit: If things do not work, you should try to debug piece by piece.
Sending debug messages to the serial port should help, although serial
communication is likely to be significantly slowed down by the
long-running interrupt handler. As an alternative, you can use the triac
control pulses as a debug aid, maybe with the heating element unplugged.
For example:

In loop(), set dimtime to a value proportional to set_value.
Turn the pot and look at the FIRING_PULSE signal. Does the pulse
width vary proportionally to the pot position? Is it in sync with the
Vin zero-crossings?
Set dimtime proportional to input. Heat the thermocouple by some
external means. Does FIRING_PULSE vary as expected?
Set dimtime proportional to output, but keep the heating element
unplugged. How does the pulse change as you move the pot or heat the
thermocouple?