Arduino Watchdog Timer I want to work with interrupts and heard that the watchdog timer is effective way to deal with them.  I haven't been able to find a good tutorial on them though and was wondering if someone could head me in the right direction or give me a couple tips and an example.

Since you talk about the watchdog I presume you want timer interrupts. (There are also I/O interrupts, for instance when the level of a pin changes state.)
Like Russell McMahon says the watchdog is not a good source. The ATmega has several timers (8-bit and 16-bit) which serve your exact purpose. Let's view some example code:

// timer interrupts
// adapted from code by Amanda Ghassaei
// June 2012
// http://www.instructables.com/id/Arduino-Timer-Interrupts/

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
*/

// timer setup for timer0, timer1, and timer2.
// For arduino uno or any board with ATMEL 328/168.. diecimila,
// duemilanove, lilypad, nano, mini...

// this code will enable all three arduino timer interrupts.
// timer0 will interrupt at 2kHz
// timer1 will interrupt at 1Hz
// timer2 will interrupt at 10kHz

// storage variables
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;

void setup() {

  // set pins as outputs
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);

  cli(); // stop interrupts

  // set timer0 interrupt at 2kHz
  TCCR0A = 0; // set entire TCCR2A register to 0
  TCCR0B = 0; // same for TCCR2B
  TCNT0  = 0; // initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124; // = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

  // set timer1 interrupt at 1Hz
  TCCR1A = 0; // set entire TCCR1A register to 0
  TCCR1B = 0; // same for TCCR1B
  TCNT1  = 0; // initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624; // = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

  // set timer2 interrupt at 10kHz
  TCCR2A = 0; // set entire TCCR2A register to 0
  TCCR2B = 0; // same for TCCR2B
  TCNT2  = 0; // initialize counter value to 0
  // set compare match register for 8khz increments
  OCR2A = 199;// = (16*10^6) / (10000*8) - 1 (must be <256)
  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS21 bit for 8 prescaler
  TCCR2B |= (1 << CS21);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

  sei(); // enable interrupts

} // end setup

ISR(TIMER0_COMPA_vect){ // timer0 interrupt 2kHz toggles pin 8
  // generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle0 = HIGH - toggle0;
  digitalWrite(8, toggle0);
}

ISR(TIMER1_COMPA_vect) { // timer1 interrupt 1Hz toggles pin 13 (LED)
  // generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle1 = HIGH - toggle1;
  digitalWrite(13, toggle1);
}

ISR(TIMER2_COMPA_vect) { // timer1 interrupt 10kHz toggles pin 9
  // generates pulse wave of frequency 10kHz/2 = 5kHz (takes two cycles
  // for full wave- toggle high then toggle low)
  toggle2 = HIGH - toggle2;
  digitalWrite(9, toggle2);
}

void loop() {
  // do other things here
}

This sets up 3 different timers: one at 500 µs, one at 1 s, one at 100 µs. For the details about each timer, look up the registers in the datasheet.
With each timer goes a timer interrupt service routine (ISR). These perform the action required when an interrupt occurs. It's a good practice to exit an ISR as quickly as possible. Only do the things which are really time-critical, but for the rest set a flag to indicate that the interrupt occurred. Then in the main loop you continuously check that flag, and when it is set, perform the necessary actions. Don't forget to clear the flag when you're done.


Is there a board that can act as both a USB host and client for HID devices? Trying to build an arduino-based Mouse/Keyboard enhancer.  This will let me do things like press certain keyboard or mouse shortcuts on the input side, then do something custom on the output side.  For instance, this would let me add keyboard shortcuts at the hardware level instead of having to do them at the OS level.

As such, I'm looking for a board which can act both as a USB host (i.e. it can have a keyboard and mouse plugged into it) as well as one that can show up as a USB HID device to the computer it's plugged into.

The boards that I'm aware of which have something close to this are the Leonardo and chip-similar, which work to emulate a keyboard/mouse to the computer they're attached to, but which don't let you connect a keyboard/mouse to them.

So is there such a board?

The TMK USB to USB converter is a thumb drive sized board with ATMega32u4 and max3421e with pass through/remapper software. It has the same functionality as a Leonardo with USB host shield.

https://geekhack.org/index.php?topic=69169.0


How to emulate an analog potentiometer with PWM I have a piece of electronic that controls a motor. It takes power from AC power.

Now there is a 10KOhm Potentiometer. The data sheet of this controller says that the control signal is 10Vcc.

Here's the connections diagram (in Italian):

I'd like to emulate the Potentiometer with Arduino. I'm not sure if PWM will do the job.

Any hints?

Adding to Ricardo's answer:

PWM can do the job, sort of. You need a low pass filter (LPF) to convert the PWM to an analog voltage and an amplifier to take it from 0-5 to 0-10V. Or you can get a dedicated digital-to-analog (DAC) chip but that will obviously be more expensive than a resistor and capacitor for the LPF.

Here's some tutorials on converting your PWM to an analog voltage:

Analog-Output: How-To
Arduino’s AnalogWrite – Converting PWM to a Voltage

Then you need to basically double the voltage. You do that with an operational amplifier. The resistors you pick for the op amp set its "gain", in this case you want it to be 2 so you can go from ~5v (max output) to 10v.

Here's an example of that: My First OP-AMP Circuit


'Var' does not name a type! I don't have much experience in C++ programming. I'm getting this error

'z' does not name a type!!!

which I have't seen in MATLAB or python... What's wrong??? It is so simple!!!

float x=10; float y=50; float z;
z=x*y;

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

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

You cannot put an expression statement outside a function. Only the variable declarations can be placed outside functions (and those variables are called globals/global variables).

Try the following:

float x=10; float y=50; float z;

void setup() {
  // put your setup code here, to run once:
  z=x*y;
}

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

Update

What even is easier and also works (thanks to Ruslan and Juraj):

float x=10; float y=50; float z=x*y;

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

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


How can I run Hello World using Serial Monitor in Tinkercad Arduino simulator? I want to achieve printing Hello World in the serial monitor using Tinkercad to simulate Arduino.
Here is a very simple example code for real Arduino.
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Hello World!");
}

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

}

However, putting an Uno board, typing this code, and clicking "Start Simulation" in Tinkercad doesn't show the Hello World message.
Is it doable? If so how?
For real Arduino, you need to select Arduino serial port and open Serial Monitor. But I can't find such an option for Tinkercad. I can't find Serial Monitor in Thinkercad.
My real purpose is to use Serial Monitor output to test code snippets. Right now I don't have real Arduino board with me, so I thought a simulator would be ideal. If I can easily check the values of variables, it doesn't have to be Serial Monitor.
Sorry if this is not a place to ask questions about simulators.

I mean where would you expect it to print Hello World ... On the Serial Monitor, right? So first open it by clicking on the Serial Monitor button at the bottom of the code tab in Tinkercad.
I tried your code and it works perfectly fine.


Did I kill my ESP8266? So I've been playing with the esp8266 controller lately and today my Usb Host Mini came in that I wanted to connect. So for this I followed the following tutorial https://www.hackster.io/139994/plug-any-usb-device-on-an-esp8266-e0ca8a

The only thing is that I didn't do the following, because I wanted to see that it actually wouldn't work without damaging the Usb Host Mini.

Now I am wondering, because I didn't do that, and just went on with the wiring, did I actually kill my ESP8266 now? Whenever I remove all the wires, and just connect the ESP8266 to my computer, it just won't show up in the ports.

If I did kill it, what did I actually do here? Did I allow 5V to run through the board and did I fry it that way? If I would've actually made the cut shown above, would it have lived? (Because I think what the cut does, is it stops the 5V from going through the circuit.)

Well if it doesn't work then it doesn't work so a safe bet is that chip is damaged.
I found this document. It states:

VBUS pad and jumber can be used to provide 5V to VBUS. By default VBUS is connected to 3.3V; certain USB devices may have issue with
this.

So I deduce that this is connected directly to 3.3V rail of the chip. Providing 5V without opening the jumper (cutting the trace) is the same as putting 5V at the 3.3V pin.

3.3V. Power pin of the shield. Do not supply 5V to this pin - MAX3421E won't be able to detect devices on VBUS and may also be
damaged!

Apparently the "proper" way of doing things is to actually unsolder that jumper or cut the trace.
Sorry.


Sending a string from RPi to Arduino - Working Code I've been researching for 2 days now trying to figure out how to receive a string via I2C on an Arduino. There are plenty of questions online but no real solutions or full tutorials... and sadly I threw my C++ book out years ago.

The code below compiles without error and receives the string correctly. (There are several commented out blocks that I've used to verify the data is being received.) The issue is printing the full received command string. I am unable to make it print in receiveEvent() or in the loop(). Ultimately I need it as a string such as "WIN-23-200" where I will explode the string by "-" to do something but I still can't get a hold of it.

If anyone can give me a nod in the right direction I'd appreciate it.

Thanks!

#include <Wire.h>

#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);

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

}

