How do I know when filter coffee machine is finished by using any sensor? I have a filter coffee machine that seems like the following link ;
https://www.electrolux.com.tr/kitchen/small-kitchen-appliances/coffee-makers/coffee-maker/ekf5300/
and I would like to send a message to the machine users by using any development board(like Arduino or NodeMcu) when the machine is finished.
I haven't found a way to detect when the machine is finished. (I also don't want to do any physical change on the machine, like adding any cable or opening in the machine. I can use any sensor or so on).
How can I do that? Any advice?

Just two ideas, both non-invasive:
The machine moves water from the reservoir at the back to the coffeepot at the front of the machine, so its weight distribution will change while making coffee.
If you put a thin pressure pad (like this one, or something similar) under the whole machine at the back you should see the pressure at that point become smaller while coffee is being made.
If the effect isn't pronounced enough, you could make the whole machine tilt forward while making coffee by putting a narrow and thin strip of plastic under its centre from left to right so it can swivel forward and back just a little depending on the location of the bulk of the water.
If the pressure on the pressure pad at the back stops dropping, the coffee is ready. You can also detect when the coffee can is empty again this way, or maybe even how many cups of coffee are still available in the coffee can.
Or maybe you could detect with a contact microphone when the machine goes silent, assuming it makes sufficient noise when making coffee. Mine does.


Running Pro Mini Continuous on 12v w/o Damaging Regulator A Pro Mini needs to be placed in a 100mmx50mmx25mm, no holes but not air tight ABS plastic enclosure, with a 12v power supply connected to the raw input. It will be consuming max 40mA, ambient temperature 30-32C, and needs to be run 24/7. Upon prototyping in open air, I tried to touch the regulator MIC5205, after 30 seconds upon powering on with my bare fingers and it was too hot to touch. The rest of the components were cool to touch. I would use a buck converter to step down to 5v, however there isn't space for it in the current setup.

I used to run a Mega 24/7 on 12v, consuming much more current about 700mA, the onboard regulator malfunctioned after 1 year of use, which I believe was due to the excessive heat, as the PCB around the regulator turned a little brownish.

Despite being hot to touch, I understand that electronics run in heat all the time like computers, routers, etc for 24/7. Therefore, I would like to know if 12vx0.04A=0.48w will be too much heat/feasible to run in the above mentioned setup, without damaging the regulator in the long run?

Summary:

Simple, effective, low cost solution - choose any 3:
A series resistor in the regulator input, of properly designed resistance and wattage will greatly reduce regulator temperature and increase overall reliability. Reason and design details given below.

Detail:

Assuming a 5V processor dissiaption in the regulator is
(Vsupply - Vregulator_out) x Current
= (12-5)x 0.040 = 280 mW - usefully less than the 480 mW if you are dissipating all the power in the regulator.
For a 3V3 processor dissipation is (12-3.3)* 0.040 ~= 350 mW

"Too hot to touch" is a minimum of 55C and probably hotter - say 70C for now.
At 30C ambient delta T = (70-30) = 40 C.
Thermal resistanc = dT/Watts =40/0.280 = 140 C/W or 114 C/W at 3V3.

Both of those thermal resistances are very high. You do not describe what heatsinking is on the regulator but that suggests PCB copper only and not much of it. Even adding a very rudimentary heat sink should help immensely. If there is no obvious way to add a formal heat sink then adding a 'flag' of copper or brass by soldering should be doable.

Using Mark William's 220C/Watt figure (see datasheet for conditions).
Say 300 mW (see above).
Delta t = 220 C/W  x 0.3 W = 66 C rise.
Ambient is 30-32 so allow 35 for very minor safety factor.
66 C rise + 35 C ~= 101C - water boils.
And temperature inbox will rise mildly from energy dissipated so hotter again.
BUIT a series resistor inside the box or external  will make an immense difference.

An easy and effective solution:

The regulator needs some "headroom" - some voltage above the Vout value to allow some dropacross the internal switch. Check the data sheet, but a modern LDO probably allows as little as 1V headroom. So, for 5V out you need 6V in. The extra 6v from 12V to 6V is not "needed" by the regulator. So, it can be dissipated in a low cost high reliability resistor.
Determine

Vsupply_minimum - the absolute lowest value supply will assume.
Vreg_in_minimum  I'll use 6V to start.
I_load_maximum - you said 40 ma. This must be abs_max or if of very short duration must be able to be supported by capacitors.

Then

Rmax = V/I = (V_supply_min-Vregin_nax) / Imax
= (12 - 6 )/.040 = 150 Ohm.
This is the absolute maximum resistor that meets the specification. A slightly smaller value will be safer. Say 120 R in this case.
Then
Pmax in R = I^2R = .04^2 x 120 = 192 mW.
A 500 mW resistor would be "safe enough" and a 1 watt one very safe.
Pregulator max = (6-5) x 0.040 = 40 mW, 14% of the 280 mW initially.
A  W resistor with adequate cooling will be very safe. Safest is probably a purpose built air cooled wire wound.

Note that the dissipated energy will raise internal ambient. A resistor is still an effective solution.

Place a suitable decoupling capacitor at the regulator input. Even if not normally used here it is needed due to the series input resistor raising the supply resistance.

._______________________________________

Temperature rise inside box due to heat dissipation.

Summary: Using pessimistic assumptions for box thickness, available area and power dissipation an internal temperature rise of under 15 degrees C can be expected. As the regulator is now dissipating under 15% of the original dissipation due to the series resistor it will have a far longer operating lifetime.

Notes:

Temperature rise (assuming no air transfer occurs) is limited by heat transfer through the plastic. This is controlled by the thermal conductivity of th e plastic, its thickness and its area.  Obviously:
 - Thicker plastic leads to higher temperature rise.

More surface area leads to lower temperature rise.
Higher thermal conductivity of the plastic leads to lower temperature rise

So given Thermal conductivity = Ktc

Delta T = Watts x thickness / (Ktc x area)

So Ktc = Watts x thickness /(Delta_Tx area)
So units of Ktc must be Watts/metre/degree_C
Which is indeed how Ktc is usually expressed.

This table of Thermal properties of plastic materials lists Ktc for ABS as 0.17 W/m/K
This means that 170 mW will cause a 1 degree K (or C) rise when plastic ratio of thickness to area is 1.

Assume thickness of box = 5mm = much higher than is likely.
Box area for a box L x W x D = 2 x (LW + WD + DL)
Here  = L D W = 100mm x  50mm  25 mm or 0.1 x 0.05 x 0.025m
Area = 0.0175 m^2.
Use a smaller more pessimistic area of 0.01 m^2
Use a pessimistic heat dissipation of 0.5 Watts

Using the formula - Delta T = Watts x thickness / (Ktc x area)  from above

Temperature rise = 0.5 x 0.05 / (0.17 x 0.01) ~= 15 degrees C (or K)
This is based on a thicker than likely box, smaller than actual area, and higher than expected energy dissipation. A 15C rise is bearable and actual is lower, and as the regulator now dissipates under 20% of original it will survive very well.


How do I use the Arduino Mega as a 16-bit SPI slave? I have to interface an Arduino Mega as a slave with a SPI master running at 1 MHz SCK. The master will send and ask for two bytes in a single transaction. I tried using the following code for the Mega. Its intended functionality is to store the master's sent data in acc and return local data ret, which is simply an integer to be incremented every transaction.

However, while the master data is stored in acc (verified through serial output), the data returned to the master is not the value in ret. Instead, the first response byte is correct (MSB of ret) and the second response byte is just the first byte received by the Mega, which was the value already present in SPDR.

How do I send the second byte of ret as the second byte of the response? What am I doing wrong?

// SPI Slave

#include <SPI.h>

// return to master
volatile unsigned int ret;

// accept from master
volatile unsigned int acc;

// MSB/LSB indicator
volatile byte SB;

void setup(void)
{

  ret = 0;
  SB = 0;

  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // set CPOL, CPHA modes
  // byte dataMode = 0;
  // SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode;

}

// SPI interrupt routine
ISR(SPI_STC_vect)
{

  if(SB == 0) {
    acc = SPDR << 8;
    SPDR = ret;
    ret++;
  }
  else {
    acc += SPDR;
    SPDR = ret >> 8;
  }
  SB = (SB + 1) & 0x01;

}

void loop(void)
{
  // interrupt processing only
}

Edit Changed SCK from 16 MHz to 1 MHz

You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode.

  In SPI Slave mode, the control logic will sample the incoming signal
  of the SCK pin. To ensure correct sampling of the clock signal, the
  minimum low and high periods should be: Low period: longer than 2 CPU
  clock cycles. High period: longer than 2 CPU clock cycles.

This implies the maximum SCK in slave mode. 16 MHz SCK would be too fast for an Arduino Mega (at 16 MHz).

Also there is a significant latency to the ISR. To achieve higher slave mode clock frequency:

Time between slave mode chip select and clock must be stretched to compensate for the ISR latency.
The ISR will need to busy wait for all data (as the Arduino SPI transfer() is implemented).

Cheers!


Dynamic Serial port selection and use without instantiating all Serialx objects I have an arduino project that reads a config file from SD and then receives data on a serial port that is specifed in the config file.

I therefore need to instantiate the Serial (Serial0), Serial1,..2,3, etc based on dynamic data.

I am using a mega2560 with 4x HardwareSerial. Serial (also Serial0) is the USB. Serial 1, 2, 3 are on specific hardware pins.

I started with code something like:

