LED and MOTOR "ON" when A BLE DEVICE APPROACH ESP32 MICROCONTROLLER DFR0575 I have this code that is working perfectly but I want my device to start vibrating too (right now only the led is working)

On a Wemos Battery Module I have simply connected the vibration motor on the same PIN of the LED and it works perfectly.

Now I want to do the same on an Beetle ESP32 Microcontroller DFR0575. I used the same code But I can't make the module vibrating (The led light is working perfectly)

this is the code:

 #include <BLEAdvertisedDevice.h>
   #include <BLEDevice.h>
   #include <BLEScan.h>

   const int PIN = 2;
   const int CUTOFF = -50;

   void setup() {
     pinMode(PIN, OUTPUT);
     BLEDevice::init("tkr");
   }

   void loop() {
     BLEScan *scan = BLEDevice::getScan();
     scan->setActiveScan(true);
     BLEScanResults results = scan->start(1);
     int best = CUTOFF;
     for (int i = 0; i < results.getCount(); i++) {
       BLEAdvertisedDevice device = results.getDevice(i);
       int rssi = device.getRSSI();
       if (rssi > best) {
         best = rssi;
       }
     }
     digitalWrite(PIN, best > CUTOFF ? HIGH : LOW);
   }

It is generally very dangerous to drive any motor directly from a digital output pin. Motors often need way more current, than the digital pin can provide. Based on the answer to this question, an ESP8266 can provide 20mA or 12mA depending on current direction (may be a bit different for an ESP32, but not substantially). Drawing more current, than the pin can provide, can lead to the destruction of the output hardware of the pin. It is not easy to say, when this will happen, because it depends not only on the current draw, but also on time and fabrication variation.

Also a motor is an inductive load, which means, that fast changes (for example turning on and off) will induce a reverse voltage in the motor coils. These can easily be very high relative to the supply voltage and thus destroy you output pin or even the complete microcontroller.

I cannot give you a full reasoning, why it works with the first board, but not with the second. I think, it has to do with the above.

You should always do 2 things, when driving motors with a microcontroller:

Use a motor driver circuit: You can either buy a ready to use motor driver or you can build one yourself. If you only want to turn the motor in one direction (as with a vibration motor), all you need is a MOSFET, which will act as a switch between the motor and the power supply. This switch get's controlled by the Arduino's output pin (which only needs to supply a very low current for switching). You can google "MOSFET as a switch". Be sure to use a MOSFET, that can provide the needed current and that is good in saturation for the used gate voltage (the working voltage of the microcontroller).
Use a flyback diode: The reverse induction voltage can also hurt MOSFETs. You want to let these voltage spikes quickly plenish by letting the current flow to ground. You can do this with a flyback diode. That is a diode, that bridges drain and source of the MOSFET. It is oriented so that block for normal operation (the normal positive supply voltage). When the MOSFET get's turned off, a great negative voltage will build up in the motor, but since the diode is conducting in this way, the voltage will safely flow to ground, so that the induction voltage cannot hurt the other electronic parts.


Efficient periodic wake up for sensor reads I've been tasked to do an initial design for an Arduino setup that needs to run very infrequently.

Basically, I'd like the system to wake up daily to take some sensor readings and report them back to a central site (the mesh network for this will be my next stage).

Since these things are going to be run on battery, I need it to be as insanely efficient as possible, with minimal power drain when not reading the sensor.

What facilities does Arduino have to do this?

Please refer to http://playground.arduino.cc/Learning/ArduinoSleepCode

it explains the details of a the sleep command and interrupts to re-a-wake. Where the power savings is from putting the resources individually into low power mode.

In your solution, you may want to put everything in low power, except power_timer1_disable(). Where timer1 would be configured to provide an overflow interrupt, say every 1 minute or longer and then go back to powering all off and return to sleep.

Note the article also mentions that the UNO's power supply is a linear regulator, which is very in-efficient. You may want to use your own. You can also get away with just running directly off of 2-3 AA's, if your other circuitry does not care. If this, then I would also suggest enabling the brown out detection, to ensure low battery does not get funny.


Arduino WiFIWebSever - why client.println()? I need to modify the WiFiWebServer example on the Arduino website but I am having some trouble understanding the code. I am hoping to get some advice from the community on the client-server relationship in this example so I can better modify it to suit my needs.

The problem I am having is the jump between server commands and client commands. Initially I see server commands; server.begin() in setup and server.available() in the loop. The commands quickly shift, however, as nearly all the other commands in the loop become client.println()'s.

I understand the initial client commands that deal with whether the client is available and whether it is still connected. The part I don't understand, however, are the client.read and client.println commands. Even client.read makes some sense to me since I want some communication from the client side but why does the example use client.print? The Arduino webpage defines the WiFiClientPrintln as data you write from the client to the server that it is connected to. Wouldn't I want to use server.print since the Arduino in this example is the server and the client is the computer I use to view the webpage that I built on the server?

I am using the WiFIWebServer example as a template for my project. The goal is to have the Arduino take sensor readings and post them on a webpage it hosts by acting on the server. This is quite similar to the example but I notice that I have slow update/transmission speeds and errors when a different client connects to the server. For example, if I view the website on my computer, I get the data fairly consistently If somewhat slow. If I try to view the same website off my mobile device, however, I have problems connecting, may need to refresh several times and the webpage crashes on the computer.

I am trying to troubleshoot the issue but going through the code I can't figure out the reason for the client.println()'s instead of server.println(). Even if that isn't the cause of my multi-client issue, I would like a better understanding of the code before going forward so would appreciate any guidance you can provide.

The confusion you have arises from the context of the command.

The server.* commands manipulate the server instance - that is, the actively listening socket that is waiting for connections.

The client.* commands change their meaning depending on if you are a server waiting for connections or a client that is making a connection.

In the latter case client.print() sends data to the server.

In the former case, on a server, the client.* commands refer to a specific client that has made a connection to the server.  Using client.print() in this instance sends data to the currently connected client.

So "client" can be thought of as "the connection between me and the remote end" however that connection was created - either by "me" specifically connecting to the remote end, or the remote end connecting to my "server" instance and a new "client" being spawned from it for this one connection.

Remember - a client can only connect to one server, but a server can have many connections from many different clients, and it is those client connections that you talk to.


Send Photo with Arduino Uno I'm new at Arduino projects. I googled but I couldn't quite get an answer.

I've got:

Arduino Uno R3 clone
4 pin push button
3 color RGB LED Module
HC06 Bluetooth-Serial Module Card
Arduino PIC Camera Module OV7670

In my project, when the button is pushed, the Arduino takes a photo from the camera module and sends it with an HC06 Bluetooth Module to an Android device. And it receives the answer to turn on the Led green or red.

The main problem is how can I capture the photo and send it with bluetooth? I can handle the Android side.

EDIT 1

I reviewed that code: OV7670 FIFO on GitHub.

In the "Take Picture" method, I understand that the OV7670 continuously grabs frames and stores them in itself. I send it a signal to load a frame on Data Out pins. (D0-7) It loads first 8 bytes on the pins and in Arduinoo, in the for loops for height, width and byte for each pixels, I read in it from D0-7 and send a signal for next byte array.

But I can't understand how to connect the OV7670 to the Arduino. In code, there are conts called WRST, RRST, WEN, VSYNC and RCLK. On the OV7670 I've got SIOC, SIOD, VSYNC, HREF, PCLK, XCLK, D0-7, RESET and PWDN pins. How can I connect these pins like in the github link?

By the way here is my OV7670, I read there are different versions of OV7670:

I have looked into something very similar and I think the reason you are finding it difficult to find information is you are viewing the full system.  Break it down into smaller chunks and you will get more chance of finding a match.  So lets look at the camera and then the rest of it.