void loop() {
  delay(1000);
  if (receiveFlag == true) {
    Serial.println("inFlag");
    Serial.println(command);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  //works as expected
  /*while (0 < Wire.available()) { // loop through all
    char c = Wire.read();
    Serial.print(c);
    }*/

  int count = 0;
  while (0 < Wire.available()) { // loop through all
    temp[count] = Wire.read();
    count++;
  }
  //temp[32-1]='\0'; //make sure its 0 terminated, didn't matter
  command = temp; //put char array into a string variable named command

  Serial.print(temp); // prints nothing....

  //Verify Array is Loaded..works great.
  //for (int i = 0; i < count; i++)
  //{
  //  Serial.println(temp[i]);
  //}
  receiveFlag = true;
}

onReceive is intended for use by slaves. master must request data from slave and wait for answer. look at MasterReader example from the Wire library


What sensor would work for soccer ball detection efficiently using Arduino? I want to make a soccer goal counter using Arduino and some sensors. I built using an ultrasonic sensor, but it does not detect if the ball is moving too fast. Are there any other sensors I can use to detect soccer ball?

This is potentially well beyond the capabilities of a simple MCU like an Arduino UNO. So I think it is very important to clearly define the problem you're trying to solve.

Currently, at top national and international level, video cameras are used to detect a ball crossing the goal line. AFAICT, a lot of the complexity comes from having the goal keeper and several players on the line too. It is important that a player kicking across the goal line is not mistaken for the ball crossing the line. Also, it is important that players bodies can't block the view; a simplistic approach might not be able to see the ball if its kicked between a players legs.

This amounts to (probably) millions of sensors (one per pixel) being monitored at 100+ Hz.

So, I'll assume you are not trying to solve such a complex problem. Instead I'll assume you only want to detect a ball crossing the back edge of the goal line, without considering interference by players.

First, let's gather some numbers to describe the core problem.

A soccer ball/football is at least 68cm in circumference, so it is
68/pi = 21.6cm in diameter, or 0.216m, which is 0.108cm radius.

Then there is the goal. FIFA rules say "The distance between the posts is 7.32 m (8 yds) and the distance from the lower edge of the crossbar to the ground is 2.44 m (8 ft)"

So a question is, must the system detect the ball crossing the goal line at any place?

A goal is about 34 times wider than the diameter of the ball, and
just over 11 times taller. So, if the sensors were some form of 'light beam' being broken, the 'simplest' system would need more than 11 sensors looking horizontally from one goal post to the other.

How fast might the ball travel through the posts? This says Cristiano Ronaldo was measured kicking a ball at 130km/hr. That's 36.1m/s.

So the ball is going to take 0.216/36.1 = 0.006 seconds, 6 milliseconds to pass the back edge of the goal line, ie. front edge to back edge will pass a point in 6 milliseconds. This means the sensors must all be scanned, at worst, every 6 milliseconds.

For a sound based system there are more issues.

How much of the ball is 'seen', ie. if only a small fraction of the ball is 'in view' might the returned sound be too small to register with an off-the-shelf ultrasound sensor? For example, if the angle of the reflected sound is too big, ie. from the front or back of the ball, will enough reflected sound return to the sensor to be detected?

Does the ball reflect sound well? It is a membrane at quite a low excess pressure, very different from a solid wall, so I would guess it isn't a perfect sound reflector. I haven't found anything quantifying this, but it seems reasonable to assume off-the-shelf ultrasound sensors might miss the ball under some circumstances.

So it would seem reasonable to assume that two or more sensor readings of the ball would give a significantly more reliable reading than a single sensor reading.

This equates to sampling at least every 3milliseconds. That is a maximum distance of 0.34m * 3/2millisecons (round trip) = 0.5m (approximately).

This might seem to be too much of a restriction. However, the ultrasound sensor only sends a pulse of a few cycles, so it isn't able to detect the ball for the whole of that 3 milliseconds. I haven't found a spec for the off the shelf sensors, but a plausible assumption might be each pulse lasts for about 10 cycles of 40kHz, so the pulse lasts for 0.25 milliseconds. That is the time the ball might travel, about, 1cm. So the angle of reflection would not change much. Hence trying to detect the ball more frequently will increase the quality of at least one signal.

This may explain why the ball is not always detected using ultrasound sensors in your existing approach.

Using any type of sensors to detect the ball, there is a bit of a trade-off. The ball is round, and so if the sensors are almost at the balls diameter apart, then the sensors are going to need to be scanned more quickly to detect a small part of the ball (think of this as a much smaller ball). On the other hand, if the sensors are much closer so at least one gets a longer 'view' of the ball, then one is going to see something closer to the diameter of the ball, hence see it for longer, and so they could be scanned more slowly.

This adds up to a similar outcome. Increase the number of sensors so one sees the ball for a reasonable length of time, or scan the sensors much faster to have a reasonable chance of a measurement.

A 'classic' way to detect something crossing a plane (a door way or in this case the goal mouth) is with a set of laser beams (think Mission Impossible, Entrapment, etc.).

So, consider eye-safe visible-light laser pointers? They must be eye safe, which AFAIK largely implies visible light lasers as eye-safe partly depends on the eyes 'blink response'.

At the width of a goal, the laser will have spread to several cm, but should still be straightforward to detect. With some care, it might be feasible to use mirrors to reflect a beam back towards the goal post carrying the laser, halving the number of lasers, and keeping all of the wiring on one side. I don't know how many reflections might work, but it is worth experimenting as every reflection reduces the number of lasers and sensors.

One advantage of an optical approach vs sound is the goal mouth could easily be monitored at a much higher rate than the ball could possibly pass.

To discriminate between sunlight, stadium or street lights, or other sources of light, the lasers would be modulated. 5kHz is a common figure, this is well away from mains frequency. The signal should be 'low' when the laser is off, and 'high' when the laser is on. If that isn't the case, then their is signal interference, and it isn't going to work.

With a little bit of electronics at the sensors, the signals may be purely digital, so there would be no reliance on the Arduino's slow ADC; the sensors could be scanned with digital GPIO pins, with, say, all 11 sensors being scanned at 10kHz.

You may be able to achieve a similar effect using narrow angle, high-power LEDs, lenses and tubes. A reasonable lens system should be able to focus LEDs over 7.32m of the goal mouth. However, I think eye-safe laser pointers would work with simpler optics, and the mechanics and optical systems are often harder to make robust than the electronics.

Summary:
A 'raster' of eye-safe, visible-light lasers, at approximately 10cm apart, maybe with mirrors to significantly reduce the number of lasers and sensors, directed horizontally across the goal mouth, could detect a ball passing.

However, it would be confused by players across the goal line.


Audio Input into A0? I saw a YouTube Video of someone who used an aux cord input into pin A0 on their Arduino to control a strip of LEDs. I have a strip of Adafruit's RGB NeoPixel LEDs, but I'm not sure how to input my audio into pin A0. If there is a way to do this without a separate shield or board, that'd be great because I'm on a tight budget, but if not possible it'll have to do. Also, would it be possible to send this audio to another Arduino via wifi or bluetooth using a different shield? Thanks.

Depending on how loud your audio signal is, you may be able to do it with just one capacitor and two resistors:

If your signal is quite quiet, though, you may need to amplify it using an op-amp. For instance:

That arrangement would double the volume of the audio. It also has the effect of inverting it, so you will need to invert your readings in software.

Also note that both of these methods will give you an AC waveform centred around 2.5V, so silence will be a reading of around 512, and it will go up and down from there. You can sample that audio waveform and do some basic (though quite slow on an Arduino) analysis of it, such as FFT to get the frequency content of the audio - great for visual effects...


Good button debouncing/stateChange library I need debouncing/stateChange for a push button configuration. Is there a good library for debouncing/stateChange buttons in Arduino (without delay)?

The Button library in the Arduino playground works perfectly.


DC motor kickback diode? I have the following circuit:

And I know it works and that the diode protects the negative voltage from flowing back into the transistor. This is essentially the circuit:

Could someone illustrate what happens when the motor stops? The current normally flows from 5V to GND (and the electrons from GND to 5V, but this doesn't matter (I think?)), and then it reverses when you switch it off, so current comes out of the top of M1, and then what? I don't get it here.

While the motor is being powered the current flows from Vcc to GND as in this circuit:

When the power is disconnected (such as the transistor in the ground connection in your circuit is switched off) amongst other things (including the collapsing of magnetic fields) the spinning of the motor turns it into a generator.  The power generated is the opposite of what was being provided to make it move.  As the magnetic field of the coils collapses additional high voltages are also generated.

When disconnected the motor can be represented as a battery connected backwards.  In that configuration the current flows from the + of this hypothetical battery through the diode into the - thus stopping any current from going elsewhere, as in this circuit:


Arduino IDE - scope of the pre-processor "#define" I'm creating an Arduino library and have 3 files - a "test.ino" program, and two library/class files: "testLibrary.h" and a "testLibrary.cpp".
The library makes use of some hardware-specific resources such as registers and ISRs that depend upon which I/O pin is used, and this should be done at compile time.
I would like to #define a pin number in the main program which, at compile time, is used in the library to determine which code sections are activated. Since this will be a standard Arduino library for use by others, it should compile and run without users having to change their compiler or #include path to make it work.
But it seems that the scope of #define in the main program/sketch does not extend to the library.
test.ino
#define PIN_NUMBER 3
#include "testLibrary.h"
void setup() {}
void loop() {}

testLibrary.h
#ifndef _TESTLIBRARY_h
#define _TESTLIBRARY_h
#ifndef PIN_NUMBER
#error PIN is not defined
#endif
class test {
public:
  test();
  ~test();
};
#endif

testLibrary.cpp
#include "testLibrary.h"
test::test(){}*
test::~test(){}

Compiling the above branches to "#error" using the Arduino IDE 1.8.13 and also using Visual Studio with Visual Micro.
Is there a way for me to have an Arduino library use a "#define" from the main sketch?

The scope of a #DEFINE macro is the translation unit. That is the current .c or .cpp file that is currently being compiled.
In you code PIN_NUMBER is defined in test.ino. The #include macro literaly copies the content of testLibrary.h into test.ino. So for the compiler this is working perfectly fine as PIN_NUMBER is defined.
Your testLibrary.cpp however is not happy with that. Including testLibrary.h for compilation lacks the definition of PIN_NUMBER.
The Arduino IDE is very limited and does not offer you a way to define PIN_NUMBER globally. This is usually done with the compiler argument -DPIN_NUMBER=3. All translation units will get this argument and thus the compilation would succeed. No need to define PIN_NUMBER in code.


IO Control and Configuration I am using Eclipse to program a ATMega2560 and would like to stay away from the Arduino library, While looking through AVR Examples I have seen the syntax

#include <avr/io.h>

PORTD.0 = 1

or

PORTD.DIR = 1;

instead of

PORTD = 0b11111111;

To define and control the Inputs/Outputs when I try to use this syntax I get compiler errors:

error: request for member 'DIR' in '*34u', which is of non-class type 'volatile uint8_t {aka volatile unsigned char}'

I am sure that I am simply missing a include file or something but I can't figure out what I am doing wrong.

What you're doing wrong is that you're using the wrong compiler. That syntax is for CodeVision or mikroC, but the Arduino IDE uses GCC. Which follows global standards rather than making syntax up.


Soldering headers screwed up Trinket? Last week I purchased a couple of Trinkets from Adafruit (5v micro-USB). The first thing I did was solder the headers to one of them. I did the whole setup process w/ the Arduino IDE and didn't have any issues, until I actually tried uploading the "Blink" example.

When I plug in the Trinket, I get the pulsing red light, but when I try to upload during that, I get:

avrdude: error: usbtiny_send: Input/output error (expected 64, got -5)
avrdude: verification error, first mismatch at byte 0x0004
         0x1d != 0x36
avrdude: verification error; content mismatch

avrdude: error: usbtiny_transmit: Input/output error

Then, if I press the reset button, I can't get it to "pulse" again. The red light just dimly turns on and stays constant.

I tested the other Trinket I ordered (that has not been soldered yet) and it works perfectly fine.

So, did I somehow screw up something when soldering the headers? Or do I have a faulty Trinket?

For reference, here's the trinket in question...

There are what appear to be burn or melt marks on the 5 pin component labeled QTSO and on the diode near the USB pin. That could be a sign of damage due to soldering, reverse polarity, or excessive current draw through the voltage regulator (a short circuit).

Based on the fact that the light stays on solid when the reset button is pressed,  it sounds like it could also a different issue. First, turn on verbose output in the arduino IDE and post the full output when you try to upload.

Next, try disconnecting everything except the USB cable while uploading the program. If that does not fix it, it is most likely that the bootloader is corrupted. This has happened to me on multiple occasions for no apparent reason and it is pretty easy to fix.

If repairing the bootloader does not fix this, it is most likely that one or both of the components mentioned above are damaged.


Check contents of buffer after serial read I would like to test the contents of data received over a serial connection. In my loop() I store the data in bffr; and afterwards I would like to test to see if there are some predefined words in it.

#define BFFSZ 90
char bffr[BFFSZ];
char bffridx;

void loop()
{
   readline();

   //- Test the bffr
       if(strstr(bffr, "CLOSED")){ //- WORKS
          Serial.println("> conn. closed");
          digitalWrite(A1, HIGH);
       }else if(strstr(bffr, "RING")){ //- WORKS
          Serial.println("> Someone is ringing");
          digitalWrite(A2, HIGH);
       }else if(strstr(bffr, "0,7,j,BLINK")){ //- Doesn't work
          Serial.println("> Blink");
          digitalWrite(A2, HIGH);
          delay(300);
          digitalWrite(A2, LOW);
       }
}

void readline()
{
   memset(bffr,0,sizeof(bffr));
   char c;
   int i =0;
   bffridx = 0; // start at beginning

   long previousMillis = millis();
   while (1) {
     unsigned long currentMillis = millis();
     if(currentMillis - previousMillis > 20000) {
       Serial.println("TIMEOUT");
       return;
     }
     delay(2);

     c=gsm.SimpleRead2();
     //- debug only, to see if there is something received.
     Serial.write(c);

     if (c == -1)
       continue;
     if (c == '\n')
       continue;
     if ((bffridx == BFFSZ-1) || (c == '\r')) {
       bffr[bffridx] = 0;
       return;
     }

     bffr[bffridx++]= c;
     delay(2);
   }
}

The debug-line makes that I can see the data flowing, eg when I phone the SIM.

But it looks like the buffer isn't tested properly. The first two will work, but the last test fails. It is part of a larger string: $0,7,j,BLINK,567^ But I thought the strstr(1,2) searches for 2 in 1. And as 0,7,j,BLINK, is within the haystack I assume it wil return true. But apparently not...

The gsm.SimpleRead2() comes from GSMlib and is my altered version of gsm.SimpleRead(). Instead of printing the char, I just return it so we can buffer it in the readline function.

void SIMCOM900::SimpleRead()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     Serial.print(datain);
   }
 }
}
char SIMCOM900::SimpleRead2()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     return datain;
   }
 }
}