uint8_t InitPort(uint8_t port) {
    switch (port) {
        case 0:
            if(Serial.begin(9600) return 1;
            break;
        case 1:
            if(Serial1.begin(9600) return 1;
            break;

        ... etc...

        default:
            return 0;
}

However, this instantiates all Serialx objects (using 157 bytes of data/bss each).

I've since written a class wrapper that takes a referece to the desired serial object as an initialising paramter, but this just pushes the problem up-stack to the calling code.

Is there a way that a Serial object can be instanitated dynamically with a port number passed in, to only end up with one instance connected to the desired port?

You can create an instance of HardwareSerial referencing a hardware
port that depends on a function parameter, as in

void initPort(uint8_t port) {
    switch (port) {
        case 0: {
            HardwareSerial serial(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            serial.begin(9600);
            break;
        }
        case 1:
            // etc...
    }
}

However, since only a local variable can be created in this manner, it
is not of much use. Ideally, you would want to have a global variable
for the serial port, and initialize it in initPort(), as

HardwareSerial serial;

void initPort(uint8_t port) {
    switch (port) {
        case 0:
            // Invoke fictional init() method.
            serial.init(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            // etc...
    }
    serial.begin(9600);
}

Alas, this is not possible, as the HardwareSerial class has no default
constructor. This means that binding the object to the hardware port can
only be done when it is constructed.

Short of modifying the Arduino core (adding a default constructor and an
init() method), the only option I can see is to have the global
variable be a pointer. Then, in initPort() the object is
instantiated while initializing the pointer. I tried this approach in
the example program below. There was a slight technical difficulty
though: since the object files from the core defining Serial,
Serail1, etc. will hopefully not be linked to the program, the
interrupt service routines defined therein must be also defined in the
sketch itself. And since an ISR cannot be bound to an interrupt at run
time, the ISRs have to be defined for all the ports, even though only
one ends up being actually used.

Here is my test program:

#include <HardwareSerial_private.h>

HardwareSerial *serial;

ISR(USART0_RX_vect) { serial->_rx_complete_irq(); }
ISR(USART1_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART2_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART3_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART0_UDRE_vect) { serial->_tx_udr_empty_irq(); }
ISR(USART1_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART2_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART3_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));

void initPort(uint8_t port)
{
    switch (port) {
        case 0:
            serial = new HardwareSerial(&UBRR0H, &UBRR0L,
                         &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            serial = new HardwareSerial(&UBRR1H, &UBRR1L,
                         &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
            break;
        case 2:
            serial = new HardwareSerial(&UBRR2H, &UBRR2L,
                         &UCSR2A, &UCSR2B, &UCSR2C, &UDR2);
            break;
        case 3:
            serial = new HardwareSerial(&UBRR3H, &UBRR3L,
                         &UCSR3A, &UCSR3B, &UCSR3C, &UDR3);
            break;
    }
    serial->begin(9600);
}

void setup() {
    initPort(0);
    serial->println("Hello, World!");
}

void loop(){}

It should be noted that the ISRs do not take that mush flash space.
There are actually only two of them, even though each is referenced four
times in the interrupt vector table.


Visual clock with millisecond display refresh rate I need to create a millisecond capable visual clock - I will use the clock for visual frame synchronization of multiple cameras. I found this project but it seems to use a LED display that only has resolution of one 1/100th of a second. Not sure if the digits can be shifted to show milliseconds.

I guess I need to use LED instead of LCD display because of the ms refresh rate? Can someone help with my project please? I am a SW programmer and have zero experience in HW programming. So I am new to Arduino too - I have not done any project at all yet. I do own neither Arduino nor LED display.

Thanks!

You need to define the parameters of the problem more clearly.

First, and most importantly, what is the shutterspeed you'll be using? If it's longer than 1 ms, then you can't use a 7-segment display to show the MS count, since the camera shutter would be open for multiple values.

Even if your shutterspeed is a single MS, your shutter won't be synchronized with your timer, so sometimes the shutter will be open when the display switches. That can even happen with the seconds digit of your time display.

If you're using a video camera, assume the frame rate is 60 fps, which gives a likely shutterspeed somewhere around 16.6 ms. That's way too long to display ms time values using 7-segment displays.

The ring of LED idea is good, but I would tweak it.

Here's what I would do: Build an LED clock to display whole number seconds. Don't multiplex, use latches and drive each 7-segment display constantly. (There are off-the-shelf CMOS chips that are latching 7-segment drivers.) If you only care about the 1s digit of the second value, only use 1 7-segment display. That will make things easier to wire.

Use 3 rings or columns of 10 LEDs for the MS display: tenths, hundredths, and thousandths. I would lean towards using columns since it would be visually easier to read.

The display will show your seconds as numbers, and 3 columns of 10 LEDs, showing the sub-second time range in 10ths, 100ths, and 1000ths. If the shutter opening spans multiple MS, as it will very likely do, all the LEDs that represent the sub-second time will be lit in the image, so you will get a nice clean visual image of the time SPAN that the shutter was open (All the LEDs from the start to the end of the shutter opening will be lit.)

You could drive the 3 columns of LEDs using 3 4017 divide-by-10 counters. These chips have both a 1-of-10- output, which will drive an LED, and a count/10 output, which would feed the next stage.

Write Arduino code that generates a short positive pulse every MS. Feed that into the clock input of the 4017 driving the thousandths digit. Feed the out/10 output of that chip to the clock input of the hundredths 4017, and the output of the hundredths 4017 into the clock input of the tenths 4017.

You can drive the whole ms display with 2 Arduino lines: The ms clock, and a reset line tied to all your 4017 counters' reset lines. To start timing, first pulse the reset line to zero them all out, then start your ms clock.

My CMOS cookbook doesn't say how much current the 4017 will put out to it's 1-of-10 outputs, but I bet it's enough to drive a display LED directly. You could wire all 10 LEDs in each column as common cathode, with a single current limiting resistor between each column's common cathode and ground.

You could probably set up a timer pin on the Arduino to generate a millisecond pulsed output, but that's not something I've learned how to do yet.

Occasionally you'll get a whole second 7-segment display with 2 different values captured in a frame, but that will be rare, and you will be able to figure out what happened from the frames immediately before and after it. (Previous frame shows a 5. Current frame shows a 5 and a 6 superimposed, so it's a mess. Conclusion, this frame shows the end of second 5 and the beginning of second 6.)


Is there a way to combine a 3-axis accelerometer/gyroscope into one value? I have a three-axis accelerometer that reads me its x, y, and z components.  This results in three graphs.  Is there a way to "combine" these components into one reading, hence, one graph?   Same question holds for a gyroscope.

The datasheet for my device is here:

The answer is: technically, yes, it is possible. The combined result is called Quaternion. This is what is typically used in 3D programs.

But most likely that is not what you had in mind.

Usually one can do a simplification and reduction of dimensions when in presence of some constraint.

Imagine that your moving object is bound to a planar surface: no matter how you tilt and rotate and pan it, it is still a 2D surface, plus a quaternion indicating the rototranslation.

But, once you have established the coefficients applied to the rototranslation, it is 2D.

Similar 1D case: imagine that your moving object is bound to some well-known geometrical shape, say a circumference. Once you have established how the circumference is oriented in the 3D space and its radius, you can express the position of your device by indicating either the angle or the distance from a reference point on the circumference.

In both cases you can simplify the representation because of constraints that do not allow for real 3d movement.

But if your device is a flying drone that can rototranslate freely within certain boundaries (max horizontal range, min/max altitude), there is no way that you can simplify the 3d coordinates.

If, instead, your question was related to the protocol used to read info from the accelerometer, you are bound to the protocol defined in the datasheet, by the manufacturer.


can we make Drone with Dc 180 motor and Arduino? I want to make a drone as a project for my university, But I am kinda newbie in this, I did many searches about this and I found I should do it with the brushless motors (BLDC) but I can't buy this kind of motors, So I want to do it with DC motors I found in youtube there is motor can be used in the drone it called ( 180 dc motor) but they didn't use them with Arduino.
My question is can I use Dc 180 motor with Arduino and make a drone Or Not?

Yes you could but you will have to use a motor driver or else the motors will not be able to get enough power and try using arduino micro or an esp32 if you want to use it with Bluetooth which will also help you to keep the weight down.


Can I use a 6 pin Bluetooth module in a 4 pin socket? I have a Funduino joystick shield and it features a 4 pin bluetooth socket in the top right hand corner (just above the D, T, - and + legends).

For some reason, on eBay, 6 pin bluetooth modules are cheaper and more common than 4 pin bluetooth modules.

The joystick shield's 4 pin socket is labelled R T - +. Obviously these correspond with RXD, TXD, GND and VCC on the bluetooth module.

I was wondering:

What is the difference between the 4 pin and 6 pin modules?
Can I use a 6 pin module in the four pin socket on the joystick shield?
What is the function of additional STATE and EN pins on the bluetooth module?
Are these two additional pins necessary as other modules do not have them?

After some more concerted searching I have found the answer on Success Using the JY-MCU (linvor) Bluetooth Module:

  The module has 6 pins labeled on the back, but most modules only have
  4 of those populated with pogo pins.  KEY & STATE seem to be not
  required, as KEY is used for flashing the device and STATE simply
  indicates if the device is awake or not.  So that leaves only GND,
  VCC, TXD, RXD.  Not shown is Pin 11 which is the RESET pin, resetting
  the module when pulled LOW.

So, the answer is apparently yes, and you can buy a cheaper 6 pin module and remove (snip/desolder) the two additional pins.  The EN pin is also apparently labelled as KEY on some modules.


Wide range of protocols one chip? Is there some way to do raw radio on a esp32 and change frequencies. If not what would I need to transmit rf, wifi, bluetooth, zigbee etc. There seems to be no tutorials on how to do anything of the sort.

There seems to be no tutorials on how to do anything of the sort.

That's because doing such a thing is not something the manufacturer of a part typically expects you to want to do. Yes, some chips may be capable of other protocols internally, but making them use those protocols would mean direct manipulation of the low level components in the chip.
Chips like the ESP32 or the nRF24L01 are geared towards specific protocols. They expose functionality that is good for those protocols.
There are other chips which are designed with (almost) any protocol in mind, but there's nothing "arudinoy" about using them. To access other protocols you would download the SDK for that chip and create new firmware specifically for the protocol you want to use. In many cases such SDKs and the associated documentation is protected under NDA so you or I getting access to such a thing is not usually possible.
In general though a chip is designed with a specific protocol and application in mind and is optimised specifically to handle the requirements of that protocol.


Ardiuno DUE board. Sketch uploading Error I am working on Arduino UDE board in Ubuntu 18.04. I've followed following link tutorial.
https://www.arduino.cc/en/Guide/ArduinoDue#:~:text=Use%20your%20Arduino%20Due%20on%20the%20Arduino%20Desktop%20IDE,the%20Arduino%20Boards%20Manager%20page.
In Ardiuno IDE I am getting as /dev/ttyS4. Also, I've gone with follwing procedure :
sudo usermod -a -G dialout username
sudo chmod a+rw /dev/ttyS4
ls -l /dev/ttyS4

This gave the following outpit
crw-rw-rw- 1 root dialout 4, 68 Jun 17 17:26 /dev/ttyS4

And I am getting following error while uploading sketch though Ardiuno IDE :
Sketch uses 11092 bytes (2%) of program storage space. Maximum is 524288 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyS4
/home/user/.arduino15/packages/arduino/tools/bossac/1.6.1-arduino/bossac -i -d --port=ttyS4 -U false -e -w -v -b /tmp/arduino_build_718911/ardiuno_to_python.ino.bin -R
Send auto-baud
No device found on ttyS4
An error occurred while uploading the sketch
Set binary mode

I've tried following solution of decreasing baudrate to 1200 by following command line mulitple times till I get output as 1200 :
stty -F /dev/ttyS4 speed 1200 cs8 -cstopb -parenb

Still I am facing the error while uploading sketch. I've tried pressing reset and erase buttons few seconds but still not getting anything. Can anyone please help

The problem is solved. The cable came with my Arduino was charge only , I tried data transfer cable and it worked. This is so dumb. sorry for wasting your time.


Using strings inside mBlock extensions code The following question is about a 3rd party Arduino programming enviroment mBlock and creating extensions for it. I hope that there are some of you out there, who are fammiliar with it.

I was recently making an extensions for mBlock that can be used to write code for Arduino, when I came over this obstacle. I tried to write a function inside the "work":"" statement.

It looked like this:

"work":"Serial.print("Hello world");"

The extensions could not be imported, due to the quotation marks around the Hello world string. I tried removing the quotation marks, the extension was sucessfully added, but the program did not work, beacause quotation marks are needed inside C++ code to define a string.

Is there a way to add them in the extensions, without screwing up the code?

If that is a JSON format you could try using single quotes instead of double quotes:

"work":'Serial.print("Hello world");'

Alternatively you could escape the internal quotes:

"work":"Serial.print(\"Hello world\");"


Part of Board exploded when Peltier Plate was wired t(o Board Photos and Screenshots: https://imgur.com/gallery/bpmJglE
By the way, I used a screenshot that was originally from this post: Have I bricked my Arduino Uno? Problems with uploading to board
Hey guys,
I was trying to wire two TEC1-12706 Peltier plates to my breadboard, and I saw that using the USB connection for power was not enough for both plates. So, I found a 19v--3.9A DC/AC adapter/computer charger and plugged it in to my Uno via the Power Jack port. The Peltier plates were not wired to the board when I plugged it in and everything looked fine, all the normal LEDs on the UNO lit up, etc. Then, I wired a peltier plate to my breadboard. As soon as I did, a part exploded, and grey smoke come out of the "L" light area. I unplugged it immediately. The next day, I plugged the adapter back into the Power Jack port and a screenshot is attached of some observations I made by touching the board. Photos of my Uno are also attached. As you can see, the "Slightly less hot but still burning part" is pretty much destroyed. The "L" light will not light up and as of right now I can't upload any code to it. Might be an unrelated issue so I will continue troubleshooting that, but it is still another observation. The test LED I wired is lit up, so I guess the board can still kinda function? I'm high school student and obviously a complete beginner. Will continue to do research on this. I really want to know what happened. Please help?  Thanks everyone.

You did a pretty good job of nuking your board. Gratz.
Basically what has happened: you connected 19V to the input of the 5V regulator (rated at 800mA max) and connected a 12V 50W device to the output.
I have no idea what a peltier will do when under powered, but at 12V it's going to want about 4A. That's 20x more than the 5V regulator can provide (also exacerbated by the massive amount of heat needed to be dissipated to drop 14V) - so it went pop.
In going pop it short circuited. That meant that 19V (or just short of) ended up going into the rest of your Arduino. The 3.3V regulator didn't like that (the bit that looks toasted), and neither will any of the rest of the components on the board.
In short: probably almost every component on the board has been nuked.
The moral of this story: don't connect high powered 12V devices direct to the Arduino. Things like peltier devices need their own dedicated power supply which can be controlled (as you would a motor or relay) through a power MOSFET.


4 Digit, 7 Segment Display Wiring (14 pin) I purchased this 4 digit, 7 segment display from Adafruit:

Product: http://www.adafruit.com/products/865

Data Sheet: http://www.adafruit.com/datasheets/865datasheet.pdf

Everything I have searched for on the net either has 12 pins or 16 pins and most of those are only using 4 resistors.  This one has 14 pins.  I'm trying to wire it up to an Arduino but I'm not sure which pins should have resistors and which shouldn't.  If I wire it up like in the product picture with 1k resistors, I get 8.8.:8.8. and as I remove resistors from 5V, I can see the different sections that are lit/not lit.

Is that the correct way of doing it?  Can I now just wire those to the Arduino?

It's just a 12 pin display, but with two extra pins for the colon.

Removing connections can help you better understand what it going on.

Resistor should be added to the anodes (pins 1,2,3,4,5,8,9,12,13) just like on the website. Pin 8 should be a different value, to match the brightness of the other (multiplexed) leds.

The other end of the resistor can be put into the Arduino. Depending on the resistor value you may need to add some transistor to drive the other pins (cathodes) on the display. Lower value resistors means a brighter display, but too much current for the Arduino to drive all 8 leds of a digit at the same time.

1k resistors, would mean about 3mA of current per segment. So if all segments are on in one digit, that would be 8*3, so 24mA. Which is approaching the maximum current an Arduino pin can source.


for() loop doesn't seem to break? So I'm quite new to the whole Arduino coding but constructed a sketch that does work, but I think it doesn't work properly. So I'd love to get some advice on how to improve it.
This script is currently running on a Wemos ESP8266 chip attached to a 1 meter WS2812 144 LED strip.
My questions:

The loop is set to break when fadein is higher then 254.
When I try to break it at fadein == 255 the loop doesn't work anymore as it the fadein value directly jumps to 255. Why?

When I set the delay to zero the led flicker due to too fast updating. however, this flickering continues even after the for loop is broken, which makes me conclude that the for loop is still running even when the break is applied.
Of course this is no longer an issue when the delay is set higher (as it is supposed to be) but it still seems a waste of processing power to keep the for loop active while it's not doing anything new anymore
how can i completely stop the loop from being executed?

How can this be done differently / more effective?

The code
#define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
#include <FastLED.h>                                                  //add fastled lib
#define NUM_LEDS 144                                                  //set number of leds
#define DATA_PIN D4                                                   //set data pin leds

CRGB ledStrip[NUM_LEDS];                                              //init led strip
int fadeIn = 8;                                                       //init fade in counter
int led = 0;                                                          //init led counter

void setup() {
  Serial.begin(115200);                                               //setup comm channel
  FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
}

void loop()
{
for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(3);
    if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
      break;                                                          //stop led animation
    }
}

    if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=16;                                                      //increase fadeIn value with 16
    }
    if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
      Serial.println(led);                                             //print led counter value
      Serial.println(fadeIn);                                          //print fadein value
    }
    if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
      fadeIn = 255;                                                     //clamp fadeIn value to 255

    }

}

Consider the sequence of values of "fadeIn". It starts at 8 and in incremented by 16.  So: 8, 24, ... 248, 264, ... .  It is never exactly 255.  So you never break out of your "for" loop.
There is only 1 delay in your example code.  It is difficult to associate the described behavior in your question and the location of the delay.
Arduino programming is actually C and C++ programming.  Developed at Bell Labs, this language has been around for decades and there are countless books on the subject.  Rather than rewriting your program (someone might yet still do this) I would recommend leaning C programming and if you want to write Arduino library software then C++ programming as well.


Put integer and double into char array I want to print text and numbers mixed in a table with Serial.print(); from a char array. My problem is the conversion between the different data types. My idea is to print the data of the rows in a for loop with the variable i and the columns in a for loop with the variable j.

I have in the following example two variable, one is type integer and the second is a double. Now i want to add the values of the variables into the char-array, but I can't find a way to do this...

In my main program the variables need to have this data types and should be inserted later into the char array.

Does someone have a solution for this challenge?

Here is a small example code:

int a = random(0, 100);
double b = random(0, 100);

char* myStrings[][6] = {"This is string 1", "This is string 2", "This is string 3",
                        "This is string 4", "This is string 5", "This is string 6"
                       };

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

void loop() {

  //now put the integer and double variables into the char array in the second column

  //Print the values
  for (int i = 0; i < 2; i++)
  {

    for (int j = 0; j < 6; j++)
    {
      Serial.print(myStrings[i][j]);
      Serial.print("  ");
      delay(100);
    }
    Serial.println();
  }

}

Many thanks in advance.

Guss

EDIT:
The output should look like this:
Headline (in this example it is the text "This is string 1", "This is string 2"...)
and then the values of the variables in the next row. It should be like this:

This is String 1     This is String 2     This is String 3

Variable a           Variable b           Variable int

Variable double      Variable double      Variable int

First of all, you should decide for a datastructure for you table. There are many options with various advantages and disadvantages. I am choosing a statically allocated table here, with a fixed width for each entry in the table and a fixed number of columns. One may also use pointers to strings which are allocated on the heap or elsewhere, but I find this to be the simplest.

Anyways, the basic problem doesn't change: We want to write a integer value in some string buffer. I am using the C library function snprintf() here. This function is like printf(), just that it writes its output to a given buffer of a maximum size. Thus, we can use simple format strings here and some workarounds for non-working format strings (floating points..)

Here is the code.

#include <Arduino.h>

/* A table is a 2 dimensional array of char buffers.
   The core element is a char buffer of fixed size.
   The number of columns must be fixed at compile time.
   Rows can by dynamically added in the structure without having to
   declare the number of elements.
   You can declare the number of rows at compile time, but do not need to fill them.
   Thus you can dynamically add rows to the table.
 */

#define MAX_ENTRY_SIZE 20
#define NUM_COLUMNS 3
#define COLUMN_PRINT_WIDTH MAX_ENTRY_SIZE

char myTable[][NUM_COLUMNS][MAX_ENTRY_SIZE] = {
        {"Column 1", "Column 2" ,"Column 3"}, //Row 1
        {"Variable a", "Variable b", "Variable int"}, //Row 2
        {"Variable double", "Variable double" ,"Variable double"}, //Row 1
};

char* get_table_entry(int row, int column) {
    char* entry = myTable[row][column];
    return entry;
}

void write_int_to_table(int value, int row, int column) {
    //Get a pointer to where the entry is
    char* entry = get_table_entry(row, column);
    //write a new string inside it
    snprintf(entry, MAX_ENTRY_SIZE, "%d", value);
}

void write_double_to_table(double value, int row, int column) {
    //Same as above, different format string..
    char* entry = get_table_entry(row, column);
    //Formatting floats on an Arduino Uno is tricky. %f formatters don't work (cut out due to size.)
    //use String API instead
    String stringFloat(value);
    const char* cString = stringFloat.c_str();
    strncpy(entry, cString, MAX_ENTRY_SIZE);
}

void print_table() {
    //Get number of Rows
    int numRows = sizeof(myTable) / (MAX_ENTRY_SIZE * NUM_COLUMNS);
    for(int row = 0; row < numRows; row++) {
        //Print all columns of this row
        for(int column = 0; column < NUM_COLUMNS; column++) {
            char* entry = get_table_entry(row, column);
            Serial.print(entry);
            //fill with spaces to the right
            for(unsigned int i=0; i< COLUMN_PRINT_WIDTH - strlen(entry); i++) Serial.print(" ");
        }
        Serial.println();

        //Table header seperator
        if(row == 0)
            Serial.println("============================================");
    }
}

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

void loop() {
    int a = random(0, 100);
    double b = random(0, 100);

    Serial.print("Will write new values for a = ");
    Serial.print(a);
    Serial.print(" and b = ");
    Serial.println(b);

    //write these in the second row (first row after header), first and second column.
    write_int_to_table(a, 1, 0);
    write_double_to_table(b, 1, 1);

    //Print table again
    print_table();
    Serial.println();
    Serial.println();

    delay(5000);
}

Two rounds give the output:

Column 1            Column 2            Column 3
============================================
Variable a          Variable b          Variable int
Variable double     Variable double     Variable double

Will write new values for a = 7 and b = 49.00
Column 1            Column 2            Column 3
============================================
7                   49.00               Variable int
Variable double     Variable double     Variable double


Potentiometer won't work I'm trying to get the potentiometer seen at the top left of the photo to work, essentially as a dimmer. I've managed to upload the Arduino sketch, but it isn't working. Any help would be greatly appreciated!
NB: I have little-to-no electronics experience so my understanding of jargon is limited.

Thanks!

/*
 SENSOR_LIGHTS: Potentiometer >> LED (Single Channel Script)

 This example dims light levels using an LED on pin 11
 and a potentiometer on A0.

 Created by Ryan Achten | SOMA | somavisions.com

 This example code is in the public domain.
 */

int potentLevel;
int ledLevel;

//*************************CHECK*****************************

int led = 11;           // the pin that the LED is attached to
int inputPin = A0;      // the pin that the potentiometer is attached to

//*************************CALIBRATE*************************

const int numReadings = 1;  //change this to alter the number of values to be averaged
int potentMin = 280;
int potentMax = 700;        //maximum output from potentiometer
int loopDelay = 100;       //delay time between loops. Too low may cause overclocking
//                            while too high may cause delayed sensor response

//***********************************************************

int potentAve = 0;
int readings[numReadings];
int index = 0;
int total = 0;

// the setup routine runs once when you press reset:
void setup()  {

  //*************************POTENT >> LED SETUP CODE*************************

  Serial.begin(9600);

  pinMode(led, OUTPUT);

  //***************************SMOOTH SETUP CODE*****************************
  // initialise all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;

}

//****************************SMOOTH LOOP CODE****************************

void loop()  {

  total= total - readings[index];
  readings[index] = analogRead(inputPin);
  total= total + readings[index];
  index = index + 1;

  if (index >= numReadings)
    index = 0;

  potentAve = total / numReadings;
  Serial.print("Average Potentiometer Readings: ");
  Serial.println(potentAve);

  //*************************POTENT >> LED LOOP CODE*************************

  ledLevel = map(potentAve, potentMin, potentMax, 0, 255);
  Serial.print("LED Level: ");
  Serial.println(ledLevel, DEC);
  analogWrite(led, ledLevel);

  Serial.println();
  delay(loopDelay);

}

Assuming the brown board in your drawing is stripboard, I have to as the question:
What is this?

If those five wires in that column are all ground, that link is basically short circuiting your MOSFET via the green wire next to it, thus rendering your whole circuit pointless.  The LEDs will just be on full brightness permanently since the current just flows from the input power, through the LED strip, through the red/white wire, through that little white link wire, then through the green/white and/or the brown/white wires to ground.


Controlling VFD with ModBus RTU via RS485 and Arduino I am attempting to control a Folinn VFD (Manual: Manual) with an Arduino Uno via a MAX485 module such as this.

Pins for MAX485:

DI > D8
DE & RE > D10
RO > D11

VFD settings:

F00.01 set to 2
F00.06 set to 9
F13.00 set to 1
F13.01 set to 5
F13.02 set to 3

At this stage I am attempting a very simple code just to turn the VFD on:

/*

   ModBus RTU control VFD

   Address               : 01H  (is the address of the VFD)
   Function              : 06H  (write function code)
   Starting data address : 20H
                         : 00H  (2000H  is the address of control command)
   Data(2Byte)           : 00H
                         : 01H  (0001H is forward command)
   CRC CHK Low           : 43H
   CRC CHK High          : CAH

*/

#include <SoftwareSerial.h>

#define SSerialRX        11  //Serial Receive pin
#define SSerialTX        8  //Serial Transmit pin
#define SSerialTxControl 10   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

// From manual vfd Forward command = 01H 06H 2000H 0001H 43CAH

byte request1[] = {0x01, 0x06, 0x20, 0x00, 0x00, 0x01, 0x43, 0xCA};

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  // digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);

}
void loop()
{
    digitalWrite(SSerialTxControl, RS485Transmit);
    RS485Serial.write(request1, sizeof(request1));

}