I think that the reason you can't get an answer for this is that you can't do what you want with what you have.  My research seems to say that the OVO7670 camera needs a separate micro processor and 'special' RAM to work (can't remember what is special about the RAM at the moment).  There is a board that does this called a 'PIXY', but its not cheap.

On the plus side, connecting an Arduino to Android via blue tooth should be quite simple there should be lots of examples on how to set up the Arduino side.  You then need to define to convey your messages between your server an client and I know you aren't asking how to turn a LED on and off from an Arduino. (If you are please see the Example Blink).

Hope that helps

EDIT

I think you should have 18 pins on you OV7670.

3v3 - 3.3v
Gnd - Ground
SIOC - Input - I2C Clock
SIOD - I/O - I2C Data
VSYNC - Output - Vertical Synch
HREF - Output - Horizontal Synch
PCLK - Output - Pixel Clock
XCLK - Input - System Clock
D7 - Output - Data bit 7 (MSB)
D6 - Output - Data bit 6
D5 - Output - Data bit 5
D4 - Output - Data bit 4
D3 - Output - Data bit 3
D2 - Output - Data bit 2
D1 - Output - Data bit 1
D0 - Output - Data bit 0 (LSB)
RESET - Input - RESET - Low to reset
PWDN - Input - Power Down - High to activate


At dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt While using dimmer circuit with esp8266, at dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt. at the output inductive load is connected like TABLE FAN , it has not any type of adapter, its AC line device.

where, the dimming range is 0-128 .
0=ON (no power clipping) means load should be ON.
128=OFF means load should be OFF.

Is this happens with dimmer circuit normally while load connected [TABLE FAN] or I am doing something wrong?
Also , can we use this value(128) for switching purpose? --means whenever we put the dimming=128 the load will be stay OFF,and power consumption stops towards load, as switch works.

i am newbie and trying esp8266 dimmer for first time.

here , the line voltage is 230-240 volts AC, 50Hz power supply .

I am referring this circuit as it is and code also, only the change is dimming value taken using serial communication

here i am using inductive load (TABLE FAN).

`

  const int interruptPin = 14;
int AC_LOAD = 4;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  Serial.begin(115200);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), 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)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx)

  int dimtime = (75 * dimming);  // 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) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {

   dimming = Serial.read(); // dimming value is taken from serial for
                               dimming the load

}`

int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

The code comments explicitly tell you that the range is 0-128; while non-trivial to do safely, digging out a scope to understand what exactly happens on overflow could be interesting (for example, it may skip alternate half cycles), but the obvious solution is to never command values outside that range, and clamp any out-of-range values which might be requested over the serial port to the limits.

Given that the timing is done unreliably in software, the precise phase behavior of your zero cross detector may be different than the original author's and the line frequency and pulse width constants may or may not be correct for your location, it's not really surprising that you are seeing 128 fall outside the limit of proper behavior rather than just within it.  Likely you want to be conservative in what you allow.

To avoid inconcistency, even better than clamping the maximum value, you may simply want to treat everything above a chosen delay limit as an absolute "off" by simply finishing the ISR immediately without firing the triac at all.  This may prove a lot simpler than trying to reliably find a delay limit that is "almost entirely" off without sometimes slipping over to firing right at the start of the next half cycle - and who really uses the "barely even on" range anyway?

Technically, depending on what the actual memory access width and alignment rules of the ESP8266 are, the sharing of a potentially non-atomic variable between the main and interrupt contexts could cause a one time glitch when it is changed (though even that is unlikely for your expected range of values, especially if you do the limiting before assignment to the shared variable). However, the atomicity concern can be simply remedied by using a volatile unsigned char (or more portably including stdint.h and using a volatile uint8_t) as the shared variable. The volatile keyword is used to require that the compiler actually calculate a variable that may not appear to be used, and actually store it in memory rather than merely cache it in a register.

It's worth noting that the software timed dimming, while somewhat portable is not particularly reliable, and may at high degrees of delay mean the processor spends almost all of its time in the ISR.  For this reason it is generally better to use a hardware timer for this purpose, however that then becomes more chip-specific.  If you are hoping to have things life WiFi running on your ESP8266 at the same time, you'll almost certainly want to move to a hardware timer to avoid glitching.

Ultimately it seems that the tutorial your are following is a poor one, such that doing a complete from-scratch reimplementation would be wise.  Additionally, mains-powered dimming circuits present many safety and reliability concerns even when driving a lightbulb - and it is by no means clear that your triac and snubber circuit are safe to use with an inductive load.  This is a challenging project, and not necessarily an appropriate one to attempt without deep experience.  You might want to consider using a DC fan PWM-controlled from a well-engineered low-voltage power supply instead.


ArduinoJSON v6 - Passing buffer as function parameter I'm new to ArduinoJSON - so perhaps it is a newbie's question.... but I wish to pass a StaticJsonDocument into a function as a parameter ( later on it should be implemented in a library ).

exmaple below shows test_1 what I wish to obtain, but by duplicating StaticJsonDocument, which I don't want to do.

How can test_1 should be written (as I tried in test_2)?

#include <ArduinoJson.h>

StaticJsonDocument<200> doc;

void createJSON() {
        doc["sensor"] = "gps";
        doc["time"] = 1351824120;

        JsonArray data = doc.createNestedArray("data");
        data.add(48.756080);
        data.add(2.302038);

        // Generate the minified JSON and send it to the Serial port.
        serializeJson(doc, Serial);
        Serial.println("JSON is created:");

        // Generate the prettified JSON and send it to the Serial port.
        serializeJsonPretty(doc, Serial);

}

bool test_1(StaticJsonDocument<100> _doc){
        serializeJson(_doc, Serial);
        return true;
}

bool test2(const JsonObject& _doc){
        Serial.println("HI");
        serializeJson(_doc, Serial);
}

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

        createJSON();
        test_1(doc);

}

void loop() {
        // not used in this example
}

The StaticJsonDocument is a template class. The template value in <> is here only the size of the internal buffer, but every size used generates a different class. (memory usage!)

To have the parameter of the function take an StaticJsonDocument version instance, it must be the same version or a common base class. In this case the base class is JsonDocument.

If you don't use the reference symbol & the parameter is copied. In this case StaticJsonDocument<200> _doc or JsonDocument _doc would create a copy and that copy would be modified in the function. The object used as parameter value would be unchanged - empty.

So use

void test2(const JsonDocument& _doc) {
  Serial.println("HI");
  serializeJson(_doc, Serial);
}


Long term stability of bluetooth connections I have two Arduino Megas with HC-05 on Serial1 connected to a Raspberry Pi 3b+ via bluetooth, using the HC-05 and the RPi's built-in bluetooth, and python's pySerialTransfer library to make the connections.

For reasons I am still trying to root cause, the bluetooth connection gets severed a few times an hour. Ideally, I'd get hours to perhaps a day between severed connections; is this a realistic goal?

Over a course of a few days, my testing has shown:

Mega#1 median connection duration is 10 minutes & 88 minute max duration; 25 bytes sent by RPi->Arduino, and by Arduino->RPi every 0.2sec
Mega#2 median connection duration is 38 minutes & 153 minute max duration; 4 bytes sent by RPi->Arduino, and by Arduino->RPi every 0.2sec

During this testing, they're completely stationary within about 12" of each other, so range should not be an issue.

My RPi code detects a lost connection by virtue of failure to receive a message within 5 seconds, and attempts to reestablish the connection, and that is successful about 80% of the time.  I have a second-tier of lost-connection recovery - resetting the HC-05 via an Arduino-triggered MOSFET - if a message isn't received by the Arduino in ~20 seconds, that works in the remainder of the cases, so I'm ultimately able to systematically recover within a max of about 30 seconds.  However, this lost connection for ~10-30 seconds every 10-60 minutes causes a poor user experience for my remote controls.

The Python errors given for about 95% of the failures are a lack of a receipt of a heartbeat message from the Arduino to the RPi python; about 5% give a unspecific [Errno 5] Input/output error error.

While I'm running down multiple theories via day-long stability tests (longer byte transmissions are more error prone? there's some bug in my Arduino code causing crashes, so remove all logic except the send/receive code to test?), I've read a few posts about how finicky & fragile bluetooth can be, and so I'm curious for some thoughts about the general goal / attempt to get a longer-term (hours to a day or more) connection.

Have folks been able to achieve this with the HC-05 on Arduino?  Or is a dropped connection every 10-60 minutes just something one needs to deal with through robust code?  Thank you.

Bluetooth communication works with fixed time intervals that both communication partners have to agree during the advertising and connection phases. Such an agreement could be: "While connected, lets' meet every second. If one does not show up during 3 meetings, let's leave the connection state".

From this you can see that timing is a very important factor in bluetooth communication. So both communication partners need a very accurate clock. No two clocks have exactly the same speed, one is always lagging the other.

It could be that one or multiple of the clocks of your HC-05's do have too much clock drift, so the connection will be lost. Maximum clock deviation allowed for a bluetooth clock is ±40 ppm (i.e. ±40 parts-per-million!) over the entire temperature range.

You could check this theory with multiple HC-05s. If individual modules lead to individual connection lengths, then this could be your problem.


Problem receiving CAN messages using arduino, MCP2515 CAN module and multiprotocol radio shield I am using an arduino UNO and a Cooking Hacks CAN BUS module through a Cooking Hacks Multiprotocol radio shield. I plan to read the CAN messages through the car's OBD-II port. I have connected the components according to the tutorial and though there is no LED to indicate that the shield and CAN bus module are ON, I verified that they are indeed ON by using a multimeter. Also, when the reset button is pressed on either the shield or the CAN module, the arduino resets so I guess they are powered up. Coming to my problem, I uploaded the code and connected the setup to the OBD-II port and turned the ignition ON. I expected to see the CAN messages on the arduino serial monitor but I didn't see anything. I also took up this issue with the cooking hacks support team who told me that the libraries were updated and that I should use the updated ones. So I downloaded the revised libraries to use with my code but I am unable to upload the code itself to the arduino because of an error during compilation.
C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\arduinoCAN.cpp:26:49: fatal error: ../arduino-api/arduinoMultiprotocol.h: No such file or directory
The major difference as far as I can tell between the old and the new libraries is the addition of two lines in the arduinocan.cpp file :
include "../arduino-api/arduinoMultiprotocol.h"
include "../arduino-api/arduinoUtils.h"
Both of these are header files in another library that was included as part of the whole library that you can download from their website.
I realise I might have confused whoever's reading but please have a look at the arduino code. Hopefully, that should clear things up. Any help would be highly appreciated. Thanks.
Code:
    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    // Create an instance of the object
    CAN myCAN = CAN();

    // Setting up our devices and I/Os
    void setup() {
    // Using the Socket 0 onto which Can bus module is plugged in
    Utils.setONSocket0();
    Utils.setMUXSocket0();
    // Initializes the UART
    Serial.begin(115200);
    delay(100);

    myCAN.begin(500); // Start talking to the BUS. Speed= 500 Kbps
    }

    void loop() {
    // 1. Receive data

    if (myCAN.messageAvailable()) {
    // Read the last message received.
    myCAN.getMessage(&myCAN.messageRx);
    // Print in the serial monitor the received message
    myCAN.printMessage(&myCAN.messageRx);
     }
    }

EDIT: PROBLEM SOLVED!
Putting the header file's full path in the sketch did not solve it. The compiler still displayed the same error. I then made a backup copy of all the files containing the #include "arduinoMultiprotocol.h" statement and edited them to contain the full path. Initially, the error didn't change and I moved onto the next suggestions, all of which did not change the error. However, I went back to the edited files and replaced the backslash() with the slash(/). This time, the compiler did not throw the same error, instead saying it cannot find arduinoUtils.h.
So I proceeded to do the same thing with arduinoUtils.h, editing all the files containing it to mention the full path. And this time it worked and the sketch works as well. Thanks for your help!

The compiler is saying it can't find the header files. The part of the path ../arduino-api/ is suspicious.

It may be because the header files are expected to be somewhere else, or their is a small error which has had a knock on effect.

1 - Find arduinoMultiprotocol.h
Put its full path into the include statement, e.g.

    #include "C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\wibble\arduinoMultiprotocol.h"

If that is still broken, but a new error is printed, copy the error. If the error doesn't change, then make a backup copy of every file you can find containing #include <arduinoMultiprotocol.h> and edit it to contain the full path. It looks like starting with arduinocan.cpp is a good place to start.