Does anyone know the answer to this?

After a serial.read();, the data [as far as I can tell] is pretty much destroyed. You have two main options to accomplish this:

Store the data in a string when read and then reference this later. I'd do this with a global variable, that is declared outside of a method and accessible throughout your whole sketch.
I haven't read throughout your whole code, but, if you only need to read one character, you can use serial.peek();. This only works if you need the first character of the buffer.

Most likely, your only option would be the first bullet. I'd implement this by adding a method something like this:

String buffer_string_serial;

void setup() { //code here }

void loop() { //code here }

int serial_read_buffer() {
  while(serial.avaliable() > 0) {
    buffer_string_serial = buffer_string_serial + serial.peek();
    return serial.read();
  }
}

Then, just use serial_read_buffer();. That will act similar to serial.read();. The only difference is it will fill up the buffer_string_serial string. You'll have to clear that out after you used all the data so it doesn't get full.


Arduino digital pin reading string numbers Using for example 433MHz RF Receiver modules, they are connected to a digital input pin with interrupt. Looking at the most basic meaning of digital readings (e.g. 1/0, on/off, HIGH/LOW), how does the Arduino convert the signal readings to a number/string?

From my limited understanding, I'm assuming it has something to do with the (external) libraries, or it might just be that my understanding about digital readings are too limited.

From the official Arduino site, See DigitalWrite :

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

The exact definitions can be found here for reading a signal: Constants

When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW.

HIGH

The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report HIGH if:

-a voltage greater than 3.0V is present at the pin (5V boards);
-a voltage greater than 2.0V is present at the pin (3.3V boards);

A pin may also be configured as an INPUT with pinMode(), and subsequently made HIGH with digitalWrite(). This will enable the internal 20K pullup resistors, which will pull up the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This is how INPUT_PULLUP works and is described below in more detail.

When a pin is configured to OUTPUT with pinMode(), and set to HIGH with digitalWrite(), the pin is at:
-5 volts (5V boards);
-3.3 volts (3.3V boards);

In this state it can source current, e.g. light an LED that is connected through a series resistor to ground.

LOW

The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report LOW if:

-a voltage less than 1.5V is present at the pin (5V boards);

-a voltage less than 1.0V (Approx) is present at the pin (3.3V boards);

When a pin is configured to OUTPUT with pinMode(), and set to LOW with digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts).

Probably, HIGH is 1, LOW is 0, and ON is 1, OFF is 0.
Than 1 is mapped to 5V or 3.3V depending on the Arduino and 0 is mapped to 0V.
These mappings and the definitions of HIGH/LOW/ON/OFF are in the Arduino libraries.


Breaking out of a while loop using IR remote for neopixel I've been piecing together various lighting effects. I am wanting to have each lighting effect loop until another button is pressed to trigger another lighting effect.

I've come to a bit of standstill at the moment. I've created a loop that doesn't seem to end. I've had a look around but I can't work out how to fix my code. Sorry in advanced, I'm new to using arduinos but if anyone could help out, it would be much appreciated.
Thanks!

//www.elegoo.com
//2016.12.9

#include "IRremote.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(20, PIN, NEO_GRB + NEO_KHZ800);

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
int Remote = 0;

/*-----( Function )-----*/
void translateIR() // takes action based on IR code received

// describing Remote IR codes

{

  switch(results.value)

  {
  case 0xFFA25D: Serial.println("POWER");
  ArrowRight(strip.Color(25, 0, 0), 100); //Red
  ArrowRight(strip.Color(0, 0, 25), 100); //Blue
//  Remote = 0xFFA25D;
  break;

  case 0xFFE21D: Serial.println("FUNC/STOP");
  ArrowLeft(strip.Color(25, 0, 0), 100); // Red
  ArrowLeft(strip.Color(0, 0, 25), 100); // Blue
//  Remote = 0xFFE21D;
  break;

  case 0xFF629D: Serial.println("VOL+"); break;
  case 0xFF22DD: Serial.println("FAST BACK");    break;
  case 0xFF02FD: Serial.println("PAUSE");    break;
  case 0xFFC23D: Serial.println("FAST FORWARD");   break;
  case 0xFFE01F: Serial.println("DOWN");    break;
  case 0xFFA857: Serial.println("VOL-");    break;
  case 0xFF906F: Serial.println("UP");    break;
  case 0xFF9867: Serial.println("EQ");    break;
  case 0xFFB04F: Serial.println("ST/REPT");    break;
  case 0xFF6897: Serial.println("0");    break;
  case 0xFF30CF: Serial.println("1");    break;
  case 0xFF18E7: Serial.println("2");    break;
  case 0xFF7A85: Serial.println("3");    break;
  case 0xFF10EF: Serial.println("4");    break;
  case 0xFF38C7: Serial.println("5");    break;
  case 0xFF5AA5: Serial.println("6");    break;
  case 0xFF42BD: Serial.println("7");    break;
  case 0xFF4AB5: Serial.println("8");    break;
  case 0xFF52AD: Serial.println("9");    break;
  case 0xFFFFFFFF: Serial.println(" REPEAT");break;

  default:
    Serial.println(" other button   ");

  }// End Case

  delay(0); // Do not get immediate repeat

} //END translateIR
void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  strip.begin();
  strip.show();
  Remote = 0;

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}/* --(end main loop )-- */

void ArrowRight(uint32_t c, uint8_t wait) {
  while (Remote = 0xFFA25D) {
    for (uint16_t i = strip.numPixels()/2; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
    }
    for (uint16_t i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(wait);
  }
}

void ArrowLeft(uint32_t c, uint8_t wait) {
  while (Remote = 0xFFE21D) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2-1; i + 1 > 0 ; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
    }
    for (uint16_t i = strip.numPixels(); i + 1 > 0 ; i--) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(wait);
  }
}

There are a few causes for eternal loops and other things that will go wrong in your code.

As ChrisL noted above you are assigning a value to Remote in the while condition which is almost certainly not what you wanted to do.  On the plus side, every C/C++ programmer ever has also made that same mistake at some time or another.

Now if you change it to while (Remote == 0xcFFE21D) it still won't work, because Remote is always 0.  You have commented out the lines that set Remote, but they are after the call to the function.  To be honest since you know the value before you call the function (because of the switch statement) you don't need to check the value within the function so you could remove the while loop all together.  If you intention is to call this function repeatedly until a different button is pressed on the remote, the way you are doing it won't work.  you need to store the last button pressed value and then pass that into the switch statement.  When a different button is pressed update the 'last button pressed' value.

You for loop conditions need looking at.  I don't think that the number of lights in the strip is going to change while the program is running.  If that's true then your are wasting processor instructions by doing strip.numPixels()/2-1 you might want to look at setting global values in setup.

Also the for loops might benefit from using i >= 0 because then you don't need to do i+1 every loop.


Good books to learn more about microcontrollers / electrical engineering? I've bought the Arduino starter kit with the project book and I'm about half way through and addicted.

As I go through the projects I wish they would go into more detail on the electrical components, and other things such as Ohms law.

The question here is do you have any suggestions for books to read for the purpose of gaining a better understanding of microcontroller programming/engineering, from a beginners perspective?