With the MAX485 connected to the correct ports (S+ and S-) on the VFD, this current setup receives no response is someone able to spot where I am going wrong? I have taken the values for CRC CHK Low & High from a different example, is this the issue?

Have also tried setting F00.01 to an unlisted '3' setting that I have seen pop up in other discussions but this made no difference. Any advice would be much appreciated, let me know if I can supply further details.

(I chose this method based on this example

User on other site (https://forum.arduino.cc/index.php?topic=663365.0) Might have default run conditons on VFD set differently or by hardware.

Check the VFD is listening to the ModBus Comms.  OK.

Check VFD is 'Ready to Run'. Hardwire e-stop or 'Active' inputs.
F00.22 Check Binding source
F00.05 Check Set min Hz
F01.01 Check Set min Hz

Give drive MIN Hz So when received RUN signal has default speed to goto.

Are you doing a Hard Reset on the UNO every time you want to send the Modbus string? Code runs once, does not actively transmit.


Line not printing int in Serial Monitor I'm trying to make a kernel for a macro-key maker, this is the starting page's code:

char m[] = "What do you want to do? Type the following commands in this "
      "terminal:\nnew  --> Creates a new Keybinding\ndelete  --> Deletes a "
      "previous Keybind\nlookup --> Find what is bound to a key\n\nTurn off the "
      "switch to go back to the normal mode.";
Serial.println(m);
Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

When I run it, the screen displays:

What do you want to do? Type the following commands in this terminal:
new  --> Creates a new Keybinding
delete  --> Deletes a previous Keybind
lookup --> Find what is bound to a key

Turn off the switch to go back to the normal mode.

The last line is missing.  Is this a problem with object casting? takenKeybind is an int.

You should never do this:

Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

Yes, it should cope with it and append the strings, but that's really nasty even if it does work. And there is absolutely no call to ever do concatenation when printing to serial.

Instead just use:

Serial.print(takenKeybinds);
Serial.println(F("/64 Keybinds taken."));

Note also the use of the F() macro when printing a string literal. This keeps the string in flash and prevents it being copied to RAM, which is just wasteful.

The same with your big long string - it's wasting RAM, and if you never want to modify it, why have it in RAM? Better is:

Serial.println(F("What do you want to do? Type the following commands in this terminal:"));
Serial.println(F("new  --> Creates a new Keybinding"));
Serial.println(F("delete  --> Deletes a previous Keybind"));
Serial.println(F("lookup --> Find what is bound to a key"));
Serial.println();
Serial.println(F("Turn off the switch to go back to the normal mode."));


ESP32 AP max connections: 4 or 10? I am using the SoftAP feature of the ESP to create a central node, and connecting five or six clients in the final application. However, I don't know if i can connect that many clients.

One of the core files on GitHub, esp_wifi_types.h shows two conflicting lines:

#line 215, as a member of the 'wifi_ap_config_t' struct
uint8_t max_connection; /**< Max number of stations allowed to connect in, default 4, max 4 */

#line 254
#define ESP_WIFI_MAX_CONN_NUM (10) /**< max number of stations which can connect to ESP32 soft-AP */

So is it four or ten? Or something else? Any advice by somebody who's tried this would be appreciated.

esp_wifi_types.h on GitHub

The answer is as clear as any other EspressIf configuration data, it is 4 or maybe 5, or 8, or 12, 16 or even 20 (the same as a ESP8266!)

To clarify, it seems that around 2015 the maximum was 4 connections, but it is possible to recompile the SDK to support up to 16 connections.  There doesn't seem to be a #define of flag that will let a programmer control this.

These links may guide you to a proper solution:
https://github.com/esp8266/Arduino/issues/570
 or https://myesp8266.blogspot.com/2016/11/esp32-increase-maximum-number-of-sockets.html


DFPlayer library using RT TX pins I am using the DFRobotDFPlayerMini-1.0.1 library by Angelo. I am trying to use the actual RX TX pins on a Uno R3, but it doesn't connect unless I type in an alternate digital pin number. This is no good for my application as I have a major pin shortage. I have tried typing in (0,1) but that is not being accepted.

The reason for using this library is because it provides a LOOP function that works well.

How do I use the RX TX pins with this library?
Is there another library that has a good LOOP function in it?

Thanks.

Doug

On a classic Arduino pins 0 and 1 are used for serial communication with the host PC, so you cannot use them to talk to a peripheral without conflicting with that.  The library may well be coded to trap and reject such an attempt.

On various alternate (ARM, Atmega32u4, etc) boards these pins may be usable, though the library may not be aware of that.  Also on such boards you would generally want to use an available hardware UART rather than a software simulation of one, which may be fairly ATmega-specific anyway - the end result of which is that library code may well need modification to work on a non-traditional device.


Is this method to a String from a function going to cause memory corruption? I'd like to define a function such that I return a string and a boolean indicating whether the result is valid. Like this:

bool getStringOrTimeout(String *s) {
  ...
  if (timed_out) {
    return false;
  } else {
    *s = String(<some value>);
    return true;
  }
}

Is this going to cause a memory problem because the string is allocated on the stack and deallocated when it leaves scope, or is this okay?

You are better off passing the string by reference, like this:

bool getStringOrTimeout(String & s)
{
  if (timed_out)
    return false;
  s = "foo";
  return true;

}

That means the caller's string will be modified. And you no longer need to pass down a pointer to a string.


MKR ZERO is not detected in IDE / MKR ZERO not showing up in windows 8.1/ I m connect it with my IDE software and its work perfectly yesterday, but today morning I'm connected it to software to upload another sketch but its didn't detect the port and the charge led is not on yesterday but today is on. I tried every resolution which is given on website but its didn't work. please help me through this I'm new to this board.

A few possibilities come to mind:

Your USB cable is bad.  Try a known good one.
Your USB port has failed.  Try a different port or try plugging something else into this one to verify that it's still OK.
Your MKR ZERO has become damaged somehow.


DVD drive stepper motors with polulu a4988 on Arduino I am new to arduino, I started learning about it today and i'm stuck. I ripped out a small stepper motor from an old DVD drive. I got a polulu a4988 driver and I have wired it up as follows:

/*     Simple Stepper Motor Control Exaple Code
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 */
// defines pins numbers
const int stepPin = 3;
const int dirPin = 4;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}
void loop() {
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000); // One second delay

  digitalWrite(dirPin,LOW); //Changes the rotations direction
  // Makes 400 pulses for making two full cycle rotation
  for(int x = 0; x < 400; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000);
}