2 - If that doesn't fix the error, create an empty sketch, including all those headers, e.g.

    #include <arduinoCAN.h>
    #include <arduinoClasses.h>
    #include <arduinoMultiprotocol.h>
    #include <arduinoUART.h>
    #include <arduinoUtils.h>
    #include <Wire.h>
    #include <SPI.h>

    void setup() { }

    void loop() { }

Compile and copy the error message.
Move the #include <arduinoMultiprotocol.h> a bit later in the sequence of #includes. If the error changes copy that for later, and record which sequence changed it.

3 - Change #include <arduinoMultiprotocol.h> in that empty sketch
to the full path (as in step 1). If that doesn't fix it, copy that error message.

If you still need help, please update your question with the results of those tests.


Mac OSX Yosemite no serial ports showing for Uno R3 I have a MacBook Pro running OS X Yosemite (10.10.3). I connected my Arduino UNO R3 to my computer for the first time after the Yosemite upgrade - it worked fine before this!

When I opened the Arduino IDE I selected Tools > Board > "Arduino UNO", but when I try to choose a Serial Port the only options are:

/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

I have followed several tutorials and threads on how to 'fix' this issue, all to no avail:

I've installed the latest version of the FTDI drivers (even though, from what I recall the UNO doesn't even need them): FTDIUSBSerialDriver_v2_3.dmg

Downgraded to a prev. version of the FTDI driver hoping that would clear it up: /Volumes/FTDIUSBSerialDriver_v2_2_18

I followed a tutorial of how to remove the existing Apple drivers and removed the kext files, etc...

Tried connecting arduino to both USB ports.

Tried various cables, including the one that a I used before the Yosemite upgrade.

Tried installing updated Silabs drivers:
Arduino compatible's serial port not showing Mac OSX

Walked through the entire Arduino Mac OSX guide:
http://www.arduino.cc/en/guide/macOSX

After looking into the system info of my Macbook Pro, I can see the USB Controller is Broadcom based, in case that helps. I searched for Broadcom USB drivers but got hits for Silabs one instead.

Under my Tools > Port menu.. I can see these options:

clicking the Serial Ports option doesn't do anything.

Running ls -1 /dev/tty.* or ls -l /dev/tty.usb* from terminal gives me:

/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem

The Board does NOT show up under system networking (as it has for others), so it's not recognized as an incorrect device.

I'm at a complete loss. The board powers up... but I cannot connect to it.

SIDE NOTE: This is a legit Uno R3, not a clone.

Probably, you have Chinese Uno analog which works on CH340 USB-to-serial chip, so you need to install driver for it.

Steps to fix:

Install the CH340 driver
Run the command in Terminal: sudo nvram boot-args="kext-dev-mode=1" (disable kext signing introduced in Mac OS X 10.9 Yosemite)
Reboot

Also you're right according to Uno and FDTI:

  Differences with other boards

  The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial driver chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed as a USB-to-serial converter.


Arduino Video Feed (Building Zumo Robot) I'm building a Zumo robot with my daughter, but I have very limited experience and knowledge with programming and electronics. Pictures of the equipment I have are in this link and the last picture has all the equipment together: https://imgur.com/a/ehPpFnV. I wanted it to be a fun challenge to build, but I honestly don't know where to start. I'm looking for some advice on how to get started with the Arduino software and hardware. I need to:

Hook up the 2 screens to the power supply (from the Zumo?) or see if I need to buy a separate power supply.
Figure out how to use the SD card with the Arduino so I can pull video from the card and put it on one or the other screen.
How to learn any other programming for the Arduino that may be helpful for this project.

I know this is a lot to ask, but anything helps. Thanks so much!

As Duncan wrote in the comments, an Arduino is way not up for the task of handling video (even still images can be a problem due to memory.

So you need to go with a small single board computer, like the Raspberry Pi Zero, that can be seen on one of your images. It has a Mini HDMI output, where you can connect a display. I don't know, if there already is software on the Arduino and Pi, because I don't know this robot. You have to make sure, that this software doesn't conflict with the software, that you would write.

How to connect 2 displays is more tricky. The Zero is not capable of running 2 displays independendly. If the displays should show the same, I think there are Y-cables for HDMI. If only one display has to show something at a time, you could use a HDMI switch (and you can even hack that, to trigger it from the Zero or Arduino). If you really need both displays independently and simultaneously you need to either use a Raspberry Pi 4 (which supports 2 displays via its 2 Micro HDMI outputs) or add another Raspberry Pi Zero.

The video then is of course not read from the Adafruit SD breakout board, but from the Pi's SD card. Even if the Arduino was fast enough for video, these breakoutboards are using SPI to connect to the SD card, which is inherently slow. If used in a computer the SD card is connected via a parallel interface.

  How to learn any other programming for the Arduino

There are tons of tutorials and courses online, so you just need to google. We can only help with specific problems here. And the video part will be on the Pi, so no Arduino question. You might want to learn Python to code on the Pi.


Cannot drive DC motor with Arduino PWM I've programmed the Arduino Uno to generate PWM corresponding to the serial input values. And it works fine with an LED. I took the connection from PWM pin 3 (where I set the output) to the base of a BC548 transistor and connected the motor in series with an external motor power supply (Vcc) and the collector and the emmitter is grounded (to both Arduino's GND pin and the external supply's). The motor had a fly wheel diode, 4N4007, and a capacitor of 1 µF for protection.

But when I connect the motor and provide it with the PWM input, it works for a few seconds and then I see a few flashes in the rx and tx LEDs, and it stops working even with a serial input or reset. I need to turn it off and then on to make it work again. The same thing repeats when I connect the motor, but it works fine with an LED.

How can I fix that??

I think your Arduino resets itself because of connection or current overload. Also, please share your connection. What is the voltage of the external source? If it needs high power, try a MOSFET like this.


Can I connect to a DALI network as a master node using an Arduino? I have googled a lot, and mostly every website you can link me I have already explored, some are outdated and don't work, others aren't clear in their documentation, and use equipment too expensive to run the risk of buying it and it not working.

https://github.com/edinburghhacklab/dali

https://github.com/sde1000/python-dali

https://github.com/krzychb/DimSwitch/blob/master/extras/pictures/PHILIPS-HF-REGULATOR-TOUCH-a-DALI%2018-58w-T8-%201-a-2-LAMPS.pdf

http://microcontrollershop.com/product_info.php?products_id=5384

Moreover, like any free protocol, you have to pay to access the DALI standard.

What can I do to control a network of connected DALI dimmable ballasts?

I have made a simple DALI controller with Arduino Nano. Maybe it will be useful for you. Look here: Simple DALI Controller


Very long delay() possible? I'm trying to make an opening and closing little door that should open or close every 12 hours. I was wondering if I could just make a small looping script with a delay() for 12 hours, delay(43 200 000 000); I guess? However, I have no idea if that's possible and/or recommendable. Some feedback/alternatives(if needed) would be nice :)

The real time clock method is the most accurate way but otherwise use millis

unsigned long startMillis = millis();
while (millis() - startMillis < LONG_DELAY_MS);

This will delay up to approx. 4294967295ms (2^32-1) or 49 days, after which the timer will catch up to the value of startMillis


How can I read a piezo sensor and have it output a fixed voltage? I'm trying to creature an instrument out of a few boards I have. The plan is to have piezo sensors wait for a hit, then be read by a digital pin, then execute code based on what piezo sensor was hit.

I know how to make a note play, but I don't know how to read a signal from a piezo that's between 3V and 5V. I'm not worried about velocity measurements, I just want there to be a hit, register the hit through arduino, then relay the pin number to a track number.

I read that pin change interrupts can read a signal instantly.

Below is some example code for my audio output board that plays audio files. This specific bit of code is for "notes" on an instrument.

          wTrig.masterGain(-8);                 // Lower main volume
          wTrig.trackPlayPoly(6);               // Play first note
          delay(1000);
          wTrig.trackPlayPoly(7);               // Play second note
          delay(1000);
          wTrig.trackPlayPoly(8);               // Play third note
          delay(1000);
          wTrig.trackFade(6, -50, 5000, 1);     // Fade Track 6 to -50dB and stop
          wTrig.trackFade(7, -50, 5000, 1);     // Fade Track 7 to -50dB and stop
          wTrig.trackFade(8, -50, 5000, 1);     // Fade Track 8 to -50dB and stop

I don't have experience with code, but this is how I think activating a note would work:

wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

As far as limiting voltage, don't I just need to put some resistors in circuit with the piezo sensors?

In psuedo-code, this is what I want to make happen:

Listen for signal from any pin
Store that pin number as a variable
wTrig.trackPlayPoly(pin number)
delay(100);
wTrig.trackFade(pin number, -50, 5000, 1);

A piezo will output a decaying sinusoid when you feed it an impulse (a hit on the attached surface). Problem with a high frequency sinusoid is that one: half the time it's negative, and two: it forces a near-real-time monitoring of the analog voltage there, ie no or small delays in your code.

I've made a pattern recognition 'drum' with piezos, and the general approach was to first start with plotting the analog voltage of the piezo. This is done by putting the positive of the piezo to an analog pin and the negative to ground, and a 1M resistor between the leads (this value worked for me, play with different values to see what works best). Then do a serial plot (ctrl shift L in the IDE) and observe:

how high the peak is for different distances and strengths of 'knocks'
how many times a significant peak occurs before decaying.