Ideally I would like a book that can be read cover to cover in my spare time (more abstract concepts, instead of problem&answer type books).

The newly updated 3rd Edition of "The Art of Electronics" by Horowitz and Hill is a great text/reference, worth every penny of its $80 price. It has a very practical approach and requires only high school math. I have been working with electronics for longer than I would care to admit and it teaches the subject the way I would like to have been taught.


KY-040 rotary encoder skipping steps Yesterday I asked a question about de-bouncing this rotary encoder and Jsotola suggested that I should use a method like This to detect the previous state and then do the counting. using that method each turn is counting twice in one turn so I came up with my version of de-bouncing the rotary encoder:

int s1, s2;
int count = 0;
boolean right = 0;
boolean left = 0;
int rotary = 0;
unsigned long timer = 0;
unsigned int bounce = 50;

void setup() {
  Serial.begin(9600);
  pinMode(6, INPUT);
  pinMode(7, INPUT);

}

void loop() {

  s1 = digitalRead(6);
  s2 = digitalRead(7);
  if (s1 == 1 && s2 == 1) {
    right = 0;
    left = 0;
    rotary = 0;
  }
  if (s1 == 0 && s2 == 1) {
    left = 1;
  }
  if (left == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 2;
  }
  if (s1 == 1 && s2 == 0) {
    right = 1;
  }
  if (right == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 1;
  }

  if (rotary == 1) {
    if ((millis() - timer) > bounce) {
      count++;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  if (rotary == 2) {
    if ((millis() - timer) > bounce) {
      count--;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  Serial.print(s1);
  Serial.print(s2);
  Serial.print(", ");
  Serial.print(count);
  Serial.println(" ");
  delay(15);
}

The code is working just fine. When turning the rotary this are the steps that I get:

10-00-01 < (11) > 10-00-01

problem is if I turn the knob quickly rotary encoder will skip one or two steps like: 01-01-01 < (11) or 10-00-00 < (11).

This problem exist in all methods/libraries (I tested them all), is there anyway to fix this with software/hardware or this rotary encoder is just junk and I should get a better one?

Another method of de-bouncing as Jsotola requested:

 int pinA = 3;  // Connected to CLK on KY-040
 int pinB = 4;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.print ("Rotated: ");
     if (bCW){
       Serial.println ("clockwise");
     }else{
       Serial.println("counterclockwise");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

I applaud you for your tenacity with the "debouncing" idea, but there is an excellent library for this rotary encoder, and the author has also written an article about it: Ben Buxton - rotary encoders done properly. Here is a link to his library: GitHub - buxtronix.

I’ve used an older version of the library before with interrupts, and it worked perfectly for my application. I see the author has updated the library and has 2 example sketches; one uses interrupts, and the other uses polling. I tried both of them today on an Uno and I was very impressed with the polling sketch’s performance. It seemed to equal that of the interrupt method.

If you take the important bits out of the library files, then add them to a sketch, you can see how little code it takes for this "method" of processing the encoder’s output. Here is a test sketch with the library bits in it.

#define R_START 0x0
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
#define DIR_NONE 0x0
#define DIR_CW 0x10
#define DIR_CCW 0x20

const byte pin1 = 5;  // DT
const byte pin2 = 6;  // CLK
int state = R_START;
int counter = 0;

const unsigned char ttable[7][4] = {
  // R_START
  {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
  // R_CW_FINAL
  {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
  // R_CW_BEGIN
  {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
  // R_CW_NEXT
  {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
  // R_CCW_BEGIN
  {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
  // R_CCW_FINAL
  {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
  // R_CCW_NEXT
  {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 0x30;
}

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){
  unsigned char result = process();
  if(result == DIR_CW){
    counter++;
    Serial.println(counter);
  }
  else if(result == DIR_CCW){
    counter--;
    Serial.println(counter);
  }
}

Heres a simplified sketch (It works the same but I didn't like the hex numbers and I don't use define):

const byte pin1 = 5;  // Connected to DT on KY-040
const byte pin2 = 6;  // Connected to CLK on KY-040
int state = 0;
int counter = 0;

const unsigned char ttable[7][4] = {
  {0, 2, 4, 0},
  {3, 0, 1, 0 | 16},
  {3, 2, 0, 0},
  {3, 2, 1, 0},
  {6, 0, 4, 0},
  {6, 5, 0, 0 | 32},
  {6, 5, 4, 0},
};

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){

  unsigned char result = process();

  // Clockwise rotation.
  if(result == 16){
    counter++;
    Serial.println(counter);
  }

  // Counter clockwise rotation.
  else if(result == 32){
    counter--;
    Serial.println(counter);
  }

}

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 48;
}


Using L298N bridge to control smart lock I want to use L298N bridge to power up and control simple smart lock. It requires 12V power supply, so I've used L298N bridge to power this smart lock.

I removed jumper from enA pin and connected enA 12V to Arduino Nano D8 pin.

I sent value 255 through this pin but smart lock did nothing. Any suggestions?

I'm using BLE controller to send turn on/off signal from Android App (but its not relevant in this case, because analogWrite is called).

Lock:
https://www.aliexpress.com/item/32949292074.html

Here is code:

#define enA 8

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

void loop() {
 String msg = bluetooth.read(); //using BLE controller to get message from Android app.

 if(msg == "ON"){
   analogWrite(enA, 255);
 } else if(msg == "OFF"){
   analogWrite(enA, 0);
 }

}

Here is setup:

You really don't want an L239D to control that lock. It's overkill.  The L239D is a H-bridge that is designed to drive loads in two different polarities (forward / backwards on a motor for example).

That lock is merely a spring-loaded solenoid. You give it power and it pulls the lock back. You remove power and the spring closes it again.

All you need is a simple transistor circuit just like you'd use for a relay.

Since you insist on using an L239D, here's a schematic for you:

simulate this circuit – Schematic created using CircuitLab


How to debug an Arduino sketch on a Mac? I have 2 Lowpowerlab WaterMote's talking to each other using the 'out of the box' pre-installed sketch that just confirm they're talking to each other. I verified this by opening a COM connection and saw traffic of 'receiving packets...' That was just to show that they are functioning and talking to each other.

Now, using Arduino IDE on Mac OS X 1.9.x (Lion?) I have loaded the WaterMote sketch (found on Github) on the Moteino with the sensor (not the gateway) as it should be. The traffic looks like it's working, except the text being transmitted (number of Gallons) stays the same at 0.02 Gallons.

So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

My current setup

Moteino Gateway (as out of the box) connected to a Raspberry Pi (with ssh enabled)

Connected via USB to the RasPi

Moteino with WaterMote sketch loaded

Connected via USB to the MacBook Pro
Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
I do not know what to make of this since that text is not in the WaterMote sketch.

Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

I found a debugging article:

Visual Micro

So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

It's definitely possible to debug a sketch with OS X. But it's definitely an advanced AVR topic, and if you're not experienced enough with embedded programming you should first try to avoid it, except if it is really necessary.

Debugging a sketch for an ATmega328 implies:

Running a flasher such as the AVR Dragon, the JTAG ICE 3, the STK500 or the AVR ONE; no cheap flasher implements the DebugWire protocol;
Setting up the debug fuse, which is an operation that can brick your MCU.

If you're using an ATmega32U4 (or alike), you won't be able to do it out of the box, as the 32U4 needs a JTAG connection for on-chip debugging.

Finally, once you got through that, you can bind a gdb to the AVR using AVaRICE. I'm not getting you through all that, because I really, really, strongly advise you not to do it until you're experienced enough to know what you're doing.

  Moteino with WaterMote sketch loaded
         connected via USB to the MacBook Pro
         Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
         I do not know what to make of this since that text is not in the WaterMote sketch.
  Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

It is very likely you did not setup the correct baudrate for the serial outputs. Arduino IDE defaults to 9600 bits/s connections, whereas the WaterMote source code defines a 115,200 bits/s connection. When you open the Serial Monitor change the setting at the right of the status bar.

And finally, be sure to uncomment the #define SERIAL_EN line to enable the serial communication and debug outputs.


Load Arduino flash code from SD card I have an Arduino Uno. It doesn't have a lot of memory space, which is a bit of a nuisance. I was wondering:  Is it possible to load a text file from an SD card and compile it on the Arduino into code that the Arduino can use. I don't really care if it is slow or uses 99% of the memory space just to load on the code. If it is possible would this work: use bootup code to load a piece of code to Arduino, dispose of bootup code so there is more code, do what ever that code does, dispose of that code, load new code.

See topic #16812, “Load sketch code from SD Card”, in forum.arduino.cc, which explains how to replace the ordinary Arduino bootloader with one that can load programs from an SD card.

Also see Bootdrive loads Arduino sketches from SD card at dangerousprototypes.com, which gives different code to do the same thing.  It also mentions BootDrive for Arduino from baldwisdom.com.

Note, the program code that these loaders install into flash is already compiled, as opposed to being original C source code.  If you want to load source-level code into the Arduino, look for an interpreter / interpretive language to run on the Arduino.


How to recover an I2C bus when SDA is stuck low? Edit: SDA line stuck high See edit at the end of the message.

I have an Arduino in master mode connected via I2c to a slave, with 2k pull-up resistors on SDA and SCL. Sometimes the SDA line is stuck low, which causes my program to hang indefinitely.

How to recover from such a scenario?

Edit1: Since the SDA line is tied low the problem probably comes from the master. My guess is that the slave waits for the rest of the clock pulses that never come.

I'm not using the Wire library. I wrote my own implementation based on the AMmega328P datasheet.

void TWIInit() {
  TWSR = 0x00;
  TWBR = 0x48; // SCL = 100khz
  TWCR = (1 << TWEN);
}

void TWIStart() {
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
}

void TWIStop() {
  TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
  while (TWCR & (1 << TWSTO));
}

void TWIWrite(uint8_t data) {
  TWDR = uint8_data;
  TWCR = (1 << TWINT) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
}
unsigned int TWIReadACK() {
  TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
  while ((TWCR & (1 << TWINT)) == 0);
  return TWDR;
}

unsigned int TWIReadNACK() {
  TWCR = (1 << TWINT) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
  return TWDR;
}

unsigned int TWIGetStatus() {
  unsigned int statusOfRegister;
  statusOfRegister = TWSR & 0xF8;
  return statusOfRegister;
}

int TWISendBytes(uint8_t slaveAddr, uint8_t regAddr, uint8_t buf[], int numbBytes) {
  TWIStart();
  if (TWIGetStatus() != 0x08) {
    TWIStop();
    return 1;
  }
  // send address and Write bit
  TWIWrite(slaveAddr & 0xFE);
  if (TWIGetStatus() != 0x18) {
    TWIStop();
    return 1;
  }
  // send the register address
  TWIWrite(regAddr);
  if (TWIGetStatus() != 0x28) {
    TWIStop();
    return 1;
  }
  // send bytes
  for (int i = 0; i < numbBytes; i++) {
    TWIWrite(buf[i]);
    if (TWIGetStatus() != 0x28) {
      TWIStop();
      return 1;
    }
  }
  TWIStop();
  return 0;
}

int TWIGetBytes(uint8_t slaveAddr, uint8_t regAddr, uint8_t buf[], int numbBytes) {
  TWIStart();
  if (TWIGetStatus() != 0x08) {
    TWIStop();
    return 1;
  }
  // send address and Write bit
  TWIWrite(slaveAddr & 0xFE);
  if (TWIGetStatus() != 0x18) {
    TWIStop();
    return 1;
  }
  // send the register address
  TWIWrite(regAddr);
  if (TWIGetStatus() != 0x28) {
    TWIStop();
    return 1;
  }
  // repeated start
  TWIStart();
  if (TWIGetStatus() != 0x10) {
    TWIStop();
    return 1;
  }
  // send address and Read bit
  TWIWrite(slaveAddr | 0x01);
  if (TWIGetStatus() != 0x40) {
    TWIStop();
    return 1;
  }
  // get bytes
  for (int i = 0; i < numbBytes; i++) {
    if (i == (numbBytes - 1)) {
      buf[i] = TWIReadNACK();
      if (TWIGetStatus() != 0x58) {
        TWIStop();
        return 1;
      }
    } else {
      buf[i] = TWIReadACK();
      if (TWIGetStatus() != 0x50) {
        TWIStop();
        return 1;
      }
    }
  }
  TWIStop();
  return 0;
}

Edit2: The SDA line, and SCL, is held high not low as I first incorrectly assumed (I probably did something wrong when I measured it and thought it was low but anyway.) The problem was that the resistors I was using as pull-up resistors were in fact 1k not 2k. I changed them for 2k resistors and the problem disappeared.

I solved the problem by replacing the pull-up resistors with 2k Ohm resistors. I thought I connected 2k Ohm resistors when in fact their value was 1k. So sometimes the SDA line couldn't be driven low due to the too strong pull-up resistors and that caused the hanging.


Protect the Arduino make with Unique Id I’d like to protect my arduino make with a unique serial number for every device I make.
What are the proper ways to do it? Probably there are kind of best practices…
Keep it in EEPROM is obviously a bad idea.

I believe that there is some chip that can be added to the circuitry.

The general idea is the following.
Circuitry has a hardware which gives a unique id (serial number). Distributor/seller generates the signature using unique id and put it to the eeprom. Arduino program verifies this signature using hardware serial number. Arduino program is distributed in binary or within the device.

I still suggest using the eeprom.
It is the firmware's job to handle whether or not data in eeprom can be written.
You could implement wrapper functions for the arduino which can only read/write after a defined offset. You can set this read-only data with the .eep-file when you upload your sketch. The eeprom file then may be generated programmatically.

Once you have to flash several individual devices with a final firmware version, there are no benefits in using the arduino ide. You can upload the firmware and the eeprom file using avrdude:

avrdude -P YOUR_PORT -b 115200 -p ATmega328P -e -U flash:w:YOUR_FIRMWARE.hex -U eeprom:w:YOUR_EEPROM.eep

It's up to you how to generate the eeprom file (bash/batch, make, pyhton,...).


HTTP post via GPRS (SIM808) to Azure http endpoint logic app is failing I am using a SIM808 with a atmega2560.

I have setup the endpoint in Azure and that works when I try a http post via postman and/or an online http post tool (I get a 202 as result and see data comming into Azure)

I want to send a json package to an Azure http endpoint (smart app) using the function httpPOST in the SIMCom library from itead.

I am connecting to the network:

logging (I printed all that is written to GSM):

AT+CIFSR
DB:STARTING NEW CONNECTION
AT+CIPSHUT
DB:SHUTTED OK
AT+CSTT="provider.net","","" DB:APN OK
AT+CIICR
DB:CONNECTION OK
AT+CIFSR
DB:ASSIGNED AN IP
GPRS status=ATTACHED
AT+CIPSTART="TCP","prod-13.westeurope.logic.azure.com",443
DB:RECVD CMD
DB:OK TCP

Then call the httpPost function from the library with the following variables:

const char server[35] = "prod-13.westeurope.logic.azure.com";
const int port = 443;
const char path[200] = "/workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken";
const char parameters[100] = "{\"device\":\"alive\",\"timestamp\":\"09270845\"}";

Part of the httpPost function from the library for sending the data

    int InetGSM::httpPOST(const char* server, int port, const char* path, const char* parameters, char* result, int resultlength)
         ....
    gsm.SimpleWrite("POST ");
    gsm.SimpleWrite(path);
    gsm.SimpleWrite(" HTTP/1.1\r\nHost: ");
    gsm.SimpleWrite(server);
    gsm.SimpleWrite("\r\n");
    gsm.SimpleWrite("User-Agent: Arduino\r\n");
    gsm.SimpleWrite("Content-Type: application/json\r\n");
    gsm.SimpleWrite("Content-Length: ");
    itoa(strlen(parameters),itoaBuffer,10);
    gsm.SimpleWrite(itoaBuffer);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(parameters);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(end_c);
....

Which gives this output on the serial monitor (I printed all that is written to GSM):

AT+CIPSEND
DB:>
POST /workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken HTTP/1.1
Host: prod-13.westeurope.logic.azure.com
User-Agent: Arduino
Content-Type: application/json
Content-Length: 55

{"device":"alive","timestamp":"09270845"}

DB:SENT

And then it is waiting for a response:

Starting read..
Waiting for Data............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
CLOSED

Done..
response:
10

CLOSED

which times out I guess.

And I see nothing coming into Azure.

(I am getting data when I try a httpGet on a random site. So hardware, sim and network is working ok I guess)

Any ideas?
thx!

Juraj's comments put me on the right track, for SSL you need to do more then just select the port.

I did some searching and got it to work using a different GSM library that also supports SSL:
tinyGSM

in combination with ArduinoHttpClient

Jeroen

EDIT: It works, but there is a big downside. It looks like there is major overhead, each message seems to uses 13Kb of data...? I suspect this comes from the data that is returned by the endpoint.
This is way too much over GPRS so now looking into MQTT.


help with arduino programming my project involves:
1 ultrasonic sensor.
1 servo motor.
3 leds.
when a person comes in range of ultrasonic sensor (7 to 20),servo turns by 150 degree.
then ultrasonic sensor check again if the person is in range, if yes then led1 turns on for 10sec n turns off, still if the person in in range then led2 turns on for 10sec and turns off, still if the person is in range then led3 turns on for 10sec and this keep on repeating for the leds(led1, led2, led3 but servo is still in 150)
once detected and the person is not detected the leds should not glow and servo should return to 0

code:

if ((distance1>7)&&(distance1 <= 20))
 {
  myservo1.write(150);
  delay(1000);
 }
 {
  if ((distance2>7)&&(distance2 <= 20))
   {
   digitalWrite(led1,HIGH);
   delay(1000);
   digitalWrite(led1,LOW);
   }
  if ((distance1>7)&&(distance1 <= 20))
   {
   digitalWrite(led2,HIGH);
   delay(1000);
   digitalWrite(led2,LOW);
   }
   if ((distance1>7)&&(distance1 <= 20))
   {
   digitalWrite(led3,HIGH);
   delay(1000);
   digitalWrite(led3,LOW);
   }
else
{
 myservo1.write(0);
  }

but this code does not work the way i want.
it blink the leds even when there is no person in range.
need help in programing so that the leds blink only when ultrasonic detects the person in range and stops when person is not detected.
thank u in advance

Your indenting doesn't match your code.

Right after the very first if (without an else), you have a new open brace ({). This looks wrong:

if ((distance1>7)&&(distance1 <= 20))
 {
  myservo1.write(150);
  delay(1000);
 }
 { // <<<< What is this?

The very very final else matches the very very final if - certainly not the first if!

Also, what is the difference between distance1 and distance2? You only have one ultrasonic sensor - there is only one distance!

EDIT:

I think what you need to do is use loop() more effectively. At the moment, you're pausing in the middle of your code, rather than letting the rest of the code work and using millis(). That function returns the number of milliseconds since the program started - which you can use for your problem (with a little mathematics):

EDIT 2:

I've added a little extra code to play different tunes depending on the current state. It uses the library at http://www.rhydolabz.com/other-widgets-c-205_124/mini-mp3-player-module-p-2159.html

static unsigned lastMilli = 0;
static byte lastLED = 0;
static const byte LEDs[] = { led1, led2, led3 };

distance1 = // Whatever you call to get the distance...
if (distance1>7) && (distance1<=20)) { // Too close?
   if (lastMilli==0) {       // Is this new???
       lastMilli = millis(); // Yes! Record that...
       mysero.write(150);    // ...and set servo.
   } // if
   unsigned delay = millis() - lastMilli; // Get how long it's been
   byte which = delay / 10000 % 3;        // Which LED / tune?
   byte LED = LEDs[which];                // Which LED?
   if (LED != lastLED) {                  // Has LED changed?
       if (lastLED!=0) {
           digitalWrite(lastLED, LOW);    // Yes! Stop that one
       } // if
       mp3_single_loop(true);             // Play forever!
       mp3_single_play(which+1);          // Play "mp3/000#.mp3"
       lastLED = LED;
       digitalWrite(LED, HIGH);           // And start the new one
   } // if
} // if
else if (lastMillis!=0) { // They're gone!
    digitalWrite(lastLED, LOW); // No LED
    myservo.write(0);           // No servo
    lastMilli = 0;              // So start again
    lastLED = 0;
    mp3_stop();
} // else


Problem on color mixing lamp on Proteus Arduino starter kit I set the circuit and couldn't illuminate, where is the problem?

Fritzing: https://fritzing.org/media/fritzing-repo/projects/c/color-mixing-lamp/images/Arduino%20Lamp%20Project.png

just fixed by using TORCH LDR instead of normal LDR. FULLY WORKS.


Possible error in CAN-Bus shield schematic? This is a part of SeeedStudio CAN-Bus shield schematic. The vertical green line on the left seems suspicious to me. Am I missing something?

No, it's not a mistake. It's related to this statement on their Wiki:

  When you use more than two CAN Bus Shield in one net, you should take the impedance into consideration. You should either cut P1 in the PCB with a knife, or just remove R3 on the PCB.

If you look closely at the pads of P1 you will see a small trace joining them together. That is the "rogue" green line you found. By cutting that trace you disconnect the termination resistor. You can then re-connect the termination resistor by soldering the pads together again.


Digital Pin won't ground when set to LOW My friend and I are repurposing an old rc car for a project. When we connect the dc motors to 5V and ground, the motors spin. However, when we power the motors from 5v and ground it in the digital output pin set to LOW, nothing happens. The identical circuit works in tinkercad. We are using a nano, but have tried an uno and mega as well.

Never directly connect a motor to an Arduino IO pin
You will destroy the Arduino.
An Arduino cannot source (or sink in your case) enough current to drive a motor, and if the motor did manage to turn the huge amounts of EMI it generates would literally blast holes in the silicon inside the chip.
You must use a motor driver of some form. If you only want one direction that driver can be a single NPN Bipolar transistor or N-channel MOSFET.  If you need it to change direction then an H-bridge is what you want.


Analog reading with noise - Arduino Uno VS ESP12e I was testing analog output from a microphone (Max9814) with an Arduino Uno, which came with nice results. The output provided by the microphone is converted into sound and is loud and clear.

Setup: (Max to Uno)

Pin Vdd to 3,3V
Pin GND to GND
Pin Out to A0

However when I tried to set it up with an ESP12e instead of an Uno, I got a lot of 'noise' and no clear sound at all.

Here I used the following setup: (Max to ESP)

Pin Vdd to VCC (VCC is measured at 3.3v with a multimeter)
Pin GND to GND
Pin Out to AD0

A little 'side step'

The problem arised that the analog output from the microphone delivered a voltage of around 1.24, while the ESP12e analog has 1v as max input. This made the analogRead max out all the time. For this reason I put a 10k OHM resistor between the OUT and AD0 combined with a 20k OHM resistor between gnd and AD0. This resulted into nice analog readings (instead of 1024, around 400-500 all the time).

However, like mentioned before, a lot of noise is in between and the sound is not clear. (I also tried to work with 'sample windows', here is the 'filtering mechanism' which can be found on many sites/questions and works perfectly fine):

//(global logic is set to take n samples and than print the line)
//Tried n of 5 to 20
//Also instead of just samples tried the micros variant instead of just samples which is also found on many sites to create a time window to record.
unsigned int sample = analogRead(A0);
if (sample < 1024) {  // toss out spurious readings
  if (sample > signalMax) {
    signalMax = sample;  // save just the max levels
  } else if(sample < signalMin) {
    signalMin = sample;  // save just the min levels
  }
}

unsigned int peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
Serial.println(peakToPeak);

Does somebody have a clue why the Arduino gives such clear and good sound, while the ESP12e does not. (The analog values do not 'seem' to differ much in the levels)

The ESP8266 is an incredibly (electrically) noisy environment.

Because you can't use anything except the internal voltage reference, which is in turn driven from the internal noisy power, you can't get anything even vaguely approaching stable readings.

It is recommended to disable the WiFI completely ("Modem Sleep") when doing ADC readings to reduce noise.

However, the ADC was never intended for this kind of work. Its primary role is for monitoring the battery voltage of your hardware - and as such it really doesn't care that much about noise, since you can average a number of samples for greater accuracy (something you can't really do with audio).


Pull EN pin of regulator to ground I have an Adafruit Huzzah Feather with ESP8266 board, but I think my question will apply to most all boards (as most all have an onboard regulator). Most regulators have an Enable pin (EN) as does my Adafruit board. Apparently, I can shut down the regulator by pulling this pin low. I have a specific application where an external device will provide a high signal to me when I want the device to turn on, otherwise, I want it off at all times. So, what I have is a 1k resistor pulling the EN pin low, to ground. I tried other values 10-20k but they did not pull enough low to shut down the regulator. For example, 20k pulled me down from 3.3V to 2.6V but the regulator stayed on. On the other hand, 1k pulls me down to .3V on the EN pin and this shuts it down.

Then, when the external device gives me the high signal, which I have also tied to the EN pin, this will pull it back up and turn on the regulator.

This seems to be working just fine, but I wanted to ask if this sounds reasonable (I know this is a general question but I want to know if there is a better way). A specific, related question would be am I wasting too much power by using a 1k resistor when powered up or pulled high since some of the supply current will be dumped via the 1k resistor to ground.

UPDATE: In looking at the schematic on the Adafruit site, it appears that they have pulled EN to the input via a 10k resistor. So, I am fighting that which is probably why values over 10k do not pull it down enough to turn off. If I was doing the board design, I would have reversed this and pulled EN low by default but this is not the case when using the off the shelf board. So, I guess any value below 10k should work, like 4.7k? I guess I could also remove their pull up if I wanted to get really crazy. Thoughts on all of this?

Thanks!

A better solution would be to use a PNP transistor to control the EN pin. A PNP is ON when the input to it is LOW (or lower than the collector minus 0.7V, that is).

Take this circuit, for instance:

simulate this circuit – Schematic created using CircuitLab

When the GPIO is HIGH the transistor Q1 is turned off (GPIO >= VCC-0.7). Also if the GPIO pin is disconnected it is turned off because R3 pulls it up to VCC.

Set the GPIO LOW and Q1 turns on since the base is now lower than VCC-0.7V. With Q1 turned on it connects the EN pin to ground, so it becomes LOW.

If you replace the PNP with an NPN (there's more chance you have one in your bits box) you can basically invert the logic:

simulate this circuit

Now when the GPIO is LOW or pulled down by R3 Q1 is off and EN is pulled HIGH. Set the GPIO HIGH and Q1 turns on and connects EN to ground setting it LOW.

In both these scenarios the EN pin defaults to HIGH. If you want it to default to LOW until you activate the GPIO pin (i.e., during bootloader operation when the GPIO is in INPUT mode) you can reverse R3 so it becomes a pull-down (for the PNP) or a pull-up (for the NPN).


Mains-Frequency Clock Library I have an arduino thing, and the hardware I plan to connect to it (a triac zero-crossing based dimmer) provides a synchronization signal from the mains power phase it connects to.

Main power does of course vary some from the nominal 60Hz, however the exact frequency gets adjusted over the course of the day to ensure there are almost exactly 5184000 cycles per day and pretty much exactly 36288000 cycles per week, and is used by mains-powered wall clocks to keep time.

Since my application will need to keep accurate time-of-day across weeks or months without adjustment, it would be advantageous to be able to use this time source.

I can of course write my own code to increment a counter every time the arduino receives a pulse, but if a library that can handle this already exists, I would prefer to use that, in particular since then I won't have to write code to track days and months, handle DST, or any of that stuff.

What libraries exist (if any) to handle timekeeping based on a fixed-pulse-rate input source?

Counting the pulses is child's play and doesn't need a library (hint: use an interrupt input and increment a counter). From that count you can use TimeLib.h to convert seconds since 01/01/1970 to an actual time.  Or just do simple division to convert seconds (count/50) into minutes, hours, whatever division you want.


Follow up question to Calling a timer when a button is pushed I have changed the code with some help here. There are two buttons each one is set to turn on a LED. When the LED turns on it is timed and when the time is up it turns off. The problem I am having is that only one LED can be on at a time even though I am not using the delay() and I am using millis() to keep track of time. So if I press button one the first LED will turn on. Even if I press button two at this time the second LED wont turn on until the first one turns off.

const int ledPin2 = 2;
const int ledPin3 = 3;
const int buttonPin6 = 6;
const int buttonPin7 = 7;

const unsigned long onTime = 10000;
unsigned long previousMillis = 0;

void timer() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin2, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin2, LOW);
}

void timer2() {

unsigned long previousMillis = millis();
unsigned long currentMillis = millis();
digitalWrite(ledPin3, HIGH);

while ((currentMillis - previousMillis) < onTime) {

    currentMillis = millis();
}

digitalWrite(ledPin3, LOW);
}

void setup() {
Serial.begin(9600);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(buttonPin6, INPUT);
pinMode(buttonPin7, INPUT);

}

void loop() {

int buttonState2 = digitalRead(buttonPin6);
if (buttonState2 == HIGH) timer2();

int buttonState = digitalRead(buttonPin7);
if (buttonState == HIGH) timer();

}

Yes, it is because in timer() and timer2() you busy-loop with while until the condition is not met. Hence, when buttonState2 is HIGH, your code will execute timer2() until the condition of the while loop is not met. You are effectively doing a delay.


Cannot ping ESP8266's IP address from a computer on the same network I have an ESP8266 module connected to my Arduino Mega 2560. I sketched a simple code to pass whatever command I typed from the Serial Monitor to ESP8266 and vice versa:

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

void loop() {
  if (Serial.available())
  {
    Serial2.write(Serial.read());
  }

  if (Serial2.available())
  {
    Serial.write(Serial2.read());
  }
}

So from here on I just type my AT commands inside Serial Monitor and receive the output also inside Serial Monitor. Managed to connect into a wifi network using the command:

AT+CWJAP="SSID","password"

And obtain my ESP8266 module's IP address using the command:

AT+CIFSR

+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"5e:cf:7f:c2:ce:30"
+CIFSR:STAIP,"192.168.1.103"
+CIFSR:STAMAC,"5c:cf:7f:c2:ce:30"

OK

Problem is, whenever I run CMD and "ping 192.168.4.1" or "ping 192.168.1.103" from my PC which is connected to the same network, I will get "request timed out". Pinging my own PC's IP gets me a reply. What is wrong here? Totally clueless... :-/

EDIT My PC's IP address is 192.168.56.1

First, you need to confirm that your PC's wireless connection is on the same IP subnet as the ESP8266. At the CMD prompt, type:

ipconfig /a

and look for the wireless adapter. Hopefully the IP address will start with 192.168.1.... It should but there's no harm in checking!

Second, check that your WiFi router hasn't disabled pinging between its clients - some do (mine did, until I threw it out...). Do you have a smartphone or other WiFi device? If so, find out its IP address (hopefully also 192.168.1....) and confirm that you can ping it.

Pinging your own address isn't very useful. Normally it detects the fact that it's its own address, and replies with no attempt at sending over the air.


Interfacing 4 ESCs and an Arduino with a single LiPo battery I have 4 BLDC motors, and 4 ESCs, one for each motor. But I have one LiPo battery from which I want to power one Arduino Mega and all the 4 ESCs. Can I remove the connectors from the ESCs and put them on a breadboard in a single column/row so that they are connected together, and then connect the + and - of the battery (after removing its connector as well) to the respective breadboard column/row, so that they are essentially connected together to power all the ESCs? Also, I would want to use a jumper from the Arduino Vin and GND pins to the same column/row on the breadboard. Will this method of powering all the 4 ESCs and the Arduino from a single LiPo work?

Powering all the ESCs from a single LIPO is not an issue.

Using a breadboard to distribute this power is highly unlikely to work, breadboard connectors are usually only good to a few hundred mA, 1A is you want to push your luck.  Most ESCs and BLDC motors are in the 5A to 50A range (each, your power bus has to handle 4 times this current).

Also, ESCs tend to inject a lot of noise into the power bus.  If you connect the arduino to the ESC power bus, you will likely get random resets and really poor noise performance on the ADCs.  Keep in mind that some ESCs actively brake the motors using regenerative braking, which puts the kinetic energy of the motor back into the power bus.  This can increase the voltage on the power bus to more than the nominal battery voltage and can have large voltage spikes on it causing a failure on the Arduino.

If you are prototyping, use a separate power supply/battery for the arduino and connect all the grounds together instead of using a single supply.  If you are building a rover/uav/whatever and don't want a second battery, use a high quality BEC (or the BEC output from a high quality ESC) and remember that the 5V output on a BEC/ESC can be significantly higher than 5V in reality).

ESC = Electronic Speed Controlled
BEC = Battery eliminator circuit (I think, basically a 5V-ish regulator)
BLDC = Brushless DC motor (three phase in this case)


ESP01 unsuccessful code execution I am trying to upload the Blink example from the Arduino IDE to a ESP8266-01 module using an Arduino Uno as serial programmer.
Now, the upload is successful but, upon restart (and disconnecting GPIO0 from GND), nothing happens. I have tried with different example sketches but it seems code was not uploaded.

My Board manager configuration

Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40 MHz
CPU frequency: 80 MHz
Flash size: 1M (128K SPIFFS)
Debug port: Serial
Debug level: none
Reset method: ck (tried nodemcu too without success)
Upload speed: 115200
USB port

As an addition, here's what I get from the ESP01 through the Arduino IDE Serial monitor:

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
e:
 ets Jan  8 2013,rst cause:3, boot mode:(3,7)

ets_main.c

and here's the IDE console window output:

sptool.py v1.3
Connecting..........
Auto-detected Flash size: 8m
Running Cesanta flasher stub...
Flash params set to 0x0020
Writing 229376 @ 0x0... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x0 in 39.0 seconds (47.0 kbit/s)...
Writing 229376 @ 0x10000... 0 (0 %)1024 [...]
Wrote 229376 bytes at 0x10000 in 39.0 seconds (47.0 kbit/s)...
Leaving...

The sketch I am using

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

If you are using an ESP01 I don't think you should be using GPIO1 as the output pin, its my understanding that they don't have GPIO1.

I think they have GPIO0 and GPIO2, so you should have attached the LED to GPIO2 and use digitalWrite(2, HIGH); in you code.

Have a look at this page and see if what its on about is what you are trying to do.

http://iot-playground.com/blog/2-uncategorised/38-esp8266-and-arduino-ide-blink-example


ESP32 AsyncWebServer SPIFFS problem loading page I can load spiff docs, but I get a 404.  Wireless works, IP addressing works and I can load other examples successfully.  This simple image load ino is giving me fits!
#include <WiFi.h>
#include <AsyncTCP.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
const char *ssid = "x";
const char *password =  "123456789";
IPAddress staticIP(10,0,0,1); //ESP static ip
IPAddress gateway(0,0,0,0);   //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0);  //Subnet mask

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  WiFi.softAP(ssid, password);

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{request->send(SPIFFS, "/index.htm", "text/html");});

server.on("/image.png", HTTP_GET, [](AsyncWebServerRequest *request)
{request->send(SPIFFS, "/image.png", "image/png");});

server.begin();

}//END setup

void loop()
{
}

<!DOCTYPE HTML>
<html>
<head>
     <meta charset='UTF-8'>
</head>
<body>
     <img src="image.png" alt=" image goes here">
</body>
</html>

I don't have an ESP32 to test with.  Though, I tried to make your code run on an ESP8266, but it's a bit of an effort to validate what is ultimately a wild guess on my part.
And that is: perhaps you have some uppercase letters in your filename such that "/image.png" does not match perfectly and furthermore maybe SPIFFS is case sensitive.  That is, your file could be named Image.png or IMAGE.png and that might matter.
UPDATE:
In my exploring this on the ESP8266, I'd forgotten to execute SPIFFS.begin().  And I see no counterpart to it in your code.
At least one example of ESPAsyncWebServer I've seen does call SPIFFS.begin()
I found that the filenames are case sensitive, again at least on the ESP8266; so that can be a source of problems.
Also checked that if the SPIFFS size is changed through menu selections, I did indeed need to reupload the SPIFFS image.
I know these are different systems; in fact the code I'm using to test doesn't compile for ESP32, but I suspect a lot of the code is shared, and so maybe the problems are as well.


Solenoid "vibrates" instead of pushing I'm using my Arduino Uno to control a 5V 1A solenoid.

I'm using an N-Channel MOSFET linked to the Uno's 0 pin to switch the solenoid on and off. It is protected by a Schottky diode. Initially, I tested the circuit with the blink example sketch (just set to blink Pin 0 instead of Pin 13). I used the Uno's built in 5V 500mA output and the solenoid "blinked" on/off perfectly at whatever interval I wanted:

I plan on controlling multiple solenoids in a future version, which will draw more current than the Arduino output can supply, so I bought a 5V 12A power supply. I proceeded to test it with my single-solenoid set up using the same blink example sketch:

When I power the solenoid with my 5V 10A my power supply, the solenoid doesn't push on command. It merely "vibrates," travelling only about .5mm at several hundred Hz. The solenoid vibrates constantly the moment I plug in the power supply, and does so completely independently of whatever interval I have set it to "blink."

Any ideas as to what may be causing this to work with the Arduino's built in power supply, but not with an external power supply? I've tested the voltage on my power supply, and it reads 5V as advertised. I'm somewhat new this, and feel like I may be missing something obvious.

Thanks,

Max

From your schematics it looks like:

you connected the power supply backwards (on both schematics actually, I wonder how come you did not fry your Arduino)
the external supply and the Arduino do not share a common ground as they should.

Edit: about the orientation of the power supply:

the (−) side of the supply (and GND of the Arduino) should be connected to the source of the N-MOSFET
the (+) side of the supply should be connected to the cathode of diode (the side identified by the small white bar)


Arduino: How to get the board type in code I want to write a sketch that can be compiled on different Arduino boards.
I want to display on the PC which board is currently connected.

This means that the user connects the PC via USB cable to the Arduino/Teensy board in which runs my sketch and my sketch tells the PC via Serial which board is connected. On the PC runs my C# application which receives this data and displays it.

Therefore I need the board that has been selected when the sketch has been compiled:

I found the code on https://github.com/backupbrain/ArduinoBoardManager
but it does not give correct results (apart from the fact that several boards are missing).

Here a snippet from the code:

static const uint8_t BOARD_MICRO= 0x04;

....
#elif defined(__AVR_Atmega32U4__) // Yun 16Mhz, Micro, Leonardo, Esplora
  static const uint8_t BOARD = 0x04;
  static const uint8_t NUM_BITS = 8;
  static const uint16_t CPU = __AVR_Atmega32U4__;
  static const unsigned long SRAM_SIZE = 2500;
  static const unsigned long EEPROM_SIZE = 1000;
  static const unsigned long FLASH_SIZE = 32000;
#elif defined(.....

So this code gives the same result (BOARD = 0x04 = Micro) for Yun 16MHz, Micro, Leonardo y Esplora.

Is there any way to get in my C code exactly the string that the user has selecetd in the menu of the Arduino compiler?

Thanks to the help of Charlie Hanson and jantje I found the universal solution!

Because it is a pity that every Arduino programmer has to go through the same pain to figure out how to get the board name, I will offer my code to the public so everybody can just copy and paste it.

Here it is:

#if defined(TEENSYDUINO)

    //  --------------- Teensy -----------------

    #if defined(__AVR_ATmega32U4__)
        #define BOARD "Teensy 2.0"
    #elif defined(__AVR_AT90USB1286__)
        #define BOARD "Teensy++ 2.0"
    #elif defined(__MK20DX128__)
        #define BOARD "Teensy 3.0"
    #elif defined(__MK20DX256__)
        #define BOARD "Teensy 3.2" // and Teensy 3.1 (obsolete)
    #elif defined(__MKL26Z64__)
        #define BOARD "Teensy LC"
    #elif defined(__MK64FX512__)
        #define BOARD "Teensy 3.5"
    #elif defined(__MK66FX1M0__)
        #define BOARD "Teensy 3.6"
    #else
       #error "Unknown board"
    #endif

#else // --------------- Arduino ------------------

    #if   defined(ARDUINO_AVR_ADK)
        #define BOARD "Mega Adk"
    #elif defined(ARDUINO_AVR_BT)    // Bluetooth
        #define BOARD "Bt"
    #elif defined(ARDUINO_AVR_DUEMILANOVE)
        #define BOARD "Duemilanove"
    #elif defined(ARDUINO_AVR_ESPLORA)
        #define BOARD "Esplora"
    #elif defined(ARDUINO_AVR_ETHERNET)
        #define BOARD "Ethernet"
    #elif defined(ARDUINO_AVR_FIO)
        #define BOARD "Fio"
    #elif defined(ARDUINO_AVR_GEMMA)
        #define BOARD "Gemma"
    #elif defined(ARDUINO_AVR_LEONARDO)
        #define BOARD "Leonardo"
    #elif defined(ARDUINO_AVR_LILYPAD)
        #define BOARD "Lilypad"
    #elif defined(ARDUINO_AVR_LILYPAD_USB)
        #define BOARD "Lilypad Usb"
    #elif defined(ARDUINO_AVR_MEGA)
        #define BOARD "Mega"
    #elif defined(ARDUINO_AVR_MEGA2560)
        #define BOARD "Mega 2560"
    #elif defined(ARDUINO_AVR_MICRO)
        #define BOARD "Micro"
    #elif defined(ARDUINO_AVR_MINI)
        #define BOARD "Mini"
    #elif defined(ARDUINO_AVR_NANO)
        #define BOARD "Nano"
    #elif defined(ARDUINO_AVR_NG)
        #define BOARD "NG"
    #elif defined(ARDUINO_AVR_PRO)
        #define BOARD "Pro"
    #elif defined(ARDUINO_AVR_ROBOT_CONTROL)
        #define BOARD "Robot Ctrl"
    #elif defined(ARDUINO_AVR_ROBOT_MOTOR)
        #define BOARD "Robot Motor"
    #elif defined(ARDUINO_AVR_UNO)
        #define BOARD "Uno"
    #elif defined(ARDUINO_AVR_YUN)
        #define BOARD "Yun"

    // These boards must be installed separately:
    #elif defined(ARDUINO_SAM_DUE)
        #define BOARD "Due"
    #elif defined(ARDUINO_SAMD_ZERO)
        #define BOARD "Zero"
    #elif defined(ARDUINO_ARC32_TOOLS)
        #define BOARD "101"
    #else
       #error "Unknown board"
    #endif

#endif

You can even put this code into a new header file and #include it into your project.

P.D.
If you want to know additionaly to the board also the CPU model, search for the file avr_cpunames.h


Problems with NodeMCU and Relay I've connected the MCU to a cheap chinese 24/12v to 5v car phone charger and hooked some wires to a relay.When I try to program doesn't matter if the pin is set to high or low , as soon as I touch the "IN" wire from the relay into any of the selected pins, the relay auto actives.

here is the schematic
The charger input is hooked to a 12V drill battery for tests and the output to arduino is an usb port that I soldered wires to it's respective poles.

USB from Chinese charger Positive pole ------- NodeMcu Vin
USB from Chinese charger Negative pole ------- NodeMcu GND
USB from Chinese charger Positive pole ------- Relay   VCC
Relay Ground --------------------------------- NodeMcu Gnd
Relay DataPin -------------------------------- NodeMcu D0 or D1

And here's the code:

int port = D0;
int portB = D1;

void setup() {
Serial.begin(115200);
pinMode(port,OUTPUT);
pinMode(portB,OUTPUT);

digitalWrite(port,HIGH);
digitalWrite(portB,LOW);

}

void loop() {

}

But the result is that the relay will always be on activated ( IN pin = Low ) even connected to D0 that is high... Any ideas ?

Does your nodemcu directly feed the relay?
If so, 3.3v (nodemcu output high level) is not enough to activate it.
I would use a transistor like a s8050 to Power it (do not forget the freewheel diode on the relay coil)


Creating a timer using a Real Time Clock with start and stop times I have an Arduino Uno with a motor shield, as well as a DS1307 RTC that I am using to control 2 pumps.

Ideally I would like to set a start time (startHour + startMinute) and end time (endHour + endMinute) for each pump.

I have had luck using if statements to control my timer like below (adapted from Iain Foulds):

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

byte startHour2=22
byte startMinute2=30
byte endHour2= 2
byte endMinute2= 45

void loop() {
  byte checkStartTime1() {
    DateTime now = RTC.now();
    // Read in what our current datestamp is from RTC
    if (now.hour() == startHour && now.minute() == startMinute) {
      validStart1 = 1;
    } else {
      validStart1 = 0;
    }
    return validStart1;
    // Return the status for powering up
  }
}

But my concern is that this only checks for equivalency at the moment, and if I lost power when my start time came up my pump would not come on. So I was hoping to set up an if statement that can deal with ">=" as opposed to just "==".

Which I can use if I only deal with the hour section:

if (now.hour() >= startHour && <= endHour)

But things get complicated when I try to add in minutes to the control structure. I end up with a series of nested for loops that do not work.

I'm hoping someone can help me write an if statement (or switch case) that can accommodate hours and minutes. So that any time between 8:15-14:20

validStart1=1

and anytime other time

validStart1=0

And please note the addition of the second set for this timer (StartHour2)- which I threw as my second pump will need to deal with the switch over past midnight.

I had a similar problem when i tried to control some heating source here at home.This was how I made my steps to get it working.
First I will assume you are using the library time.h and DS1307RTC.h (check here for info: https://www.pjrc.com/teensy/td_libs_Time.html).

Assuming that you will need 3 variables of the type tmElements_t.
tm will store your current time( the one you get from DS1307). The other two are auxiliary for defining time you start and time you stop the pump.
In similar way, you will need 3 variables of type time_t for the same reasons.
time_t variables store a the timestamps since 01/01/1970 (Unix epoch) which are easier to work with but tmElements structures are more human friendly.

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

Now in your loop you need to get the current time from rtc:

time_t now = RTC.get();

after, use the breaktime funtion to convert the timestamp value to tmElements struture:

breakTime(now, tm);

Next step is to copy contents of tm to the other auxiliary structures, use the memcpy function:

memcpy(&tm_hour_start, &tm, sizeof(tm));
memcpy(&tm_hour_end, &tm, sizeof(tm));

after, change the the auxiliaries vars to meet your correct schedule of start and stop (are seconds important? if so, do similar way):

tm_hour_start.Hour = startHour;
tm_hour_start.Minute = startMinute;
tm_hour_start.Second = 0;
tm_hour_end.Hour = endHour;
tm_hour_end.Minute = endMinute;
tm_hour_end.Second = 0;

Ok, we have the more human friendly start and end structures, lets get the timestamps from them. To do soo we use the makeTime function that converts tmElements_t structures to time_t:

t_hour_start = makeTime(tm_hour_start);
t_hour_end = makeTime(tm_hour_end);

All you need to do now, is check if your current timestamp (now) is between this newly created timestamps:

if ((t_hour_start <= now) && (now <= t_hour_end)){
   //do something is soo...
}else{
   // do something if not...
}

Extra tip: In case your stop hour goes past midnight, add one more day to the timestamp:

if (startHour > endHour) //past midnight correction
   t_hour_end = t_hour_end + SECS_PER_DAY;

clean code:

#include <time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour=8
byte startMinute=15
byte endHour= 14
byte endMinute= 20

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now, t_hour_start, t_hour_end;

// setup function and other needed things...

void loop(){
  //get current timestamp
  time_t now = RTC.get();
  // make current date and time structure
  breakTime(now, tm);
  // make auxiliary structures to be more human editable and friendly
  memcpy(&tm_hour_start, &tm, sizeof(tm));
  memcpy(&tm_hour_end, &tm, sizeof(tm));
  // change auxiliary structures to meet your start and end schedule
  tm_hour_start.Hour = startHour;
  tm_hour_start.Minute = startMinute;
  tm_hour_start.Second = 0;
  tm_hour_end.Hour = endHour;
  tm_hour_end.Minute = endMinute;
  tm_hour_end.Second = 0;
  // reverse process to get timestamps
  t_hour_start = makeTime(tm_hour_start);
  t_hour_end = makeTime(tm_hour_end);
  // check if end time is past midnight and correct if needed
  if (startHour > endHour) //past midnight correction
       t_hour_end = t_hour_end + SECS_PER_DAY;

  //final part
  if ((t_hour_start <= now) && (now <= t_hour_end)){
          //do something is soo...
  }else{
          // do something if not...
  }

}

EDIT: to correct the thing about midnight checks spotted in comments. New code:

#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <stdio.h>
// other includes etc...

byte startHour = 8;
byte startMinute = 15;
byte endHour = 14;
byte endMinute = 20;

tmElements_t tm, tm_hour_start, tm_hour_end;
time_t now_, t_hour_start, t_hour_end;
boolean update_tm = 1;

// setup function and other needed things...
void setup(){};

void loop(){
  //get current timestamp
  time_t now_ = RTC.get();
  // make current date and time structure
  breakTime(now_, tm);
  // make auxiliary structures to be more human editable and friendly
  if(update_tm){
    memcpy(&tm_hour_start, &tm, sizeof(tm));
    memcpy(&tm_hour_end, &tm, sizeof(tm));
    // change auxiliary structures to meet your start and end schedule
    tm_hour_start.Hour = startHour;
    tm_hour_start.Minute = startMinute;
    tm_hour_start.Second = 0;
    tm_hour_end.Hour = endHour;
    tm_hour_end.Minute = endMinute;
    tm_hour_end.Second = 0;
    // reverse process to get timestamps
    t_hour_start = makeTime(tm_hour_start);
    t_hour_end = makeTime(tm_hour_end);

    // check if end time is past midnight and correct if needed
    if (startHour > endHour) //past midnight correction
      t_hour_end = t_hour_end + SECS_PER_DAY;
  }
  //final part
  if ((t_hour_start <= now_) && (now_ <= t_hour_end)){
    /* if we got a valid schedule, don't change the tm_hour structures and the
    respective t_hour_start and t_hour_end timestamps. They should be updated
    after exiting the valid schedule */
    if(update_tm)
      update_tm = 0;

    //do something is soo...
  }else{
    if(update_tm == 0)
      update_tm = 1;
    // do something if not...
  }

}


Confusion with Serial Communication Is a buffer used for outputting data from the arduino?

OR

Is the output from the arduino buffered before sending it to Computer?

Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

Eg- If am sending a text through the Serial Monitor to the arduino and I am also doing Serial.println("sth") then are they both using the same buffer?

How can i relate Serial buffer with these processes

Please Help!

Arduino Noob

EDIT-1

Can you please explain about the TX buffer overflow

Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

there are two buffers RX buffer and TX buffer.

  Is a buffer used for outputting data from the arduino? OR Is the output from the arduino buffered before sending it to Computer?

TX buffer holds the data until they can be send. Data are send from TX buffer by interrupt routine.

  Can you please explain about the TX buffer overflow

TX buffer overflow doesn't happen, because it is easy to handle the situation.
The interrupt routine can send the data only at set baud rate. If the program fills the buffer faster then the interrupt empties the buffer, then the TX buffer fills, but the write function knows that the buffer is full and waits in a while cycle until there is space for that one byte to write.