But nothing happens, the motor doesn't even vibrate. Any idea what could be wrong?

According to Pololu's website, the VMOT pin needs at least 8V to function. Try a 12V switching (important!) wall wart supply that can supply at least 1A instead of your USB supply. Avoid supplies that can deliver currents >3A, as they are overkill for a small stepper motor and can be dangerous if shorted. Be sure to put a large (100uF is good) capacitor across that supply to prevent voltage spikes. To prevent damaging the motor from the higher voltage, follow the information Pololu provides on setting the current limit and set it to about 350mA. If you notice the motor is too hot to touch, try 200mA.


Using Capacitance-to-Digital converters AD7150 or AD7747 to measure fluid levels I'm looking to measure the fluid inside a polyethylene waste holding tank with walls 10 mm thick. This is typical of a boat or RV. I'd like to measure using proximity sensing capabilities of Capacitance-to-Digital converters, which have no direct contact with liquid, are highly accurate and have low current requirements. Analog Devices makes two sensors, AD7150 and AD7747 that might work based on the specs I've read, but I don't know if they'll measure through the holding tank walls. If anyone knows if either of these would work, or has any other suggestions I'd appreciate your advice. Thanks.

Sounds like a fun project. Why not try the EVAL-AD7150EBZ is a fully featured evaluation board for the AD7150. The evaluation board can be operated in standalone mode ( either battery-powered or with external power supply) or connected to a PC via a standard USB interface. When operated with a PC, software is provided enabling the user to perform detailed analysis of the CDC's performance. This software includes the technical note describing the operation and set up of the evaluation board. Also how you package the sensor will have a big impact on how it works.