Your end goal is to have the Arduino recognize a peak by seeing when the analog reading is above a threshold value , then have a dead period where it ignores subsequent peaks (so it doesn't read multiple events on a single sinusoid), and then play your note. Longer dead period means less false-positives, shorter means more responsive.

I apologize for the long-windedness of my somewhat ambiguous response, I'll try to remember to paste my code when I'm at my computer tomorrow.


What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info Can anyone tell me why 1k resistor is used on pin 13 of ATmega16U2 in arduino uno schematics. I have also seen a 100k resistor used in this position?

Link for schematics - https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

Its a pulldown resistor!

Comment there says "USB Boot Enable" so safe assumption that it's an digital pin.

They're handy because they mean if there is no input to whether that pin is headed, the voltage at the pin will be 0 instead of floating.

The value doesn't matter too much, "When in doubt 10k it out" is a pretty well known saying around electronics people, meaning just use a 10k Ohm resistor and you'll be fine.


Adafruit 128x64 OLED not turning on I ordered a 128x64 pixel OLED display from Adafruit and wired it according to their guide. (To an Arduino Uno) I'm using SPI right now and the display will not turn on or do anything. I haven't tried i2C, but I don't think that should make a difference. Maybe I will if nothing else works. I've installed the two libraries from the guide and am running the SPI 128x64 example. I've tried to find people with this same issue but I haven't found that much about it. Any help would be greatly appreciated!

Edit: Added pictures. I've used header pins in the past in case anyone is wondering if the connection using these wires isn't good, but the pins did not work either, so it's not a bad connection.

Wiring is your problem. Use soldering iron/solder and flux. Solder your wires. Intermittent connections and accidental shortages with current setup may damage your Arduino and display (and possible your PC/laptop).


Power supply for DIY Arduino CNC Router I am making a CNC router from a dremel and 3-5 NEMA 17 steppers. I am really confused on how I can power all those motors. I am using a RAMPS 1.4 with Arduino Mega. I have a 2.4A USB power supply. Is that enough? If not, what is the minimum specs I need to ensure that I don't burn, blow, or under power anything? I am trying to get my hands on a ATX power supply.

I have a 2.4A USB power supply. Is that enough?

Not by a long way, no.
NEMA 17 motors are typically 12V, not 5V, so a USB power supply is not even close.
You will need a decent 12V power supply with a lot of current.
My 3D printer has 3 NEMA 17 motors and uses a 200W 12V power supply. Most of that goes to the motors with only a comparatively small proportion to the hot end.
You need to know the current draw of the motors you are using (note: NEMA 17 defines the physical size, not the electrical characteristics).  Sum all those up for all your motors, and that's the absolute minimum you'll need from your power supply. Add some more on top for losses in the motor drivers and to power the Ardiuno.
And I'm not even considering the dremel in any of this...
So yes, an ATX power supply is probably a good choice.


Changes to array not reflected Here's a simple sketch. I have an array data and a variable idx.
I'm assigning a value to each of the array element, and then sending them to my serial monitor.

volatile uint16_t data[5];
volatile uint16_t idx = 5;

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

  while (!Serial) { }
  Serial.println("\nHello!");

  data[0] = 1010;
  data[1] = 1011;
  data[2] = 1012;
  data[3] = 1013;
  data[4] = 1014;

  for(int i = 0; i< idx; ++i)
  {
    Serial.print(data[idx]);
    Serial.write(",");
  }

  while(1){  }
}

void loop() {}

When I look into my serial monitor, I get this:

Hello!
0,0,0,0,0,

Why is this happening? Did I overlook something fundamental? I'd appreciate if you could offer your thoughts on this.

I'm testing this code on Arduino Mega2560.

You got confused here:

Serial.print(data[idx]);

You're printing array slice 5 (the sixth entry in a 5 entry array) 5 times.

You probably meant to write:

Serial.print(data[i]);

To improve clarity you may want to #define it instead:

#define DATA_SIZE 5
uint16_t data[DATA_SIZE];

...

for (int i = 0; i < DATA_SIZE; i++) {
    ....
}

Or you can do it the other way round (get the size from the array):

uint16_t data[5];
#define DATA_SIZE (sizeof(data) / sizeof(data[0]))


Solution for simple multi-Arduino communication network (or alternative?) I know similar question has already been discussed here but I could not get clear answer.
Here is the thing: I have one master device - Mega2560, and multiple (about 9 but could be expandedin future) I2C perfiferals - displays, that can have one of two possible I2C IDs - limitation by the manufacturer. As I can't connect and talk to them from a single I2C bus I chose to attach each two of them to a Mini-Pro's I2C pins and connect the 5 Mini-Pros to the master. The question is am I going to the right direction, and which connection would do the trick? I2C is obviously out of question, so the remaining are UART and SPI. UART would require some external hardware to cope with multiple outputs from the slaves, SPI would require additional pins from the master for chip select signal.
Data rates are not high - min 10-20 kbps.
I think the SPI offers better solution, but I'm no expert, what do you think?

Cheers!

Stefan

Thanks all for your answers.

I did some more research with the new info you provided and found my perfect solution: TCA9548A. That's a 1-to-8 port i2c multiplexer that will allow the master MEGA2560 to control up to 8 independent i2c buses, where I can connect my displays. The chip is dirt cheap here - 2 euro only, and it is available in the store.

Thanks again guys!


Can't use uint16_t in library I wonder why the following minimal example sketch doesn't compile (unknown type name 'uint16_t'):

sketch_does_not_compile.ino:

#include "myheader.h"

void setup() {
  char a[]="hello world";
  uint16_t l=str_len(a);
  Serial.println(l);
}

void loop() {}

myheader.c :

uint16_t str_len(char* input_string) {
  uint16_t i=0;
  while (input_string[i++]!='\0');
  return i;
}

myheader.h :

#include "myheader.h"

uint16_t str_len(char* input_string);

Compilation fails with

myheader.c: At top level:
myheader.c:3:1: error: unknown type name 'uint16_t'
 uint16_t str_len(char* input_string);
 ^
exit status 1
unknown type name 'uint16_t'

Using uint16_t in the .ino-file directly like in the sketch below compiles fine.

sketch_compiles.ino :

uint16_t str_len(char* input_string) {
  uint16_t i=0;
  while (input_string[i++]!='\0');
  return i;
}

void setup() {
  char a[]="hello world";
  uint16_t l=str_len(a);
  Serial.println(l);
}

void loop() {}

What am I missing?

Using #include <Arduino.h> in your myheader.h will also include <stdint.h> and probably solve this.

The Arduino IDE automatically includes Arduino.h in the sketch itself, but apparently not for external stuff.


How to simply close a tab? How can one close a tab in the Arduino IDE? There is a Tab button (little triangle) with the Option "Delete"(kind of misleading term). There is no "Close" option. And the "Delete" option doesnt do the job for me either, because the tabs are write-protected, and I just get a prompt.

You cannot close a tab in the Arduino IDE.  If a file exists in the sketch then it is there with a tab. Deleting a tab deletes the file.

In the Arduino IDE a tab is a file and a file is a tab. You can't remove one without removing the other.

You might like to check out my IDE, UECIDE, which deals with tabs in a more traditional manner.


Reading text line by line from SD Why does the following code return this error?  How can I make this work?

  Error: exit status 1 invalid conversion from 'const char*' to 'char'
  [-fpermissive]

#include "FS.h"
#include "SD.h"
#include "SPI.h"

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

  if (!SD.begin(33)) {
    Serial.println("Card Mount Failed");
  } else {
    Serial.println("Card Mount Succeeded");
  }

  File offline = SD.open("/offlineLog.txt", FILE_READ);

  while (offline.available()) {
    String line = offline.readStringUntil("\n");
    Serial.println(line);
  }
}

The docs say that stream.readStringUntil returns a string...

The error has nothing to do with what readStringUntil returns. It has to do with what parameters it accepts.

The function expects a single character to look for. Instead you are passing it a string (C string) containing one character.

In C you represent a string (char *) using "", and a single character (char) using ''.

Since readStringUntil expects a char, not a char *, you need to use '':

String line = offline.readStringUntil('\n');


Arduino Ultimate GPS Logger Issue I am new to electronics and learning how to play around with arduino. I recently purchased the Arduino ultimate GPS Logger, and despite also buying an external anntenae the GPS data shows that it does not fix at all. Despite leaving the unit powered for more than 5 minutes. Please advise on what could be wrong. Is it normal to take so long to get a GPS fix? This is the Arduino in question. https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/overview

This style of antenna can be very finicky.  GPS on this module may take 15 or 30 minutes to lock, not just 5.  I would suggest you take this outside away from any walls or buildings and see if it will lock then.  I also suggest that you run it off a battery.  (one of those USB battery packs for charging your phone will work great).  Once you get a lock try changing one variable at a time (power supply / location) and see if you can get it to look again.

The reason this module takes longer to lock than your cellphone is that your cellphone is cheating by doing a warmstart.  The cellphone can get a semi-accurate time/date and also your regional location.  This warm start data improves GPS lock time down to 5 seconds or less sometimes.


Arduino Uno - Building a Controller I have the Arduino Uno and I'm working on a project to build a controller with different inputs and some outputs for readouts. In classic style, I got the Arduino Uno before realising that I might not have enough I/O points to connect everything I want.

I believe there is a way to expand my Uno by using an I/O Expander? Has anyone done something similar? The controller will be for a specific game called Kerbal Space Station. There are quite a few articles helping with the build but not specific to what I am looking at.

Components I'll be using:

INPUTS:

2x 3 Axis Joysticks
11x Microswitches
6x Toggle switches
1x Analogue slider
1x 10 point rotary switch

OUTPUTS:

4x 12 pin LED Bargraphs
1x Serial LCD module display

Yes, all those things have been done before.  Here's some suggestions for components:

MCP23S17 / MCP23017 - SPI / I2C IO expander (16 IO pins, many can be connected together) (MCP23S17 library)
MCP3208 - 8 channel 12-bit SPI ADC (MCP3208 library)
TLC59116 - I2C Constant Current LED PWM driver (16 channel) (TLC59116 library)

Some other useful tutorials that may help:

Keypad - read lots of buttons / switches with not many pins
Multiplex - Control many LEDs with not many IO pins


Can't change pins in AM2320 code, types mismatch I took a simple A2320 temperature sensor and connected it not to  A4/A5, but to A1/A0 pins. SDA => A1, SCL => A0. (In C code they are number 15 and 14). But I can't call the library to take these pins.
The basic example from the library uses the default values, probably from some tutorial.
I read the .h and .cpp files and see these definitions:
Adafruit_AM2320::Adafruit_AM2320(TwoWire *theI2C, int32_t tempSensorId,
                                 int32_t humiditySensorId)
    : _temp(this, tempSensorId), _humidity(this, humiditySensorId),
      _i2c(theI2C) {}

bool Adafruit_AM2320::begin() {
  _i2caddr = 0x5C; // fixed addr
  _i2c->begin();
  return true;
}

I just tried to make types match. Not even port number.
I declared a TwoWire instance and passed it to AM2320 constructor, but without success:
#include "Wire.h"
...
TwoWire mywire();
Adafruit_AM2320 am2320 = Adafruit_AM2320(mywire, -1, -1); // as the default values

Outputs in error log:
error: no matching function for call to 'Adafruit_AM2320::Adafruit_AM2320(TwoWire (*)(), int, int)'
    Adafruit_AM2320 am2320 = Adafruit_AM2320(&mywire, -1, -1);
In file included from testproj.ino:2:0:
...Adafruit_AM2320.h:52:3: note: candidate: Adafruit_AM2320::Adafruit_AM2320(TwoWire*, int32_t, int32_t)
   Adafruit_AM2320(TwoWire *theI2C = &Wire, int32_t tempSensorId = -1,
   ^~~~~~~~~~~~~~~
...Adafruit_AM2320.h:52:3: note:   no known conversion for argument 1 from 'TwoWire (*)()' to 'TwoWire*'

What am I doing wrong?

Two problems:

When you create an object instance with no parameters you must not have parentheses. You should construct thus:

TwoWire mywire;

The constructor expects a pointer to an object, not an object. Just take the address of the object with & and pass that:

Adafruit_AM2320 am2320 = Adafruit_AM2320(&mywire, -1, -1); // as the default values

However
Most Arduino boards have the I2C pins hard-wired internal to the chip and can't be changed. You would need to use some form of software implementation that is also a polymorphic child of the TwoWire class. If such a thing exists.


Operating AD5780 EVAL Board Via MicroController OK, so thanks in advance because I am new here. I am reading the AD57XX drivers here  https://wiki.analog.com/resources/tools-software/uc-drivers/renesas/ad5780 and am struggling to understand how to get the device working and understanding it properly.

I am using code here https://github.com/maxgerhardt/arduino-ad57xx-driver/blob/master/src/main.cpp in order to test the DAC. I have several questions about the drivers and operation in general. I will itemize them if that is ok

Where in the drivers am I performing Slave Select and where am I determining Clock Speed? I have looked through the C in the drivers library, and it seems that each command, whether reading or writing selects the Slave/Master each time? I see no reference to which pins on my microcontroller it is reference though so I do not know if any of this is right.
Why do I need to be reading in the Control Register or anything from the DAC at all? Why does this matter? All I want is to output a voltage
How do I perform the right conversion to a voltage that I want? The command " AD57XX_SetDacValue() " takes a long, but I do not understand how that relates to a float value of voltage. Say I want 2.35 Volts, or a Sine Function from -2 to 2 Volts, how do I do this conversion?
I don't know how to debug the system in general. When I run the example code, which is supposed to output a triangle wave function, I get a sin function, which seems to just be noise.

Where in the drivers am I performing Slave Select and where am I determining Clock Speed? I have looked through the C in the drivers library, and it seems that each command, whether reading or writing selects the Slave/Master each time? I see no reference to which pins on my microcontroller it is reference though so I do not know if any of this is right.

The slave select is controlled within the SPI_Write() function.  It uses the PinMgt_PinWrite() function to do the slave select control, which in turn selects a pin from the pinMapping[] lookup table.

The clock speed is set in AD5780_Init().

  Why do I need to be reading in the Control Register or anything from the DAC at all? Why does this matter? All I want is to output a voltage

You don't. The code is just for demonstration purposes. It shows you how you could query those registers. If you don't need to, then don't.

  How do I perform the right conversion to a voltage that I want? The command " AD57XX_SetDacValue() " takes a long, but I do not understand how that relates to a float value of voltage. Say I want 2.35 Volts, or a Sine Function from -2 to 2 Volts, how do I do this conversion?

That value is the raw value to set the DAC to. You refer to the DAC datasheet to know what that value equates to.  In this case the range is from \$V_{REFN}\$ to \$V_{REFP}\$.  Divide that range by 218 and you have the voltage per bit.

  I don't know how to debug the system in general. When I run the example code, which is supposed to output a triangle wave function, I get a sin function, which seems to just be noise.

You need some debugging tools. Things like a logic analyser to be able to acually see what the IO pins of your MCU are doing.  An oscilloscope can be used to see if a signal is present, but to see all the SPI signals together you really want a logic analyser.


Update custom library I've recently made a custom library. Then, I've imported the library into the IDE via the add .zip library. Once I tried to compile the code, I've realised that I made a small typo. Once I changed the error and then retried to compile the code, the error still appeirs and I'm quite sure that I've changed it.

So my guess is that the library is not updating. I've tried to go to manage library and then seeing if there is an other version of the library. There wasn't any.

So is there an easy fix to this solution that doesn't involve updating or downgrading the IDE?

Text from here says this:

  In Arduino v16 and earlier, libraries were stored in the
  ArduinoInstallDirectory/hardware/libraries folder, which also
  contained all the built-in libraries (like Wire and Serial).

  In v17 and up, the user libraries are now stored in the
  ArduinoSketchDirectory/libraries folder.

Check your version of the Arduino SDK and then look in the appropriate directory for your library source code.  Then change it there.

The Arduino SDK is fairly simple and often compiles everything to avoid problems like this.  The installing from a zip file feature (unless it has changed) is more for convenience when downloading a single zip file.  I have often developed & edited custom library source code where the SDK expects to find it.


What's wrong with my ESP8266? After trying to upgrade firmware of ESP8266, it failed. I am not finding any response from it. It's just blinking a red LED.

What will I do now?

I had tried to upgrade the firmwire in different ways...but couldn't.The result is that i am not finding any wifi signal response in the network connection ...What's now?

The upgrade firmware on the ESP8266 is hardcoded. Attempting to reflash it with known good firmware should restore functionality.


Why does enabling TIMSK1 mess up serial? I am intending to write a code where a user will send lines through serial to affect timer interrupts. I am noticing a problem with serial where as soon as I enable the timer interrupts, the serial communication becomes garbled. More specifically, as soon as I enable the timer interrupts and I open the serial monitor, the monitor gets flooded with garbage. I haven't written too much code and this is already happening. Am I making a silly mistake? I am using an Arduino Mega 2560. My code is below:

void setup() {
  Serial.begin(9600);
  Serial.println("Hello World!");
  timer_setup();
}

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

void timer_setup() {
  // waveform generation = 0100 = CTC
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |=  (1 << WGM12);
  TCCR1A &= ~(1 << WGM11);
  TCCR1A &= ~(1 << WGM10);
  // output mode = 00 (disconnected)
  TCCR1A &= ~(3 << COM1A0);
  TCCR1A &= ~(3 << COM1B0);
  // Set the timer pre-scaler
  TCCR1B = (TCCR1B & ~(0x07 << CS10)) | (2 << CS10);
  OCR1A = 0x4000;
  TCNT1 = 0;
  // Enable timer interrupt mask 1
  TIMSK1 |= (1<<OCIE1A);
}

If I comment out the TIMSK1 |= (1<<OCIE1A) line, serial doesn't mess up.

You've enabled interrupts for Timer 1 Compare A interrupt. Where is the interrupt handler?

For example:

ISR(TIMER1_COMPA_vect)
{
  // whatever
}  // end of TIMER1_COMPA_vect

Without that, the processor is just restarting. No wonder serial output is messed up.


Arduino sketch- How to add Time Stamp for outgoing MQTT I'm writing a sketch in order to upload to a Sonoff device ( Remote relay, based ESP8266 ).

All is working great, but I wish my MQTT pubs to contain following format:

[ DATE & TIME ] msg

ESP8266 is connected to the internet.
I;m looking for a way doing it (including periodic time updates ) without running all 1MB memory, meaning: a code that
1) get time from external source (LAN or WAN )
2) update it every 24h
3) Lite code ?

Thanks

Start with the ESP8266WiFi "NTPClient" example.  That will teach you how you can get the "Unix Epoch" time from the internet.