Do I need 3 full-size arduinos to control this LED setup? I'm sourcing the parts now for an LED persistence of vision setup on a bicycle.  Two wheels with anywhere between 16-32 LED's per wheel, as well as 24 LED's mounted on the frame of the bike itself

Since the Arduinos have to be mounted into the wheels to drive the POV displays - do I need a total of 3 arduinos?

Driven by 2x [Nano 3.0 Atmel Atmega328P Mini-USB Board][1] + an Arduino Uno from the frame?
So far I think I'll pick up 2 x [433Mhz RF Transmitter Module + Receiver Module Link Kit][2] for wireless control, [Reed Switch Magnetic Detection Sensor Module][3] for calculating velocity from a small magnet mounted somewhere on one of the forks. 4 x [WS2811 RGB 8-LED Light Strip Module][4] as the POV LED's, or maybe some of the [DotStar Digital LED][5]
and miscellaneously perhaps are some of these required/ useful? maybe instead of the 4x8 I could go 4x [SSC Seoul P4][6], or from [SparkFun][7],  following pieces of [this guide][8]

DIY AT89S52 Microcontroller Development Board Set
[KT0026 Electronic Parts Pack][9]
[Square Prototyping Plate][10]
[ZnDiy-BRY Z-069 MB102 Breadboard + Power Supply Module][11]

My main concern is refresh rates....getting everything controlled...and making sure I have enough I/O. Any help would be greatly appreciated.  (URL's available on request :P)

Maybe look at NeoPixels Revealed: How to (not need to) generate precisely timed signals. The author there controlled 1000 Neopixels with a Duemilanove with fairly simple code. These were WS2812 not WS2811 but perhaps the code could be adapted to suit. Judging by the datasheets they are fairly similar.

Since he got 30 fps with 1000 pixels, your requirement of around 100 pixels would seem fairly straightforward.


Why does my dc motor immediately spin when connected to a 9v battery? I've set up a DC motor connected to my Arduino Uno with the following layout. I'm using a 1.5V - 3V DC motor that was purchased from RadioShack.

Here is my code:

int controlPin = 9;

void setup(){
  pinMode(controlPin, OUTPUT);
  Serial.begin(9600);
  while(!Serial);
  Serial.println("Ready");
}

void loop(){
  if(Serial.available()){
    int s = Serial.parseInt();
    if(s >= 0 && s <= 255){
      Serial.println(s);
      analogWrite(controlPin, s);
    }
  }
}

If I connect the motor through the Arduino 5V pin it only hums until I set the speed s to 200 or greater. This seems odd because I'm supplying 5V.

As a next step I decided to try a 9V battery (I don't really care if I fry the motor, I just wanted to experiment). Of course this is over the recommended voltage, but I assumed if I sent a low enough signal (s) through pin 9 it might not destroy the motor. However, to my surprise, when I connected the 9V battery (as illustrated below) the motor immediately starts spinning. I measured the current and it seems to be ~150mA when connected to the 9V battery. It seems like the circuit is connected even though I'm not sending any signal from pin 9 to the transistor. If I removed any of the wires connected to ground, the motor, obviously, stops spinning. My expectation, which is apparently wrong, was that the motor wouldn't spin until I sent a signal from pin 9 to the transistor. What am I not grasping here?

Here's a picture as my diagram may be wrong based on comments below. This shows the diode reversed as suggested by Chris.

I also moved the jumper going from pin 9 to the breadboard out of the Vcc column and directly into the row with the resistor. I'm not sure if that resolves the short mentioned in comments.

Your wiring diagram is a jumbled mess, and makes it impossible to figure out what's really going on.

My guess is that you have a mistake somewhere in your wiring.

Problems I see with your wiring diagram:

You show pin 9 from the Arduino wired to the positive rail of your breadboard. If the positive rail is connected to a 9V battery, this will likely destroy pin 9 of your Arduino.
You show the gate/base of your transistor wired to the positive rail of your breadboard. This would switch your transistor on constantly.
You show the symbol for a MOSFET transistor, but the label on it lists it as a 222A, which is an NPN BJT, not a MOSFET.
You don't show any wires connecting the left and right side rails of your breadboard.
You're using a row of your breadboard as the ground rather than the rails.

The picture you posted is too small to tell if your wiring diagram is wrong or if you actually connected things incorrectly, and the wire from your 9V battery is blocking the camera's view of key connections.

It looks like your wire from pin 9 is NOT connected to the power rail, but is instead connected to column 1 in your breadboard, which is good.

There are some strong conventions in wiring with breadboards and you should learn to follow them. The two pairs of columns of sockets on the left and right are for positive and negative supply voltage. Usually you wire them together and connect them to regulated power. Sometimes they will be used for different voltages, although you need to be really careful if you do this, since connecting to the wrong side can fry components.

It's confusing the way you've created your wiring diagram, but it looks like you have your flyback protection diode wired correctly, which is good. That's very important, as DC motors and other inductors create destructive reverse voltages as they are switched on and off, and without a flyback diode it can destroy solid state devices like ICs or even transistors.

You should re-wire your breadboard using the proper conventions, and post a corrected wiring diagram that really shows what's going on.

A picture where we can see all the wires and components clearly would also help.

Until you better learn what you are doing I would strongly advise against powering things directly from a 9V battery. When you do that, a mistake in wiring will fry your Arduino and/or any ICs you have on your breadboard.

Wire the 9V to the V-in pin on your Arduino, and then bring 5V and ground from the Arduino onto the +/- supply rails of the breadboard.

I also notice that in your code, you never set the state of controlPin in your setup method. You should add this line to your setup:

digitalWrite(controlPin, LOW);

That way the pin starts out in the OFF state, and then later on you can us an analogWrite to set it to the desired output level.


SRF04 Ultrasonic sensor - inaccurate readings I have an Arduino Uno linked up to an SRF04 ultrasonic sensor. I'm using the library from here: https://code.google.com/p/srf04-library/

I'm then using the basic script "Centimeter" that comes in the examples. This gives me a reading, but it seems to be ~20-25% inaccurate. When it reads 100cm, the distance is actually nearer 80cm.

I've replaced the SRF04 with another, and the same issue occurs. Additionally, it seems when it reads out of range (or even on surfaces that give an uneven "bounce"), I get very random figures (e.g. -5cm).

Has anyone experienced something similar?

Just don't use that library, it seems poorly designed.

Here is how the distance for roundtrip is calculated (code excerpts):

long sum = 0;
for (int i=0;i<_average;i++)
{
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    _duration = pulseIn(_echoPin, HIGH);
    sum=sum+_duration;
}
return(int(sum/_average));

If we remove the averaging stuff (as _average is 1 by default), this boils down to:

digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return int(pulseIn(_echoPin, HIGH));

pulseIn normally returns an unsigned long which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor.

If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then pulseIn() should return:

3 x 2 / 340 x 1000000 = 17646 us

So far we don't see any particular problem, that's fine.

Now, if we take a look at the SRF04 datasheet timing diagram, it is mentioned that if no object is detected, an echo of 36ms will be sent by the sensor; in this situation, pulseIn() will return 36000us.

The problem here is that 36000 does not fit into an int (max value = 32767), the conversion to an int will change it into a negative value! That explains your strange negative outputs.

Now regarding accuracy, the library you are using has another issue; here is how the distance in cm is calculated:

int DistanceSRF04::getDistanceCentimeter()
{
        return (getDistanceTime()/29/2);
}

The problem here is the int calculation, it should rather be performed as float. For a speed of sound of 340 m/s, one should divide the time of the echo in us by 29.4 (ie 1000000 / 340 / 100), not 29, that can make a difference in the final calculated distance!

If you want to go on using this library, then just forget about the getDistanceCentimeter()method and replace it with the following code:

distance = (int) (sensor.getDistanceTime() / 29.4 / 2);

All calculation is then performed as float and converted to int distance only at the end.

Your code should also explicitly detect negative values as meaning "no object detected".


Initialising timer interrupt crashes Mega 2560 Below is the entirety of my prototype code, the cycling of pin 13 is what I use to confirm the board is restarting. The board resets continually on this implementation of initialising the interrupt. There is no code implemented for the interrupt, simply initialising the interrupt and specifically enabling the Output Compare Interrupt by setting its bit high is enough to cause the crash. The evidence of the crash is the onboard LED cycling as instructed in the setup() routine.
I have tried setting OCR3A in one and two operations, I have tried initialising TIMSK3 and not, I have tried intialising TCNT3 to zero and non-zero values, and setting the prescaler with the bit shift and the discrete value, nothing seems to work..
What is going on?
void FlashLED() {
  digitalWrite(13, !digitalRead(13));
  delay(100);
  digitalWrite(13, !digitalRead(13));
  delay(100);
  digitalWrite(13, !digitalRead(13));
  delay(100);
  digitalWrite(13, !digitalRead(13));
  delay(100);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  FlashLED();

  // Initialise timer 3 and interrupt
  noInterrupts();
  TCCR3A = 0;
  TCCR3B = 0;
  TIMSK3 = 0;
  TCNT3 = 0;

  // Initialise OCR3A in two operations, as OCR3A = 62500; Serial.print(OCR3A); yields 36 (low byte only)
  unsigned int count = 62500;
  OCR3AH = count >> 8;
  OCR3AL = count;
  TCCR3B |= 1 << WGM32; // CTC Mode
  //TCCR3B |= 4; // Prescaler 256
  TCCR3B |= 1 << CS32; // Prescaler 256

  TIMSK3 |= 1 << OCIE3A; // Output Compare Interrupt Enable
  interrupts();
}

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

}

Update:
I had also been trying with an empty ISR handler and discounted its effect:
ISR(Timer3_COMPA_vect) {

}

However, as the astute viewer would notice, the signature is incorrect in its capitalisation. The correct handler is
ISR(TIMER3_COMPA_vect) {

}

This has resolved the issue.

You have enabled the timer and also its interrupts but you have no interrupt handler. The interrupt has to go somewhere and as it is it's going who-knows-where. Add an ISR and I believe that will resolve your issue.
Yes, the capitalization is important!


I get an error saying, "exit status 1 expected initializer before 'void'." I will be wiring a switch to the Arduino that controls the voltage. When the I turn the switch it can adjust the voltage from 0 to 5. The overall task is to print the output voltage. The print is to be a multiplication table of the voltage.
I created this code:
void setup()

void loop(){

  int (n,i,j,result);

  printf("enter N Value");

  scanf ("%d", &n);

  for (i=1; i<=n; i++);

  {
    for (j=1; j<=n;j++);

    {
      result= (i*j);

      printf("%d", result);

    }
    printf("\n");

  }
  return 0;

}

But i get the error exit status 1
expected initializer before 'void' when I try to verify it. what does it mean. How do you fix it?

Functions must have a body. So instead of:
void setup()

You need:
void setup()
  {
  // do nothing
  }

You have other issues, for example this is not C++:
  int (n,i,j,result);

That should be:
  int n,i,j,result;

Also you are returning 0, when void functions don't return a value.
Also, here:
  printf("enter N Value");

  scanf ("%d", &n);

Where is this value coming from? There isn't a keyboard on the Arduino.
See: scanf

The C library function int scanf(const char *format, ...) reads formatted input from stdin.

The Arduino is a microprocessor. It doesn't have stdin.


sleep mode and watchdog at the same time suppose a project with Arduino that we should save battery power, so we use sleep mode and also avoiding the Arduino of hanging and use watchdog timer. But the problem is here that when the Arduino goes to sleep the watchdog timer never(or cant be) reset again because of sleep and it will overflow over and over and reset the Arduino over and over.
so what do you suggest to solve this problem, I mean running sleep mode and watchdog timer at the same time in a code?

When you sleep the Arduino is locked up. So yes, the watchdog timer will time out and reset the Arduino.

But, since you're in sleep mode, it's not so much a "reboot" as a "wakeup".

The watchdog timer is one of the normal ways of waking up periodically to do things.  If you want to use the watchdog for its other "anti-lockup" purpose then you will have to arrange some other way of waking up before the watchdog is due to expire so you can "kick" it.

Or you disable the watchdog entirely before going to sleep so that the only wakeup source is whatever source you have configured. Then you can turn the watchdog on again when you wake up.

However that probably means that the watchdog is useless, since chances are you won't be awake for long enough periods for the watchdog to have any effect.

Sleeping and using the internal watchdog as a watchdog are pretty much mutually exclusive.  If you sleep, then the watchdog is a periodic wake-up source.


switching power sources I have a small project I am working on that accepts power from either a 5v DC power source or a USB power source.
Now, I know that both of the power sources are effectively 5v. I have measured the power on both with my meter and can see that the USB supply is at 5.4 and the DC supply is at 5.01v.
I would like to be able to build something that switches over to the USB supply when the cable is connected. However, I have never done this before. I have taken a look around on Google already and have read some things about P Channel MosFETs and PowerPath controllers - but I am a little confused as to whether the two incoming voltages I have are suitable for this?
Would someone be able to give me a little advice on this at all?
Cheers,
Rafa

Consider copying the Arduino Uno reference design.  This is part of that schematic showing the MOSFET used to turn on / off the USB power when the barrel jack power source is active:


parse intel hex into SPI commands for arduino ICSP AVR I'm attempting to use the arduino as an ICSP AVR to flash hundreds of ATMEGA's 90USB162.  I'm having some difficulties when trying to do the actual flashing of the chip.  I've go all the wires done properly and I'm able to read the signature.  My source is an Intel hex file and I'm reading it properly as I'm able to see each by as it is read from the arduino's memory.  Where I'm getting lost is the documentation states that I need to set the low byte first before I set the high byte for the same memory address.  Using the following as an example (underscores to break the data up) could someone help me descern what my SPI transaction bytes would look like?

:_20_0000_00_16C100003CC100003AC1000038C1000036C1000034C1000032C1000030C10000_48

I know the colon is the start code, 20 is the hex value of number of data bytes,  0000 is the address, 00 is the record type,  the next 32 bytes is my data followed by the checksum.

I thought that I would loop over the data portion and increment the address every other byte

uint16_t addr = 0;

while (recordtype != endOfFile)
{
  auto data[] = parseData();

  for(uint8_t index = 0; index < 32;)
  {
    SPITask.Send(0x40, 0x00, addr, data[index++]);//send low byte
    SPITask.Send(0x48, 0x00, addr, data[index++]);//send high byte
    SPITask.Send(0x4C, addr, addr, 0x00);//commit new bytes to address
    addr++;
  }
}

I don't think this is right and some examples i'm loosely following comment that they are changing the address byte into a word, which makes some sense based on the command layouts of the data sheet (page 260) 90USB162 Data sheet.  Can anyone please provide some guidance in how to break up this data into high and low bytes.

I have some code that does exactly what you want on GitHub.

Amongst other processors, it supports the At90USB162 chip. The code reads from an SD card in Intel hex format and writes to the chip at the press of a switch. This effectively is what you are trying to do.

Arduino forum moderator "Crossroads" (who has recently also joined Stack Exchange) has made a board to do the programming, hold the SD card, and have some status LEDs:

Here is my code to write to the flash:

// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
//  processor may return a result on the 4th transfer, this is returned.
byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
  {
  noInterrupts ();
  BB_SPITransfer (b1);
  BB_SPITransfer (b2);
  BB_SPITransfer (b3);
  byte b = BB_SPITransfer (b4);
  interrupts ();
  return b;
  } // end of program

// write a byte to the flash memory buffer (ready for committing)
void writeFlash (unsigned long addr, const byte data)
  {
  byte high = (addr & 1) ? 0x08 : 0;  // set if high byte wanted
  addr >>= 1;  // turn into word address
  program (loadProgramMemory | high, 0, lowByte (addr), data);
  } // end of writeFlash

Your loop looks a bit strange, the page size (before you need to commit) is 128 bytes (64 bytes), not 2 bytes.

See the datasheet:


Branchless programing on arduino? So I've been looking into branchless programming to speed up code and I'm curious as to how exactly Arduino (or rather atmega328) actually reads machine instructions. Does it have a memory cache or does it read every instruction from the flash memory?
From my understanding of branchless programming it speeds up the computation because the CPU does not have to jump inside the instructions and can read it sequentially, hence does not need to load in new instructions in case it has to jump to a location that's not loaded.
My question is, does this apply to the atmega328? If it reads every instruction straight from flash without using a cache then it shouldn't matter much if it has to jump in the instructions, right?

There is no cache, so you don't need to worry about that. All instructions are fetched direct from flash and executed straight away.
There is, though, a 2-stage pipeline. That means that in one clock cycle an instruction is fetched from flash, and in the next clock cycle it's executed - and while that is being executed the next instruction is being fetched ready.
That means that when a branch occurs, since the AVR uses a very very simplistic approach to branch prediction (i.e., it assumes the branch will not be taken and just loads the next instruction regardless), it has to discard the contents of the pipeline and start from scratch.
That's only a one clock penalty while it loads the newly-branched-to instruction, but it's still a penalty.
Cache is only needed when the CPU core runs faster than the memory can be accessed. Since the AVR only runs at up to 20MHz that is considerably slower than the flash can be accessed, so adding cache would be completely pointless. Other faster MCUs do use caching, such as the 200MHz PIC32MZ, since otherwise "wait states" would have to be introduced to slow the reading from flash down.


Weird behavior (Couldn't pull the pin LOW) I was trying to implement my own code to control a stepper motor on arduino uno, however I noticed that the pins were always HIGH despite what was written to them. I started to erase the code to leave only the crucial part to troubleshoot it and was left with the following

#define IN1  8
#define IN2  9
#define IN3  10
#define IN4  11
long int *period;

void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
*period=256;
}

void loop() {
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, HIGH);
}

The period statements were leftovers from the previous code, and didn't think of them too much but once I deleted them the code started working. More over, the code worked if the period value was below 256. Once it reached 256 the pins weren't pulling low.

The problem is solved now, however I am interested why would a value of a variable cause such a behavior?

You are creating a pointer variable, not a normal variable.

That pointer variable is, until told otherwise, pointing at address 0x00.  It covers 4 bytes.

Addresses 0x00 to 0x1F are the internal CPU registers R0 to R31.  Your pointer variable points to R0 plus three more addresses above it (a long is 4 bytes in total).

So when you write to your pointer you are directly writing to CPU registers R0, R1, R2 and R3.

According to the AVR-GCC ABI:

R0 is the scratch register
R1 is the zero register
R2 & R3 are general purpose (call-saved) registers.

So if you write 255 to your pointer variable you are doing:

R0 = 255
R1 = 0
R2 = 0
R3 = 0