That value can be fed directly into TimeLib to keep track of the time for you (indeed, TimeLib includes an NTP example for Arduino Ethernet that should help you get started).  Do that periodically (daily, hourly, whatever), and you have your time.  TimeLib can then give you the date and time as individual components (hours, minutes, etc), which you can then construct together (I'd use snprintf) to include in your MQTT message:

int len = strlen(message) + 25;
char mqttMessage[len];
snprintf(mqttMessage, len, "[%04d/%02d/%02d %02d:%02d:%02d] %s",
    year(), month(), day(), hour(), minute(), second(), message);

mqttMessage => "[2018/08/11 20:36:24] foo"


Change from using the external crystal to the internal oscillator BACKGROUND

I have made my own Arduino PCB based on the circuit of the Arduino Pro Mini (below) (including the external oscillator).

I have already written the firmware and the code is stable. The code uses the millis() function which uses Timer 0. I also have changed the frequency of the PWM output on pins 3, 9, 10, 11, using the clock select bits (bits 2:0 in TCCR1B & TCCR2B). See http://playground.arduino.cc/Main/TimerPWMCheatsheet

I have an ISP 6-pin programming port on the board and this is my only method of uploading code.

I want minimize on components (and avoid EMC issues), so I have been considering removing the external 16MHz crystal and instead using the internal 8MHz oscillator.

QUESTIONS

What do I need to change to use the internal oscillator?

I suspect that I need to change the board.txt file, the clock select bits and the fuses to accommodate for the new frequency.

Can I leave the external crystal in place or do I have to remove it?
If I do leave the external crystal in place and set the fuses to use the internal oscillator, will the crystal continue to resonate or does it get powered down somehow?
(I wish to know this for EMC reasons)

What do I need to change to use the internal oscillator?

You'll need to change the fuses on the chip, and you probably want a new 8MHz entry in boards.txt so that timing functions still work as expected.

  Can I leave the external [resonator] in place or do I have to remove it?
  If I do leave the external [resonator] in place and set the fuses to use the internal oscillator, will the [resonator] continue to resonate or does it get powered down somehow?
  (I wish to know this for EMC reasons)

From the datasheet:

  If the Internal Calibrated RC Oscillator is used as chip clock source, PB7...6 is used as TOSC2...1 input for the Asynchronous Timer/Counter2 if the AS2 bit in ASSR is set.

Also:

  When AS2 is set, pins TOSC1 and TOSC2 are disconnected from Port B. A crystal can then be connected between the TOSC1 and TOSC2 pins to serve as an
  independent clock source for Timer/Counter2. The Oscillator is optimized for use with a 32.768kHz crystal.

Therefore if AS2 is not set, the two pins act as normal GPIOs and the resonator is disabled.


Can I Interrupt on any keypress on this keypad? I'm learning how to write code interrupt code. I just experimented with my first toy example that I got from here:

const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

Now I'm trying to incorporate interrupts into my own project. I have a circuit that looks like this using an Arduino Uno Wifi Rev2, Membrane 3x4 Matrix Keypad, a buzzer, some resistors and an RGB LED:

Can I write code such that it interrupts any time any of the keys is pressed (and I can still tell which key is pressed)? How would I do that?

No, you can't. Owing to the fact that you have to manually cycle through each row (or column, depending on which way you are holding your head at the time) in order to read which keys are pressed there is no way to relate a button to an interrupt.

The only possible way would be to use an external keypad interface chip (you could roll your own with another Arduino) which has an interrupt signalling facility in it.


MIFARE RC522 I2C Library I was looking at this link on RFID I2C interface. I added the library to arduino, but in main.cpp, I see an error:

In function 'void setup()':
sketch_mar27a:16: error: no matching function for call to 'TwoWire::begin(int, int)'
Wire.begin(SDA_PIN, SCL_PIN); // Initialize I2C

I looked at Wire.cpp file and found that there is no such member function overloaded with two parameters.
How should I fix the problem? Even if I fix this one problem, I am not sure if this code is working code.
Where can I find working code with I2C interface? I have resource problem and SPI PORT cannot be used.
The code:
#include <Wire.h>

#include "MFRC522_I2C.h"

#define SDA_PIN 5
#define SCL_PIN 6
#define RST_PIN 3

MFRC522 mfrc522(0x28, RST_PIN);  // Create MFRC522 instance.

void ShowReaderDetails();

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  Wire.begin(SDA_PIN, SCL_PIN); // Initialize I2C
  mfrc522.PCD_Init();   // Init MFRC522
  ShowReaderDetails();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}

void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

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

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

void ShowReaderDetails() {
  // Get the MFRC522 software version
  byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
  Serial.print(F("MFRC522 Software Version: 0x"));
  Serial.print(v, HEX);
  if (v == 0x91)
    Serial.print(F(" = v1.0"));
  else if (v == 0x92)
    Serial.print(F(" = v2.0"));
  else
    Serial.print(F(" (unknown)"));
  Serial.println("");
  // When 0x00 or 0xFF is returned, communication probably failed
  if ((v == 0x00) || (v == 0xFF)) {
    Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
  }
}

SPI is a multi-slave bus. Unless you've run out of free pins to use for CS, or you have slaves that don't play nice, you can connect your RFID module to the SPI bus as well. Also your sketch will most likely compile if you only correct the offending line to simply Wire.begin(). Your library uses the standard Wire library but assumes the target is an ESP8266, whose version of Wire has an extended begin() method.

But this may all be no use since the MFRC522 you have (assuming it's the cheap blue module) is hardwired to use only the SPI interface. Unless you're ready to modify the PCB (cut traces, etc) as others have done.


int array passed through function has wrong values only after multiple passes I have this code:
for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
}

which calls the function "multiLamp" and passes 3 int arrays with 2 values each. Here is the function:
void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],2);
    }
  }
}

This function is supposed to call some function "lamp" with a few integers from the arrays. In the beginning this works fine but after more than 50 calls of the "multiLamp" function the values in the arrays become {0,128,128} and {3,3,3} or something similar even though the values passed into it from my main code are equally valid as before (they are somehow changed after being passed to the "multiLamp" function).
I can't seem to find the issue here. Any help is appreciated!
UPDATE:
Here is the full code, although I don't know if it will be of any use because I wrote it to control some LEDs and if you don't have the setup it's difficult to see if the code is working or not.
int e[] = {12,13,11,10};
int xy[] = {2,3,4,9,6,7,8,5,1,A0,A1,0,A3,A4,A5,A2};

void setup() {
  for(int a=0;a < 4;a++){
         pinMode(e[a], OUTPUT);
         digitalWrite(e[a], LOW);
  }
  for(int b=0;b < 16;b++){
         pinMode(xy[b], OUTPUT);
         digitalWrite(xy[b], HIGH);
  }
}

void loop() {
  bigCubes(100);
  rain(20, 30);
  miniCubes(15);
  every(80);
}

void lamp(int epos, int xpos, int ypos, int del) {
  int xypos = 4*xpos+ypos;
  digitalWrite(e[epos], HIGH);
  digitalWrite(xy[xypos], LOW);
  delay(del);
  digitalWrite(e[epos], LOW);
  digitalWrite(xy[xypos], HIGH);
}

void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],1);
    }
  }
}

void every(int wait) {
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      for(int k = 0; k < 4; k++) {
        lamp(i,j,k,wait);
      }
    }
  }
}

void miniCubes(int wait) {
  int cube[8][3] = {{0,0,0},{0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,1,1},{1,0,1},{1,0,0}};
  for(int c = 0; c < 8; c++) {
    for(int it = 0; it < wait; it++) {
      for(int i = 0; i < 8; i++) {
        lamp(cube[i][0]+2*cube[c][0],cube[i][1]+2*cube[c][1],cube[i][2]+2*cube[c][2],2);
      }
    }
  }
}

void bigCubes(int wait) {
  multiLamp(new int[32] {0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3}, new int[32] {0,0,0,0,1,1,2,2,3,3,3,3,0,0,3,3,0,0,3,3,0,0,0,0,1,1,2,2,3,3,3,3}, new int[32] {0,1,2,3,0,3,0,3,0,1,2,3,0,3,0,3,0,3,0,3,0,1,2,3,0,3,0,3,0,1,2,3}, wait, 32);
}

void rain(int its, int wait) {
  int x2 = random(0,4);
  int y2 = random(0,4);
  int x1;
  int y1;
  for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
  }
}

You are wrongly using the new operator for your arrays. That will dynamically allocate these arrays. They are put on the heap (not the stack like local variables) and thus don't get freed automatically, when the function exits. That has to be done by your code with the delete keyword. Your code just eats up all the available memory. Thats called a memory leak.
That you need to free your dynamically created variables is not an Arduino thing; this is correct for all C/C++ code. But the limited memory on AVR based Arduinos like the Uno makes it worse.
If you do the math, one iteration of void loop() will block 432 bytes of memory (216 array elements, each of type int thus 2 byte). The 2KB of memory (which is also needed for local and global variables) is eaten up rather fast.
I don't see, why you even would use dynamically created arrays. Why not just using locally defined arrays, like in the miniCubes() function?

That said, it is also a generally bad idea to use dynamic memory allocation microcontrollers, especially those with small memory. When creating and deleting objects of different sizes (which is the main advantage of dynamic allocation), you will leave small holes in your RAM, which are too small for one of your objects to fit. At some point your RAM is completely filled with these holes, so that no more memory can be allocated for your objects to save. Thats called memory fragmentation.
On your PC that isn't a problem because of 2 reasons:

The PC has loads of RAM available, and
the OS manages the RAM, defragmenting it, if necessary.

Since microcontrollers don't have an OS managing the RAM and often very limited RAM, you need to make sure, that your RAM doesn't get fragmented too much in the runtime of your code.


How can a USB keyboard emulator (TrinketKeyboard) type Unicode characters? I've got an Adafruit Trinket microcontroller set up using this USB keyboard tutorial, and it works great.

I'd like to set up my project to type a shruggie ( ¯\_(ツ)_/¯ ) when I press a hardware button.

My naive solution was:

TrinketKeyboard.print("¯\_(ツ)_/¯");

But that only printed the underscores, parentheses and slashes, not the "hands" or the "face."

Is there a standard keyboard input method I could use so this device, when plugged into any Mac, will type out a string that includes Unicode (specifically Katakana) characters?

An ideal solution does not require configuring the machine before plugging this widget in, and doesn't require changing state on the machine -- although I'll take what I can get! :) (e.g., configuring Japanese keyboard support and toggling input source -- all of which is done blind since the computer can't give feedback to a lowly keyboard -- is un-ideal.)

You could hack it.

Make it press CMD+SPACE
type terminal.app
press ENTER
type  echo -e
"\xC2\xAF\\_(\xE3\x83\x84)_/\xC2\xAF" | pbcopy
press ENTER
press CMD+Q
press CMD+V

though the user would see a terminal window for a second.


Need help with nRF24L01 and Arduino decoding and receiving A month ago I bought a Chinese drone, remotely controlled by: SM-217-BKT v5 controller, which uses 2.4GCOB-1A transmitter. My idea was to drive a drone with its "memory", I mean:

Start the drone and its controller.
Drive it and set it back to exactly the same position as on start.

Then to read/decode commands and after that execute/transmit them back to the drone without my help.

For the moment I know how to transmit the commands. I need to know the pipe to pair nRF24 with the receiver of the drone, to know the commands, again to know the pipe of the controlling transmitter.

I've got plan B.
To connect Arduino analog pins with the controller's joysticks, to analogRead them and than analogWrite them, but maybe this plan is not going ok.

Thanks for your time :)
1.EDIT
Under word "pipe" i mean variable which holds receiver's unique pattern of filtrating its controller's commands from other 2.4Ghz waves
2.EDIT or maybe there is a plan C, to remove the board from my drone and to use motors and frame, and than control it with another nrf24

On the nRF24L01 the communication is performed through "pipes", each with an address. That is unique to those chips and you cannot assume that some other random chip will do the same thing. As a general rule the nRF24L01 chips will only communicate with other nRF24L01 chips. You will need a SDR and an in-depth understanding of the workings of your current transmitter and it's communication scheme to even begin to think about doing what you want.