And that's no big deal: some things may go a little awry, but nothing major.

However, writing 256 results in:

R0 = 0
R1 = 1
R2 = 0
R3 = 0

The big thing here is that the zero register R1 is now 1, not zero.  The ABI states:

  R1 always contains zero. During an insn the content might be destroyed, e.g. by a MUL instruction that uses R0/R1 as implicit output register. If an insn destroys R1, the insn must restore R1 to zero afterwards. This register must be saved in ISR prologues and must then be set to zero because R1 might contain values other than zero. The ISR epilogue restores the value. In inline assembler you can use __zero_reg__ for the zero register.

So R1 must be zero except for a brief moment when you use it for something else.  Since you're setting it to 1 and leaving it as one, any other operations that then rely on that register being zero will have a hard time knowing just what they are doing.

Having a "zero" register is a common thing. There are many times (especially in a RISC architecture) when you want the number zero - and having a register that is guaranteed to always be zero saves a lot of time. For instance, in MIPS the register $0 is hard-wired to be zero and can never change.  AVR doesn't have that luxury, but the GCC compiler imposes the rule for R1 which you have to abide by - since there are huge amounts of library code and other auto-generated code that rely on that register being zero.

So when it's set to one, all gloves are off, and no one can ever really know just what is happening - you'd have to disassemble the code (or get an intermediate listing out of the compiler) to see just what is using R1, and work out what the effect of that being 1 instead of 0 would be.

As an example, digitalWrite has this:

        if (val == LOW) {
 370:   11 11     cpse r17, r1
 372:   05 c0     rjmp .+10          ; 0x37e <digitalWrite+0x50>

That's "COMPARE SKIP IF EQUAL".  It's looking at the value you pass (val) to see if it's equal to zero - by using R1 as the zero value. But if R1 isn't zero then it will never know that what you passed as LOW is LOW - instead it would find HIGH as LOW, since HIGH is 1 and R1 is 1.  So you've basically swapped HIGH and LOW over as far as digitalWrite is concerned.

There are also places where the number 255 is wanted.  This is easy to generate with "eor r1,r1" - exclusive-or of the zero register. EOR turns bits off that are on and on that are off - so zero becomes 255. Except if zero is actually 1, you end up with 254 not 255, and more strange things happen.


Message parsing from MQTT server I'm making a NodeMCU based home automation. I adapted code I found on internet for controlling a device (say LED) via MQTT broker hosted on a Raspberry Pi. It works fine. But when I try to scale it up for more than one device, I'm hitting a wall.
void callback(char* topic, byte* payload, unsigned int length)
{

  const char* t_bedroom_light1 = "/home/bedroom/light1";

  Serial.print("Topic from MQTT broker is : ");
  Serial.print(topic);
  char p = payload[0];

  // if MQTT comes a 0 turn OFF pin D4
  if (topic == "/home/bedroom/light1" && p == '0')
  {
    digitalWrite(LIGHT_PIN, LOW);
    Serial.println(" Turn Light Off! ");
  }

  // if MQTT comes a 1, turn ON pin D4
  if (topic == "/home/bedroom/light1" && p == '1')
  {
    digitalWrite(LIGHT_PIN, HIGH);
    Serial.println(" Turn Light On! " );
  }
}

Serial monitor receives and prints the topic correctly from MQTT server. But topic == "/home/bedroom/light1" never returns true. If I delete that part then p =='0' or p=='1' works fine by itself. I've tried comparing the topic with the locally declared char array, tried converting it into String and doing strcmp. Nothing. What am I doing wrong? Here is the Serial monitor output
12:43:20.346 -> .......
12:43:24.187 -> WiFi connected
12:43:24.187 -> IP address:
12:43:24.187 -> 192.168.1.5
12:43:24.187 -> Attempting MQTT connection...connected
12:43:30.752 -> Topic from MQTT broker is : /home/bedroom/light1

That's not how you compare C strings.
When you write
if (topic == "/home/bedroom/light1")

you're comparing whether the character pointer topic is the same value as the address of the string "/home/bedroom/light1", which of course it is not in this case.
To compare C strings, use the strcmp() function, which returns 0 if they're identical.
if (strcmp(topic, "/home/bedroom/light1") == 0 && p == '0')


Loading local libraries I'm new to Arduino/C development (coming from a JavaScript/Ruby environment), but I was wondering if it was possible to include a library from a custom folder within a sketch?

So this is my situation;

project.ino
libs/
  MyNewLib/
    MyNewLib.h
    MyNewLib.ccp

Now my question is: how can I include my custom library? I've tried several variations on this;

# project.ino

#include <libs/MyNewLib/MyNewLib.h>
#include "libs/MyNewLib/MyNewLib.h"
#include <./libs/MyNewLib/MyNewLib.h>
#include "./libs/MyNewLib/MyNewLib.h"

But none of them works. Can anyone tell me if this is possible? I've looked into this question around the web, but I can't find any satisfying answer. Hopefully you guys can help.

Cheers.

UPDATE

I'm aware you can put your libraries in your global libraries folder, but I want them in my local project folder. I want to share them through git with my team.

Okay, here is how it works, and I checked it to make sure.

Sure you can use hard paths, but every programmer hates using hard paths. They are not portable at all, and they lock your program in place. You use soft or hard links to the files in the project (look up the man pages on "ln"). But,... talk about ugly! So the question is how to do it "correctly"? The key is learning with what parameters and in what path the C/C++ compiler runs.

You will find the conclusion is NOT intuitive at all. Cutting to the chase: relative paths don't work correctly. Now, why?

But first, let me explain why anyone would want to place program files outside the project directory. Programmers like writing program classes, structs, methods, functions, macros, etc., once. As soon as the programmer solidifies the program fragment, he/she wants to put the files in a common tree and move on. Every program thereafter could use that private library. Also, by having the files in a central place, you won't have multiple copies and versions of each. One private library for many private programs.

As of 1.6.13 (Teensy does not yet support 1.8.*), relative includes start from the library, not your directory. It appears that the ano-to-C filter (remember that Arduino does a "conversion" to the target then calls the C/C++ compiler) starts where you installed your Arduino tree. In my case, I installed in "~/bin/arduino". Teensy's home is "./hardware/teensy". The entire home path for the libraries is "~/bin/arduino/hardware/teensy/avr/libraries" where you will find all the support program trees.

In a source file, the '#include "test.hpp"' statement correctly picks the file from your current directory. HOWEVER, if you use '#include "../test.hpp",' the include path does not start in your project directory. Instead it starts in "./libraries"! So the resulting path is:

#include "../test.hpp" ==> ./arduino/hardware/teensy/avr/libraries/test.hpp

In conclusion there is no clean way of making your own tree of tools in  a nearby directory. The only course is to commit your work in the Arduino library and be aware of those rules as well.


How to count the number of rising edges on DS3231 rtc? I am using a DS3231 rtc and I would like to get millisecond accuracy from it so I decided to use the 32kHz generated clock from it. I wrote a code that would count the rising edges or falling edges using an interrupt with (RISING or FALLING parameters) but I get only zeros on my Serial board for the count.

Here is the code I am using :

#include <DS3231.h>
#include <RTClib.h>
#include <Wire.h>
#include "rtc.h"
#define InterruptPin 3

volatile long lcnt = 0;

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  Serial.begin(74880); // init serial port
  pinMode(InterruptPin, INPUT_PULLUP);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
  attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
}
void loop() {
  unsigned long a=millis();
  if (a<1000){
  Serial.println(lcnt);
  }
}

void fcnt(){
  lcnt+=1;
}

I just want to check how many rising edges I have in 1s. What is strange is that this code used to work and now it doesn't ^^'... I don't know if I changed something by mistake or deleted something useful.

Can somebody help me to resolve this little problem ?

Thanks a lot for your time !

I'm not sure why you're getting 0 as such, but your interrupt and variable methodology leaves a lot to be desired (probably the cause of the "tutorials" you followed).

My primary concern is that you are using a 32-bit "long" variable in an interrupt, and referencing that directly outside the interrupt.  The Arduino is an 8-bit system, which means that all accesses to that variable take many instructions to arrange (splitting it down into 4 8-bit values, manipulating it, recombining it, etc).  Because of this no operations on that variable are "atomic".

You need to make them atomic.  If you don't then it's perfectly possible for the interrupt to trigger and modify the value in the middle of you doing something with that value.

The simplest way of making it atomic is to disable interrupts, then copy the value to another variable and/or modify it, and enable interrupts again.

Here's an example that I would consider stable:

#include <DS3231.h>
#include <RTClib.h>
#include <Wire.h>
#include "rtc.h"
#define InterruptPin 3

volatile uint32_t lcnt = 0;

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  Serial.begin(74880); // init serial port
  pinMode(InterruptPin, INPUT_PULLUP);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
  attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
}

void loop() {
  static uint32_t ts = millis();
  uint32_t a = millis();
  if (a - ts >= 1000) {
    ts = a;
    noInterrupts();
    uint32_t currentCount = icnt;
    icnt = 0;
    interrupts();
    Serial.println(currentCount);
  }
}

void fcnt(){
  lcnt+=1;
}

That should print the number of pulses over successive 1 second periods.


Cameras modules for my project I would like to implement a camera to my Arduino project.

So far I have worked with some sensors (e.g. distance), Wifi and Bluetooth modules, buzzer etc. You can find some very good examples on the web on how to use these things on your project, from the wiring to the sketch.

But when we talk about cameras, I feel like things start to be more difficult - I don't know if it's because camera users should know better what they are doing and therefore don't need a step by step guide, if simply there is a lack of information.

I see myself like this guy and this guy. We just can't find a tutorial!

I'm looking forward to buy a VGA OV7670 AL422 FIFO camera or a Serial TTL JPEG with NTSC video, but I don't want to spend my money on something I won't be able to use.

There is any better camera I could buy (by better I mean an easier camera to start working and with some information for the implementation)?

Thank you.

I am currently experimenting with this module: http://www.uctronics.com/mega-pixel-camera-module-mt9d111-jpeg-out-p-227l.html

I2C connection and supplies are working fine with an Arduino Uno, but getting the image data with an Arduino might be not possible.
You can slow down the Pixel Clock of this module to 375kHz, bit I think the  GPIO read-out speed (at least with the standard digitalRead functions) and memory of the Arduino are not sufficient...


ESP8266 CCLOCK Odd behavior I'm trying to write some extremely fast code for the ESP8266, so I'm trying to figure out how to time things.  I've discovered CCLOCK, a register that reflects the number of clock cycles since startup. (https://github.com/esp8266/Arduino/issues/4632#issuecomment-380632906, and other references.) In testing it out, though, I've encountered some weird behavior.  Consider the following code:
static inline volatile uint32_t asm_ccount(void) {
    uint32_t r;
    asm volatile ("rsr %0, ccount" : "=r"(r));
    return r;
}

char outgoingPacket[4];

...

void loop() {

  // ... some stuff ...

  uint32_t startTime = asm_ccount();
  uint32_t stopTime = asm_ccount();
  uint32_t elapsed = stopTime-startTime;

  outgoingPacket[0] = (elapsed >> 24) & 0xff;
  outgoingPacket[1] = (elapsed >> 16) & 0xff;
  outgoingPacket[2] = (elapsed >> 8) & 0xff;
  outgoingPacket[3] = elapsed & 0xff;
  Udp.beginPacket(targetUdpIp, targetUdpPort);
  Udp.write(outgoingPacket, 4);
  Udp.endPacket();
}

(On my computer, I have basically the following Java code running to receive these messages:)
    while (true) {
      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      byte[] data = packet.getData();
      StringBuilder sb1 = new StringBuilder();
      StringBuilder sb2 = new StringBuilder();
      for (int i = 0; i < packet.getLength(); i++) {
        sb1.append(String.format("%8s", Integer.toString(((int) data[i]) & 0xFF, 2)).replace(' ', '0'));
        sb2.append(String.format("%2s", Integer.toString(((int) data[i]) & 0xFF, 16)).replace(' ', '0'));
      }
      System.out.println(sb1 + " " + Integer.parseInt(sb2.toString(), 16));
    }

(Yes, it's a little hacky, I know, but the results have seemed correct.)
Now, most of the time, the output looks like
00000000000000000000000000000001 1
00000000000000000000000000000001 1
00000000000000000000000000000001 1
00000000000000000000000000000001 1
00000000000000000000000000000001 1
00000000000000000000000000000001 1

But about 5 times in 77000, I'll get lines like
00000000000000000000000000000001 1
00000000000000000000000000000001 1
00000000000000000000000110101000 424
00000000000000000000000000000001 1
00000000000000000000000000000001 1
...
00000000000000000000000000000001 1
00000000000000000000000000000001 1
00000000000000000000010010100001 1185
00000000000000000000000000000001 1
00000000000000000000000000000001 1
...
00000000000000000000000000000001 1
00000000000000000000000000000001 1
00000000000000000000010001001100 1100
00000000000000000000000000000001 1
00000000000000000000000000000001 1

I ran the code for 1 minute 4 seconds, and got 3 counts of 424, 1 of 1100, and 1 of 1185.  It seems particularly odd that 424 would show up three times.
Given that, as far as I understand, the relevant lines of code (the two calls to asm_ccount) would have been compiled to a given set of instructions, I'd have expected it to take exactly the same number of cycles every time.
Why is this not happening?
Is it interrupts?  Something something caching?  Does that register not actually work as claimed or as I understand?  Have I done something dumb in the transmission or logging code?  Something else?

You've got interrupts running and interrupting your code. Those take some cycles to run.


Can I cause breaking the main loop from an interrupt? Consider this simple approach to make a light work in 3 different modes: on, off and blink:

attachInterrupt(buttonVector, switchMode, FALLING);

void loop() {
  switch(mode) {
    case 0: turnOff(); break;
    case 1: turnOn(); break;
    case 2: blinkOnce(); break;
  }
}

now if switchMode is something like this:

unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = 0;
void switchMode()
{
  interrupt_time = millis();
  // debounce measures
  if (interrupt_time - last_interrupt_time > 200)
  {
    mode = (mode + 1) % 3;
  }
  last_interrupt_time = interrupt_time;
}

then once the button is pressed, the mode is changed and if we were in the blink mode (mode == 2) we'll wait until the blink is done (let's say that's 2 seconds) and only then the mode is actually switched to the "off" mode. Now, can I stop whatever was in the process of current loop, break it and get the "off" instantly?

PS Of'course there can be some workarounds, like

void switchMode()
{
  interrupt_time = millis();
  // debounce measures
  if (interrupt_time - last_interrupt_time > 200)
  {
    mode = (mode + 1) % 3;
    if(mode == 0)
      turnOff();
    if(mode == 1)
      turnOn();
  }
  last_interrupt_time = interrupt_time;
}

but is there something more elegant and general? (note that if there's 4 modes: on, off, blink, blink_slowly, than this won't work)

It is possible. You could use a setjmp()/longjmp()
combination, or you could just manipulate the stack in assembly right
before returning from the interrupt. This however, makes the program
very difficult to reason about, which can easily lead to introducing
very hard to find bugs. It is certainly not a good solution for your
specific problem.
The straightforward solution to your actual problem is to make your loop
non blocking, and this is achieved with the technique explained in the
Blink without delay Arduino tutorial. Your case is a little bit more
complex, as your LED can be in three modes. I suggest you consider
instead that it can actually be in four modes by saying that, while
it's blinking, the ON and OFF states are different modes:

static enum { OFF, BLINK_OFF, BLINK_ON, ON } mode;

I would let the interrupt handler take care of the button-controlled
mode switching:
void switchMode()
{
    // Debounce.
    static uint32_t last_interrupt_time;
    uint32_t interrupt_time = millis();
    if (interrupt_time - last_interrupt_time < DEBOUNCE_TIME)
        return;
    last_interrupt_time = interrupt_time;

    // Switch modes.
    switch (mode) {
        case OFF:  // OFF -> blink
            digitalWrite(LED_PIN, HIGH);
            mode = BLINK_ON;
            break;
        case BLINK_OFF:  // blink -> ON
        case BLINK_ON:   // ditto
            digitalWrite(LED_PIN, HIGH);
            mode = ON;
            break;
        case ON:  // ON -> OFF
            mode = OFF;
            break;
    }
}

And the loop() only has to deal with the blinking:
void loop()
{
    // This only has to handle the timing of the blinking.
    uint32_t now = millis();
    static uint32_t last_toggle_time;
    switch (mode) {
        case BLINK_OFF:
            if (now - last_toggle_time > TIME_OFF) {
                digitalWrite(LED_PIN, HIGH);
                mode = BLINK_ON;
                last_toggle_time = now;
            }
            break;
        case BLINK_ON:
            if (now - last_toggle_time > TIME_ON) {
                digitalWrite(LED_PIN, LOW);
                mode = BLINK_OFF;
                last_toggle_time = now;
            }
            break;
        default:
            // Nothing to do in the other modes.
            break;
    }
}

Another option is to have the interrupt handler only set a flag to
signal the button press. Then loop() would take care off all mode
changes. This can be a good option if you want the “state machine” (the
control of the mode) contained in a single function.


Arduino Mega 2560 with SIM808 module - Incomplete SMS response I have this code to read a SMS:

String read_SMS(int index)
{
  Serial.println("--START READ SMS POSITION" + String(index) + "--");
  delay(400);
  sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
  delay(2000);
  String tmp;
  tmp = readATcommand("AT+CMGR=1", 4000);
  Serial.println("Content: " + tmp);
  Serial.println("--END READ SMS POSITION" + String(index) + "--");
}

String readATcommand(String ATcommand, unsigned int timeout)
{
  char response[800];
  unsigned long previous;
  memset(response, '\0', 800);    // Initialice the string

  int x = 0;

  GSMSerial.println(ATcommand);
  delay(3000);
  previous = millis();
  do {
    if (GSMSerial.available() > 0) {
      response[x] = GSMSerial.read();
      x++;
    }
  } while ((millis() - previous) < timeout);   // Waits for the asnwer with time out

  return (String) response;
}

// sending AT commands to the Sim808 module
int8_t sendATcommand(String ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0, answer = 0;
  char response[200];
  unsigned long previous;

  memset(response, '\0', 200);    // Initialice the string

  delay(100);

  // Clean the input buffer
  while (GSMSerial.available() > 0 ) GSMSerial.read();

  if (ATcommand[0] != '\0') {
    // Send the AT command
    GSMSerial.println(ATcommand);
    //Serial.print(F("AT Command: "));
    //Serial.println(ATcommand);
  }

  // Waiting for the answer
  x = 0;
  previous = millis();

  do {

    // if there are data in the UART input buffer, reads it and checks for the asnwer
    if (GSMSerial.available() > 0) {

      response[x] = GSMSerial.read();
      x++;
      // check if the desired answer (OK) is in the response of the module
      if (strstr(response, expected_answer) != NULL) {
        answer = 1;
      }
    }

  } while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

  //Serial.println(F("START RESPONSE:"));
  //Serial.println(response);
  //Serial.println(F("END RESPONSE"));
  //if (answer == 0) {
  //  Serial.println("Could not get the expected answer!");
  //}
  //else {
  //  Serial.println("Found expected answer!");
  //}

  return answer;
}

What can be wrong in the readATcommand function as it replies with an incomplete response:

--START READ SMS POSITION1--
Content:
AT+CMGR=1

+CMGR: "REC READ","+407245402XX","","17/06/29,10:
--END READ SMS POSITION1--

But, when I run it from a terminal, the AT+CMGR=1 replies with:

AT+CMGR=1

+CMGR: "REC READ","+40724540234","","17/06/29,10:03:06+12"
Salut

OK

As you can see the message body is not there + the time of the SMS is also incomplete.

Thank you!

Don't delay.

In the three seconds that you wait between sending the AT command and reading the response the entire response has arrived and been placed in the serial RX buffer - which has overflowed because there's more than 64 bytes in the response. So you lose data.

You should never use delay() when reading from serial, it's dangerous (as you see).

Instead you should be just immediately reading until you see the correct response from the command you sent - which will either be "OK" or "ERROR". Everything before that is the content of the response to your command.


Help with NodeMCU based smart switch The project I'm planning is to use a NodeMCU at each electrical board in house to control lights and fans via relays. Each MCU will communicate via MQTT over WiFi to a Raspberry Pi 4 from where I can control all lights and fans in the house. My doubt is:
Can the 3.3V NodeMCU drive a 5V relay like this 1 Channel 5V Relay Module with Optocoupler since I can't find any 3.3 V relays in India. Or must I use a logic level shifter? Or just use an ESP32 board (double price).

The relay I linked to couldn't be operated with 3v3 from the NodeMCU board. I was powering the NodeMCU via a breadboard power supply that had both 3v3 and 5v output (https://www.electronicscomp.com/mb102-breadboard-power-supply-module). I connected the Vcc and GND of relay to 5V supply on that module. the IO pin relay was connected to NoddeMCU. It worked fine and NodeMCU could switch it on and off.