So... Go plan B.


My RTC DS1307 isn't returning any information. It seems to be stuck in the isrunning() function. Does anyone have debugging tips? I'm using an RTC DS1307 to keep track of time for long periods. It seems to be stuck in a function. I'm using the RTClib suggested by adafruit.

How can I get it unstuck and get values returned? Are there any debugging or troubleshooting tips that would be helpful?

Referencing this excerpt for the code I'm running.

void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

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

  if (! rtc.isrunning()) { //// **Where I think my code errors.**
    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));
  }
}

This is the example code modified slightly to increase logging, included with RTClib. It's for the DS1307.

Currently the output from the serial port is as follows:

  RTC is found.

I changed the code to the below:

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

    RTC_DS1307 rtc;

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

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

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

      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));
      } else {
        Serial.println("RTC is RUNNING.");
      }
    }

    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);
    }

First thing I see is the Serial setup seems a bit backward:

  while (!Serial); // for Leonardo/Micro/Zero
  Serial.begin(57600);

First, begin Serial; then wait for it to become ready:

  Serial.begin(57600);
  while (!Serial); // for Leonardo/Micro/Zero

Next, is this while(1); inside the if statement:

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

Which says "if !rtc.begin(), then println and go into an infinite loop that does nothing".

Try:

while (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    //delay(500);  // depending on how fast you want this thing to retry/print
}

the final thing I see, is the next section of code appears like it might be "work code" but is in the setup() function and is missing any kind of a loop.  So it's going to run the if statement once, then setup() exits (and loop() starts getting called).

Either replace the "if" with a "while" and wait for "rtc.running()"

while (!rtc.running()); // Waiting for RTC to be running
// Set the clock time

or move it out of setup() and put it inside loop()

void loop() {
  if (! rtc.isrunning()) { //// **Where I think my code errors.**
    Serial.println("RTC is NOT running!");
    // Perhaps try and fix it?
  } else {
    // If the time hasn't been set; set it; then move on
  }
}


Alternative of relay I am carrying out a physics experiment using an Arduino. This experiment requires accurate time measurements of upto a millisecond. However I am using a relay to turn on/off an electromagnet and there is a maximum lag of 10ms due to the relay. I am a complete beginner. Please suggest alternative mechanisms to switch the electromagnet and save those precious milliseconds.
P.S. - the magnet is driven by 12V 2.5A DC.

A relay is just an electromagnet, and the same circuit that can drive a relay can drive an electromagnet. You just need to make sure it can handle the power.

The simplest circuit is to use an N-channel MOSFET:

simulate this circuit – Schematic created using CircuitLab

Just make sure that the MOSFET can handle the required power dissipation and switches on fully at below 5V on the gate (a gate threshold voltage of less than 3V is ideal).


Using the ATMega328, from an Arduino UNO in a Standalone configuration, and bootloader - I am really lost I am really despaired. I have spent a full day to understand this, and it seems that I still don't.

I have an Arduino UNO, with an ATMega328, for which I wrote a great piece of code.

Later, I have built a circuit on a bread board, where I want to use that same ATMega328, in a 3.3V configuration, and hence 8MHz oscillator .

So, I understood that I have to write a new boot loader to it (is that correct?)

So I follow many guides available, including the Arduino Standalone, and then I understood that I don't have another chip (ATMega328), in order to use the UNO as a boot loader.

So, I was trying to connect the ATMega328 directly from the bread board to the UNO's serial data, change the boards.txt file to add "ATMega on bread board 8MHz", and tried to boot-loading it, without success. I get the error that it can't connect with the board.

Now I have been told that I can't connect the ATMega328 directly to the UNO serial to boot load it, so my questions are:

Do I really need to go over this hell in order to work with the same
chip that worked with 16MHz, but now on 8MHz at 3.3V? (why
in microchip I could just switch xtal? )
If I do have to boot loading it, and I have one chip, and
an UNO, how can I do that?
How you do that in mass production?

So do I understand you correctly that you want to lift the ATmega328 IC from the Uno board and use it on a breadboard? That strikes me as an unnecessarily risky proposition just to save a dollar or two for a separate ATmega328p.

Second, you technically might not have to write a new boot loader to the chip, if you don’t intend to reprogram it while it’s on the breadboard, but you definitely need different fuse settings, and the two changes are closely related in the Arduino IDE.

Third, bootloaders on ATmega are incapable of modifying themselves, so if you want to write a new bootloader, you always need a programmer (which can e.g. be your Arduino UNO running the ArduinoISP sketch or ScratchMonkey); I don’t think your single-microcontroller idea would work.

For mass production, you’d just use a programmer. Bootloaders tend not to be used for this, which can lead to situations like this year’s mishap at SparkFun


CAN communication with Arduino I'm a member of a Formula SAE team and we use the Performance Electronics ECU which uses the CAN protocol with a speed of 250 kbit/s and works fine with our 2D Recording Systems Data logger, but we're trying to build a telemetry system which gathers the same data from the CAN bus using an Arduino Uno and CAN shield provided by SparkFun Electronics.

However the CAN shield we're trying to use has failed to initialise the communication with the bus. Kindly help me out on what can be done or are there any alternatives of communicating using CAN with Arduino?

P.S. The link for the CAN shield: CAN-Bus Shield Hookup Guide

Beware, the industry standard pinout for CAN on DB9 connectors is different to what Sparkfun use on their shield:

pin 3/5 CAN bus shield schematic
pin 2/7 (Vector tools for example).

Which software have you been using on the Arduino? Any additional info on the ECU you're using, and the wiring in your system?


Modbus RTU slave library I want to use an Arduino Genuino Zero as a Modbus slave. I tried to search on google, and found a library. When I try using the library, I get a timeout error.

Can anyone tell me how to solve that error? Did anyone manage to get the Arduino Modbus RTU slave library working?

so i edited code your as below
    #define mySerial Serial1

byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

int data_count = 5;

void setup() {

mySerial.begin(9600);
Serial.begin(9600);
delay(1000);

}
int count = 0;
void loop() {

  if(count%10 == 0) {
    Serial.println();
    send_data();
  }

  count++;

  while(mySerial.available()>0)
  {
    byte b=mySerial.read();
    delay(1);
    Serial.print(b,HEX);
    Serial.print(" ");
  }
  //Serial.println(count);
  while(Serial.available())
  {

    byte a=Serial.read();
    delay(1);
    mySerial.print(a);

  }

  delay(1000);

}

void send_data() {
  Serial.println("send data");

  delay(1);
  for(char i=0;i<8;i++){
    mySerial.write(test_data[i]);
    delay(1);
    Serial.print(test_data[i],HEX);
    Serial.print(" ");
  }

  Serial.println();

  delay(1);


3x3 LED Matrix with less pins I'm building an audio cable tester/soldering station.  XLR cables have 3 pins and they can be wired in a few ways depending on what you want to do.  The basic cable is connected 1 for 1 and I want to make a system to verify if each pin is connected to the good ones on the other connector.

Picture the male and female connectors side by side.  The 3 pins on the male connectors will be connected to 3 digital outputs and the 3 pins on the female connector will be connected to 3 digital inputs.  That way, I can turn one of the outputs High and check my 3 inputs to see where that pin on the male connector is wired on the female connector.  Then I can walk the remaining outputs and find out how the rest of the cable is wired.

That part is all good, I can output the wiring via the Serial.print() command and the result is good.  The thing is that I would like to show the result with LEDs.  It brings me up to 9 LEDs in a 3x3 matrix.  I can use 9 outputs to show the result, but it seem like there could be a much better way.

The two solutions I see are the following:

Buying addressable LEDs and interface them with my Uno
Use 6 outputs, one for each row and one for each column.  Each row represents one pin on the male connector, each row represents one pin on the female connector.  So while I walk my 3 pins I can turn on the corresponding row and columns, then turn off that row and go to the next one, turn on the corresponding columns, etc.  I feel like this would work, but I'm wondering if the LEDs will flicker or if the refresh will be fast enough not to be noticeable.

What would you suggest?  Am I on the wrong track with solution #2?  Is there another way that does not require that many outputs?  I'm already up to 12 IO pins taken with #2 and 15 with #1.  It seem like a lot for such a simple build...

Option #2 can definitely work, it is based on a widely adopted side effect of human vision called Persistence Of Vision, abbreviated with POV, which is used in Television, LED cubes and many other display devices.

You SHOULD notice no flickering if you manage to keep a refresh rate above 24 FPS (Frames Per Seconds or full refreshes), but not all human being are the same, that's why we tend to aim at 60 or 100 FPS to ensure flickering is not perceivable by anybody.

What you WILL notice though is a reduced brightness as each LED will be turned on only for a fraction of time.

So, naming your pins as COL1 to COL3 and ROW1 to ROW3, you can refer to the following schematic:

simulate this circuit – Schematic created using CircuitLab

You can further extend your option #2 by using an external IC, commonly referred as LED drivers: not something you need unless you get short of outputs.


ATtiny85: Power consumption vs clock speed Short and simple: What is the power consumption for an ATtiny85 running at 1 MHz and 8 MHz using the internal clock? Not using any sleep modes.

I have googled a lot and can't find any info on this. I ask because I want to know if it is worth using 1 MHz to increase battery life.

The datasheet shows that current decreases at lower frequencies. Around 1 mA at 1 MHz running at 5 V. More like 5 mA at 8 MHz running at 5 V.

You can save quite a bit by using lower voltages as well, as you can see. For really big savings use a sleep mode. Read about Power saving techniques for microprocessors.

(Edited to add)

To amplify on my remarks, you should be able to get 200 nA consumption at 3.5 V in sleep mode with no watchdog timer. That will still respond to interrupts, such as closing a switch.

If you need to do things periodically you can enable the watchdog, and then get around 5 µA consumption at 3.5 V.

This is so much less current than the 1 mA mentioned above, that it is well worth exploring running in power-down mode, where possible.


Powering 30+ LEDs and flickering one at random I'd like to power 30+ LEDs, while having a single LED (at random) flicker every 10-15 seconds.

Is this possible to do using an Arduino? I totally new to this so please bear with me.

This is the type of flicker effect I'm hoping to achieve: https://www.youtube.com/watch?v=753-lkao8l0

Many thanks

Yes, it is possible, but it's harder than making one LED light up, and then doing the other 29 the same.

An LED typically draws 20mA, which is within the limit for an Arduino pin (40mA); however, there is also a 200mA limit for all pins together, so you cannot power more than 10 LEDs off the same arduino. Also, the Arduino only has 13 digital pins, and 5 analog pins, a total of 18 pins. This includes 2 pins used for programming your Arduino.

If you want to run lots of LEDs, the easiest way is running it through an external chip. You can buy a pre-made board e.g. https://www.adafruit.com/products/1429 (24 channel, these can be daisy-chained together for more than 24 LEDs).

Alternatively, you can save yourself some money if you can just buy the chip - a DIP chip, or through-hole, will slot directly into a solderless breadboard, and can be soldered onto veroboard later to make your project more permanent.

There are a number of chips that will do the job, you want an "LED PWM driver" chip - for example, the TLC5940. There is a tutorial for this at http://tronixstuff.com/2013/10/21/tutorial-arduino-tlc5940-led-driver-ic/ - PWM just means you can control the brightness of each LED (individually).

If you want to make your project more permanent, you can solder a board of your own - find someone who can solder (your local makerspace/hackspace will be glad to help, I'm sure!) to teach you the basics, don't burn yourself. The easiest way is to use stripboard (aka Veroboard), this also means you can solder the resistors on to the same board (the LEDs too, if you like!). It sounds very intimidating, but it's not hard to learn. You can then buy PWM chips (make sure you get through-hole, aka "DIP" chips - https://en.wikipedia.org/wiki/Dual_in-line_package ) rather than "surface mount" chips. The chips are sensitive to heat, so to start you might want to solder on sockets (see same wiki page), then you can slot the chips in later.

You should consider very carefully your power supply - find out how many milliamps (or amps) it can provide - every (lit) LED will draw 20 milliAmps, and the Arduino is rated for 200mA, so if you want more than 9 LEDs, you will want an external power source, with an appropriate rating - 500mA = 0.5 amp will drive 24 LEDs. In this case, do NOT use the 2.1mm jack on the Arduino to power it; the transformer will overheat.

P.S. - you will be able to control the exact brightness of each LED independently. Also, if you use RGB leds, and use 3 pins on the IC to drive each LED, then you will be able to control the exact colour of each LED too!

Good luck!


Arduino communicate with PC? I'm pretty sure that this is the right forum to ask this question, but if it's not just lmk.

I am trying to create an auto clicker that is as hidden as possible for a computer engineering HID unit project.

What I have created so far (it works) is an Arduino being sent serial data via a C++ application that when receives a  '@' character triggers the auto clicker code and a '#' to stop the clicking. I showed my teacher and he said this is too basic as it's just simply a serial data sending application, but he likes the autoclicking idea.

I had a few ideas but I don't know how I would make them work. All I am trying to do is while a keyboard or mouse button the arduino sends mouse clicks.

TLDR; Is there a way that I can communicate keyboard or mouse events from the mouse/keyboard directly to the Arduino whilst still working normally on the computer itself, or maybe even something less discrete like making a device driver?

I suck at coding btw so I will most likely need someone I know to help me code it.

I think want you to look at this function SetWindowsHookEx on Windows.  It lets you grab any mouse of keyboard input and don something,  The input still follows the normal route, you just get notified about it.

I used this function to hook the 4th and 5th buttons on my mouse to start and stop media player, so when people pestered me at work I could pause my tunes.

MSDN - SetWindowsHookEx function

StackOverflow - Example that might work


Arduino Timer Button I am wandering how I would make it so the arduino uno will start a timer when button a is pressed and send "Start" or "Begin" or something like that to the console window. after the timer has started when button b is pressed it will mark the time from start of the timer and put it in the console window. After the timer has started when button c is pressed it will mark the time from start of the timer and put it in the console window. So on and so forth until button e, when button e is pressed i need the time to get logged in the console and they say "End" or "Stop" or something and then pause the sequence until I restart the board. This is for a school project and my only issue really is how to log the times On a timer loop persay.

Ordinarily, posters are expected to say what they've tried so far, and to show the code they've written.  However, with a problem as difficult as this one, it seems reasonable to illustrate a complete program.

Note, this program assumes that one side of each button goes to Ground and the other side goes to a digital pin with its input pullup turned on.  (If you connect one side to +5V instead of to ground, you will need additional circuitry to sense button presses.)  The digital pins that are used are selected by changing the values swA, swB, and so forth, in the third line of the program.

//  jw - 8 Mar 2016 - Program for buttons demo
// Ref: http://arduino.stackexchange.com/questions/21590/arduino-timer-button
enum { swA=8, swB=9, swC=10, swD=11, swE=12}; // Switchbutton lines
enum { nSwitches=5 };
byte buttonPins[nSwitches]={swA, swB, swC, swD, swE};
byte buttonBusy[nSwitches]={  0,   0,   0,   0,   0};
unsigned long startTime;
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
  // Note, this code assumes one side of button goes to Ground
  // and other side to a digital pin with its input pullup turned on
    pinMode(buttonPins[i], INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Program begins");
}
//--------------------------------------------------------
void doButton(byte b) {
  char *blabels[] = {"A, Start", "B", "C", "D", "E, End"};
  if (digitalRead(buttonPins[b]) && !buttonBusy[b]) {
    // The b'th button has freshly turned on.
    unsigned long now = millis();
    if (b>0 && !buttonBusy[0]) // To ignore B-E if A isn't on
      return;
    buttonBusy[b] = 1;
    if (b==0) startTime = now;  // Button A resets timer
    Serial.print("Button ");
    Serial.print(blabels[b]);
    Serial.print(" at time ");
    Serial.println(now-startTime);
    if (b==nSwitches-1) {   // Last Button ends timing, restarts cycle
      for (byte k=0; k<nSwitches; ++k)
        buttonBusy[b] = 0;  // Clear all the busy-flags
    }
  }
}
//--------------------------------------------------------
void loop() {
  for (int b=0; b<nSwitches; ++b)
    doButton(b);
}

Edit: Note that triggering messages on button-release instead of button-press would be relatively easy if buttons didn't bounce.

Before explaining that, let's look at why the above code should work.  Assume the cycle (buttons A and later E getting pressed, and possibly some of B, C, D too) lasts at least a couple of seconds.  Assume we have ordinary button hardware, and that contacts can bounce for several milliseconds at each make or break.  When you press a button the Arduino sees a lot of pin-turning-on events, eventually settling at pin-is-on.  When you release a button the Arduino sees a lot of pin-turning-off events, eventually settling at pin-is-off.  And finally, assume each button press is long enough that at least one digitalRead() happens while contacts are closed.

Under those assumptions, the very first time in each cycle that we see a given button closed, we know that button has just been pressed.  Also, we can plausibly expect closure of button A to register before closures of other buttons, and can expect the closure of E to register after that of other buttons.  So we can ignore bounce.

On the other hand, with on-release triggering we need to distinguish whether a pin-turning-off event is due to contact bounce of a button just pressed, or is actually part of a button-release bounce sequence.

Here's a method worth considering if you want to implement trigger-on-release:
 • First, add a delay(1) call, in loop().  This will make the code timing less processor-dependent, so it can run on a 48- or 72-MHz system as well as on 16-MHz Unos.
• Each time you detect that button b is on, execute buttonBusy[b] = 40 to start (or restart) a 40-ms timeout.  That is, while a button is held down, we keep setting its timeout to 40.  (40 ms may be overly conservative.  20 ms should work ok with most switches, and 10 is ok with a lot of them.)
• When you detect that button b is off,
 • if buttonBusy[b] is zero, do nothing.
 • if buttonBusy[b] > 0, then decrement buttonBusy[b] and test if it now is equal to 1.  When it's equal to 1, regard b as released, so do its action.


How to get a list of IPs in a LAN using NodeMcu? I'm going to create an IoT system. I use a Raspberry Pi as a MQTT broker and as a webserver. Every day, the Pi gets a new IP address, so I need to find its new IP address via ESP8266 to use this information in my code. I know that I can use a fixed IP, but I don't want to, so it is better if I can find a solution.

You should use mDNS.  Install (if it isn't already) avahi-daemon on your Raspberry.

Then check out the ESP8266mDNS library and the examples it has. Especially the mDNS-SD_Extended example, which performs a query for a service on the network.


Can I measure multiple photoresistors from one pin? I would like to make a laser sensor to detect light coming from a 650nm diode. My current idea would be to use CdS photoresistors/LDRs. I want to measure a few (4-8?) at once, where light falling onto any one of them generates a signal - I don't care from which sensor it actually came. However, I would like to put as many sensors on as few pins as possible.

I've already somewhat figured out that putting LDRs in parallel isn't ideal, because any changes in voltage will become smaller the more I use. Instead, it would seem like a better idea to build some kind of 'switch' by putting each LDR together with a fixed resistor and a transistor. How exactly would a circuit for this look like, or are there better ways to do it?

If response time is critical (on the order of about a quarter of a second) consider using photo diodes instead of Cadmium sulfide cells.

Also, consider using an Arduino with more ADC ports.  The number of ADC ports is usually a constraint of the processor used.  Different Arduinos use different processors.  Some may have more ADC ports.

Finally, to utilize a single ADC port for multiple unknown resistances, consider using a resistor network where all the unknown resistances and a known pull down resistance are connected to the ADC port. Then, in turn, using as many Arduino digital pins as there are unknown resistance, apply a digital high to only 1 unknown resistance. Keeping the digital pins to all the other unknown resistance in a high impedance state. That is, change them from OUTPUT to INPUT digital ports. Then take an ADC sample. Apply this same procedure for all the other unknown resistances. Consider adding a delay after changing the state of the digital pins to allow for the ADC input to acclimate to the new voltage.

simulate this circuit – Schematic created using CircuitLab