Controlling water temperature accurately I have following setup:

Arduino Duemilanove
Small water heater connected with optical relay (PWM is ok)
Waterproof DS18B20 temperature sensor
Unknown amount of water (but temperature sensor and heater are always underwater).

How can I accurately control water temperature, based on temperature sensor readings? By accurately, I mean up to accuracy of temperature sensor (in this case, ±0.5°C). Everything should run on Arduino, so no additional data storage or processing power is available. For debugging, I can obviously use computer.

I have tried running PID, but it seems really hard to

Avoid overshooting - going over target temperature either initially, or when (cold) water is added
Stabilize properly after adding cold water.

You need to know the response time of your system and the repeatability of your measurements to characterize your data (establish confidence). I suggest taking samples and average them before turning the heater back on.

Imho, water will not happily stay within 0.5°C. Can you allow for coarse and fine modes? Use a higher PWM for great differences and then lower PWM for when close to target.

Once homed in on your target, there are a few means you can try to improve temperature stability. While pre-built things like PID work for many, I normally implement functionality like this manually.


Hooking up LCD screens reclaimed from old camcorders to Arduino Has anyone had any luck using LCD screens reclaimed from old electronics with Arduino, such as camcorders etc?

My 8 yr old has an old sony handycam (dcr-trv103) in bits and now wants to use the LCD screen with the arduino. I'm not even sure how I would go about this. Any tips? How do I figure out 'what does what' in terms of the inputs? How would I drive this thing / what do I need to do to send visual images to it via an Arduino?

Here's the front and back panels of the LCD screen, and their hookups.

The Screen

Screen hookup

I'm assuming this is the backlight

backlight hookup

Note: someone identified this as a duplicate of another question about reusing a cellphone LCD screen. This question is specifically about reusing an older camcorder LCD screen. Also that other question has very little answers. I found the answers below useful and educational. Thanks all.

This is likely a type of TTL LCD interface.  But it is nearly impossible to describe more as there are so many variations both in hardware and in timing.
Likely a steady stream of Red Green & Blue binary data way faster than an Arduino Uno could possibly manage is required to create an image.  For the necessary processing power, you would have to utilize one of the top end Arduino boards.  Even then, software to create the steady stream of binary data for this particular LCD is still required. Also, there are hardly no standards beyond saying the LCD is a TTL or LVDS.  Which means hours spent on developing software for this LCD will likely only work for this LCD.

It would be far easier to just buy an LCD and interface board known to work together.  If you are using an Arduino Uno, there is not much processing power beyond saying "I want a circle here" or "I want a line there".  Fortunately, there are such COTS parts available.  Here is a tutorial describing such a device connected to an Arduino Uno.


Unspecified running error while programing WeMos D1 in wireless mode I've tried to program WeMos D1 directly by wireless connection. I've test my D1 so it had no problem. after setting SSID and Password I've programed it for wireless using. It ran well. as I want to programing thought wireless there was an Unspecified error for running python.exe !
java.io.IOException: Cannot run program "python.exe": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:26)
    at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
    at cc.arduino.packages.uploaders.GenericNetworkUploader.uploadUsingPreferences(GenericNetworkUploader.java:99)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:709)
    at processing.app.SketchController.exportApplet(SketchController.java:682)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2190)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
    at java.lang.ProcessImpl.start(ProcessImpl.java:137)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 8 more
An error occurred while uploading the sketch

I've python on my PC  and it works. to clear my problem I've attached  the following gif

any help would be appreciated.

You might have Python installed, but can you run it?

Open a command window on you PC.  (Windows button R then CMD)
Then in that type python.

If python starts up then it should be working, but I suspect you will get an error saying:

'python' is not recognized as an internal or external command, operable program or batch file.

To fix this you need to edit you path and restart the IDE.  (How you edit you path depends on your version of Windows so you would be best searching for edit environment path and your version of windows and that should come back with an answer quickly.

Of course if its Linux/mac then it could still be the same issue.


Run a part of code upon call Lets say I have something that sends a command to the Arduino (for example, a PC sending through serial, Ethernet, etc). I want the Arduino to "check" what command it is and run a specific function linked to that command.

I don't need a very explanatory answer, just give me something so I can learn from. A sketch that shows a similar idea would be good, I can try to interpret it and adapt/remake for me.

The idea is to use the Arduino for a lot of different things. Let's say:

Turn a bunch of leds on/off;
Read data from a sensor and send it through Ethernet/I2C/Serial;
Control a servo.

But I want the Arduino to do that when I tell it to (in this case, sending the command through serial, etc). So let's say I send it 1, I'll want it to run the 1 function (turning the LEDs on/off).

I already took a tutorial course on Arduino programming, but I'm clueless on how to do this job.

If you want it really barebones and easy, you can checkout the Arduino "Dimmer" example sketch.

Instead of changing the brightness of an attached pin, you could take the input you send it over the serial console and execute various functions, depending on what you receive.

Something like this:

boolean newCommand = false;
void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);

  // other setup stuff here
}

void loop()
{
  byte command;

  // check if data has been sent from the computer:
  if (Serial.available())
  {
    // read the most recent byte (which will be from 0 to 255):
    command = Serial.read();
    // say that you received a new command
    newCommand = true;
  }

  // is there a new command?
  if (newCommand == true)
  {
    // do something depending on what command you received
    switch(command)
    {
      // if you receive command "1", do something
      case 1: functionWhatever();
              break;  // "break" out of the switch. otherwise it would continue executing the following commands as well
      case 2: functionWhatever2();
              break;
      //for cases that are not caught, send out an error
      default: Serial.write("invalid command");
              break;
    }
  }
}

If you want to use an existing library, you might want to check out:
EasyTransfer.

It can be used for communication between two Arduinos, which you then can use to execute functions on the other side of the line.

The code itself is relatively simple, so you might be able to adapt it to communicate with a processing script on your computer for example.


code to force a gentle servo power up So I am new to the board and looking for a source to answer an Arduino servo project's rough power up.  The project uses a pair of servos operating together to swing a small door.  I have been working with intro level sketches over the last few weeks. I have powered and re-powered my Arduino Uno several times with different codes and each time the unit is powered the two servo motors move to their last position at what appears to be full speed resulting in a rather jerky and jumpy power up.

What can you suggest in the code that would force the servo motors to gently move toward their new code starting position?  Like a 'warm up cycle'.

You cannot do that with ordinary servos. This is because of the way the
communication protocol is built: the only thing a servo understands is a
command which in effect means “go to that position as fast as you can”.
You can achieve smooth movements by updating the requested position (the
so called “set point”) many times by tiny steps, but you still have the
problem at startup.

I see two possible solutions to your problem:

Make sure you know the position at which the servo was left when you
powered down your Arduino. You can either arrange to leave it always
at the same position, or you can store the last position in EEPROM
before powering down. Then, at startup, you initialize the servo with
that last known set point.
Use a special type of servo known as a feedback
servo,
or convert a regular
servo to
get a feedback. A feedback servo is a type of servo that tells you
its actual position, so you can arrange for the initial set point to
match that position.


How can I maintain switch state when in sleep mode? I'm using a esp8266 to build a remote control to power a gas fireplace. I'm using this guide to try and maximize battery life.

The concept is the controller uses its built in WiFi to access a RESTful API on a remote server; If the API discovers"1", it should close a switch and the fireplace turns on. If the arduino reads a "0" via the API it opens the switch and the fireplace turns off. After discovery and performing the required action the unit calls Deepsleep and shuts off for ten seconds, whereupon it powers up and the cycle repeats itself again.

I just realized that if the controller powers off, I don't know what happens to the switch. If the fireplace was turned on,  what happens when deep sleep starts. Is there a way (special switch?) that maintains its state in deepsleep mode?

You can get a latching relay. These come in two flavours - Unipolar, where you energise one pin to turn it on, and energise the other to turn it off, and Bipolar, where the direction of the current through the coil turns on or turns off.

Unipolar is easier to drive since you just need two transistors, diodes and resistors. Bipolar is harder, since you need a H-bridge (motor driver), but requires less wires to connect it up (2 as opposed to 3).

In both cases it is just a short pulse that is needed to switch the relay into a different state - there is no need to maintain the output, so is ideal for deep-sleep mode where everything is turned off except the RTC.


Reading consecutive two pulse periods continuously I'm controlling the DC motor/fan speed by PWM through varying analog input. Using Uno or Nano.

The loop is as follows:

void loop()
{
  val = analogRead(analogPin0);  // read the analog input pin
  analogWrite(pwmPin9, map(val, 0, 1024, 0 , 255));
}

Above analogPin0 value is varied by a poti.

But I also want to output the rpm on an LCD. To do that I need to measure the period between two consecutive pulses as shown below:

How could I measure continuously "period between two consecutive pulses"? Should I use interrupt? Does anybody have any experience with that?

An interrupt off of one of the timers sounds like the easiest way to go. To get a measurement precision of, say 3% at 4ms means sampling every (4000us * .03) = 120us (8.333 KHz). If your code has little else to do, you might get away with clock-watching - micros() ticks every 4us - but you'll need to keep anything else you do between reads of micros() to under 120us, and half of that might be a good target figure.

In this answer I described a general non-blocking procedure for managing several tasks in a timely way. If you chose such a design, one task might manage the potentiometer and analog output, another one the RPM measurement, and another the LCD. The ISR would do nothing but set a flag.

The RPM & LCD tasks can run at a relatively low rate as they're intended for human consumption only. They may have to work piece-wise, though, to meet their time restrictions.


Arduino Uno R3 ISR does not work on pin 2? I have an Arduino Uno R3. I have a paddlewheel waterspeed sensor that I use on an ISR on pin 2. The power supply is approximately 8v stepped down to 4.92v with a circuit yanked from the phone charger. I have also tried this with the arduino 5v.

The pin returns the correct values with digitalRead(), so it's cycling between 1 and 0.

The ISR works fine on pin3. Why does it work on pin 3 and not pin 2 ISR?

void itest() {
    Serial.println( "test" );
}

void setup() {
    attachInterrupt(0, itest, FALLING);
}

never use Serial inside an interrupt handler, increment a (volatile) variable and print it in the loop().


VisualMicro Can't compile in debug ('Serial' was not declared in this scope) for attiny84a I was working on a project build initialy from the Arduino IDE to program an attiny84a (without a bootloader) using the board from https://github.com/damellis/attiny

I got an atmel-ice recently and I was trying to debug the arduino sketch using it.

I installed AtmelStudio (because I know it has an GUI debugger) and found VisualMicro that should help me to compile arduino sketch.
Unfortunatly as soon as a set the project to debug I got a compilation error :

'Serial' was not declared in this scope

(I don't have this error in Release mode).

My code doesn't use any serial (because I don't have any pin left), so this was wierd. I still tried to add the SoftwareSerial.h include (just in case) without success.

So I created an empty (I mean with only an empty setup() and loop() methods) and it throw the same error.

I tried to setup different versions of arduino IDE into VisualMicro (1.6.13, 1.8.1, 1.8.5 and 1.9 build 34) without success.

Then after a couple of hours I found the .cpp source generated by VisualMicro and it try to use the member "Serial" for some debugging reason.

I would like an easy way to integrate with arduino (all those library and easy to install library) and to be able to debug as well, what can I look for or do?

Thank

'Serial' was not declared in this scope

This error is not surprising when compiling for ATtiny84 because in Arduino Serial refers to the hardware serial port and ATtiny84 doesn't have one.

But you didn't use Serial in your sketch so why should you get this error? The answer is this magical debug feature of Visual Micro that you desire. It turns out that on AVR microcontrollers such as your ATtiny84 all this actually consists of is Visual Micro automatically inserting various Serial.print() statements into your code, just as we always do manually to debug our code in the good old Arduino IDE:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-Explained.html

So in fact your sketch is attempting to use Serial without your knowledge or being able to see it! If you turn off debugging you should no longer get that error.

Visual Micro does allow you to change the debugging output to software serial:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-With-Different-Ports.html

but since you say you have no pins available that may not be any help.


How to update multiple outputs simultaneously I need to update simultaneously all the outputs of a specific port.

I am familiar with using micro-processors assembly language. After initializing a port (Data Direction Register), I can write to that port and all outputs will update simultaneously.

In the Arduino commands  : I am aware of how to configure pins, such as pinMode(pin, mode), to make a pin an output or input.

I know of the digitalWrite(pin, value) , but this only updates one pin per command.

For timing reasons, I need to update several (same port) outputs without any time delay.

Normally (using assembly language) , I would keep a register with the data I desire on the output port, and write that register's data to the port.

Is there a command I can use in Arduino to accomplish the same thing?
If not a single command, what other choices do I have?

I use Arduino  micro,  UNO,  but I think the question might be valid for most Arduino

Yes, the ports of an Uno are addressed in C/C++ as PORTB, PORTC, and PORTD respectively, each 8 bits wide. You can read them or assign to them. Other processors' ports have similar names. Of course the pins' port assignments and functions differ from one to the other, which is one reason for providing the single-pin pinMode() and digitalRead(), digitalWrite() functions. But where you need to deal directly with the hardware (and probably don't care about chip-to-chip portability), the registers are exposed with the above symbols.

Also note that most other CPU registers are exposed the same way - the ports' data-direction registers as DDRA, DDRB, DDRC. You may not care about setting them up simultaneously, but if you wanted to make all of your hardware accesses similarly (and save the flash space for the portable pin functions), you could.

Update:

  Is there a specific command I can use ? Such as Write PortD ?

Yes, you can use the PORTx names like any other C/C++ variable:
PORTD = 0xFF;
PORTD ^= 0x02;
if( (PORTD & 0x40) != 0 ){, for just a couple of examples - just like real C! :-)

PS: Pighixxx makes absolutely top-notch pinout diagrams for boards & processors. Here is his diagram for the 28-pin DIP-packaged AtMega328p for instance. They're extremely useful when you're working with a chip at the port or board level.


Compile Error for Arduino Sketch I am attempting to increase the volume of a Max9744 20 watt amplifier from Adafruit using an Arduino sketch. I am just a very beginner and working with my grandson, this may be more than I am capable of doing.

Our project is to have music play when a sensor determines a door is opened.

I wonder if someone can help with this compile error.  I stripped the code of any code not related to issue - basically the sensor code.

Thanks in advance for any help you can provide.

exit status 1
'VS1053_CONTROL_SPI_SETTING' was not declared in this scope

Here is the code

#include <SPI.h>[code][/code]
#include <Adafruit_VS1053.h>
#include <SD.h>
#include <Wire.h> // Amp Code

#define BREAKOUT_RESET 9 // VS1053 reset pin (output)
#define BREAKOUT_CS 10 // VS1053 chip select pin (output)
#define BREAKOUT_DCS 8 // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET -1 // VS1053 reset pin (unused!)
#define SHIELD_CS 7 // VS1053 chip select pin (output)
#define SHIELD_DCS 6 // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4 // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3 // VS1053 Data request, ideally an Interrupt pin

#define MAX9744_I2CADDR 0x4B

int8_t thevol = 63; // I want Max Volume Always

Adafruit_VS1053_FilePlayer musicPlayer =
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

void setup() {
SD.begin(CARDCS);

Wire.begin();
if (! setvolume(thevol)) {
Serial.println("Failed to set volume, MAX9744 not found!");
while (1);
}
}

boolean setvolume(int8_t v) {
// cant be higher than 63 or lower than 0
if (v > 63) v = 63;
if (v < 0) v = 0;

Serial.print("Setting volume to ");
Serial.println(v);
Wire.beginTransmission(MAX9744_I2CADDR);
Wire.write(v);
if (Wire.endTransmission() == 0)
return true;
else
return false;
}
void Adafruit_VS1053::setVolume(uint8_t left, uint8_t right) {
uint16_t v;
v = left;
v <<= 8;
v |= right;

noInterrupts(); //cli();
sciWrite(VS1053_REG_VOLUME, v);
interrupts(); //sei();
}

void Adafruit_VS1053::sciWrite(uint8_t addr, uint16_t data) {
#ifdef SPI_HAS_TRANSACTION
if (useHardwareSPI) SPI.beginTransaction(VS1053_CONTROL_SPI_SETTING);
#endif
digitalWrite(_cs, LOW);
spiwrite(VS1053_SCI_WRITE);
spiwrite(addr);
spiwrite(data >> 8);
spiwrite(data & 0xFF);
digitalWrite(_cs, HIGH);
#ifdef SPI_HAS_TRANSACTION
if (useHardwareSPI) SPI.endTransaction();
#endif
}
void loop() {

while (counter < 3) {
musicPlayer.begin();
Serial.println(F("Playing track 001"));
musicPlayer.playFullFile("track001.mp3");
delay (100);
}

delay(1000);

musicPlayer.stopped();
}

The functions Adafruit_VS1053::sciWrite and Adafruit_VS1053::setVolume are functions from the library. They are in the Adafruit_VS1053.cpp file.

You should not copy those functions to your own sketch.

The library has a few examples. Try to stay close to those examples.


CIPSEND to ESP8266 returning bytes but no content I am trying to send a GET request from an Arduino Uno connected to an ESP8266 through SoftwareSerial. I can't get it working directly in the code so I've stripped it down to a script that passes serial monitor queries like so:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266 (rxPin, txPin);

void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200);
  delay(1000);
}

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

I setup and connect the ESP8266 to my router like so from the serial monitor:

AT+RST
AT+CWMODE=3
AT+CWJAP="rwifi name","wifi password"
AT+CIFSR
AT+CIPMUX=0
AT+CIPSTART="TCP","www.abcdefg.com",80
AT+CIPSEND=61
GET /in-progress/ab/i.php?c=20 HTTP/1.0 Host: www.abcdefg.com

Everything works fine up until the CIPSEND, the GET request part, and the serial monitor output the following:

AT+CIPSEND=61

OK
> i.php?c=20 HTTP/1.0

busy s...
Recv 61 bytes
SEND OK

I know there is a 64 byte limit for the serial monitor. my GET is 61 bytes. I'm getting bytes back but not the content from the page (it should be the word "yes") and not even a content from a 404 page. Web side my php page is a counter that adds 1 to a number in a txt file - it doesn't increment (it does work if I call it from the web browser).

Where I am going wrong here with my CIPSEND? It looks like it is correctly formed to me.

-----edit-----

Based on comments below this is the latest GET request I have tried:

AT+CIPSEND=73
GET /i.php HTTP/1.1\r\nHost: www.abcdefg.com\r\nConnection: close\r\n\r\n

I have shortened my pathway to the php file as much as possible, added the carriage returns and newlines between request and each header, added the double carriage return and newline at the end. The request now returns +IPD,919:HTTP/1.1 400 Bad Request. This error 400 is not logged on my website.

In my experience, the "busy" message appears when you try to start a new AT command or to send data before the ESP8266 is ready. You say that you are running this test with the commands in "a script" which suggests to me that there is no significant delay between lines.

You should either wait between commands until the EXP8266 responds (usually with "OK" or ">") or add a delay of a few seconds between commands.


How to determine what resistor value to use for LED strip I'm trying to use an ESP8266 powered by my computer through USB cable to control a WS2812B LED strip. I've read online that you're supposed to put a resistor before the data channel to help prevent noise but I'm struggling to figure out what the resistor value should be.
I've figured out so far that the LED strip will use a MAXIMUM of 25.8W and that the Vin pin that is powering the LED strip is outputting 5V. I also plan on putting a 470uF capacitor across power and ground.

It seems like people generally just use a resistor around 300 - 500 ohms so I'll just use a 500 ohm resistor. Answer found on another thread. And here as well.


How many clients can connect to an ESP32? I am using an ESP32 as my master and 10 ESP8266-07s are connected to the master that is in AP mode.

But I need at least 12 clients.
Please help me to increase the number of clients the ESP32 can handle in AP mode.

I have read this article but it did not help me
ESP32 AP max connections: 4 or 10?

The SDK API documentation from Espressif directly notes:

uint8_t max_connection
Max number of stations allowed to connect in, default 4, max 4

EDIT
However, another area of the API documentation (The API Guide) notes:

max_connection
Currently, ESP32 Wi-Fi supports up to 10 Wi-Fi connections. If
max_connection > 10, soft-AP defaults the value to 10.


Can I switch from Arduino IDE to Atmel studio or Visual Micro but still use Arduino library? If switch from Arduino IDE to Atmel studio or Visual Micro, how to use existing Arduino library?

Library serves important function of 'packaging' real and complex hardware (like NRF24L01 radio board) into functions of 'relatively standard format', like radio.init, radio.write, radio.read, radio.on, etc.

This allows user to easily use the hardware without reading the data sheet.

How can the same be achieved under Atmel studio?

At the end of the day, an Arduino library and the Arduino core are just files full of code.

There is nothing to stop you creating a project in Atmel studio (or wherever) and importing all those files into your project.

You will need all the core files (hardware/arduino/core/arduino/*) plus all the files for the libraries you want to use.


why there is 4 ground in l293d? I am using L293d motor driver to drive 2 motors simutaniusly in several direction.

But I am not shure why there is 2 Vcc and 4 GND in this IC.

Can anyone tell explain it?

Thank You...

It's explain in the datasheet.

  A VCC1 terminal, separate from VCC2, is provided for the logic inputs to minimize device power dissipation. (pg. 2)

VCC1 is for the logic and VCC2 is for the motor supply.

The four grounds are all tied together internally and act as a heatsink for the chip. (pg. 11)


Unpredictable behavior on parsing key-value delimited input from serial I am having trouble with a "simple" command parser; I'm guessing I'm doing something wrong with memory allocation - appreciate any pointers :)

For context: I'm running on an Arduino Uno (if it matters). The commands I expect are of the form <key1=value1;key2=value2;key3=value3>. For simplicity here (as well as for my own failed attempts at debugging), I've removed everything extraneous, so that this code just prints back to the serial monitor whatever the current value associated with the key "text" is every time a command enclosed in < > is encountered.

This seems to work correctly until after the first time the key is found; then it behaves somewhat unpredictably - haven't yet been able to discern the pattern.  But, for instance, if I send:

<a=5>
-> EMPTY
<b=7;text=here;d=9>
-> here
<d=abc>
-> here
<d=ghi;e=afds>
-> afds

That last displayed value is wrong, since no new key of text was sent over serial. The complete code is here:

// command indicators
char START_MARKER = '<';
char END_MARKER = '>';

const int MAX_KEY_VALUE_PAIRS = 3;  // maximum number of key-value pairs in message
const int MAX_ELEMENT_CHARS = 25;  // the maximum number of characters (+1 for terminator) in a key or a value

// message format: <key1=value1;key2=value2;key3=value3>
const int MAX_MESSAGE_CHARS = (MAX_KEY_VALUE_PAIRS * (MAX_ELEMENT_CHARS + 1)) * 2 + (MAX_KEY_VALUE_PAIRS - 1) + 2;  // maximum message size

char received_chars[MAX_MESSAGE_CHARS];  // <- EDIT#1
char received_chars[30] ={'\0'};
bool new_data = false;

char *text;  // the value identified by the "text" keyword, i.e.: in <text=abc;time=814a>, text would be abc.

void ParseData(char *str) {
  // This picks off the ;-delimited key-value pairs and assigns them to a multi-dim array
  char * pch;
  int pairs_count = 0;
  char config[MAX_KEY_VALUE_PAIRS][2][MAX_ELEMENT_CHARS];

  pch = strtok(str, "=");

  while (pch != NULL)
  {
    strcpy(config[pairs_count][0], pch);
    pch = strtok(NULL, ";");
    if (pch == NULL) break;

    strcpy(config[pairs_count][1], pch);
    pairs_count++;
    pch = strtok(NULL, "=");
    if (pch == NULL) break;
  }

  for(int i=0;i<pairs_count;i++) {
    if (strcmp(config[i][0], "text")==0) text = config[i][1];
  }
  Serial.println(text);
}

void ReadSerial(){
  // After calling ReceiveText to empty the buffer, if a complete command has been found,
  // parse that command.
  new_data = ReceiveText();
  if (new_data == true) {
    char temp_chars[MAX_MESSAGE_CHARS];  // temporary array for use when parsing
    strcpy(temp_chars, received_chars);
    received_chars[0] = '\0';  // <- EDIT#2
    ParseData(temp_chars);
  }
}

boolean ReceiveText() {
  // This dumps the characters on the buffer so far received_chars, searching for an END_MARKER
  // along the way; if it finds one, it goes back to find a START_MARKER; if that is also found,
  // the string within is the ;-delimited set of key value pairs
  static boolean recv_in_progress = false;
  static byte ndx = 0;
  char rc;

  boolean new_data = false;
  while (Serial.available() > 0 && new_data == false) {
    rc = Serial.read();

    if (recv_in_progress == true) {
      if (rc != END_MARKER) {
        received_chars[ndx] = rc;
        ndx++;
        if (ndx >= MAX_MESSAGE_CHARS) {
          ndx = MAX_MESSAGE_CHARS - 1;
        }
      } else {
        received_chars[ndx] = '\0'; // terminate the string
        recv_in_progress = false;
        ndx = 0;
        new_data = true;
      }
    } else if (rc == START_MARKER) {
        recv_in_progress = true;
    }
  }
  return new_data;
}

void setup() {
  Serial.begin(9600);
  text = (char*)malloc(25);
  strcpy(text, "EMPTY");
  received_chars[0] = '\0';
}

void loop() {
  ReadSerial();
}

Thanks!

Welcome to the I forgot to empty my buffer char club (I lost some days finding a simlar problem)

 strcpy(temp_chars, received_chars)  // strcpy empties temp_chars and adds the received_chars

but you have no (for me) visible routine to empty received_chars
Do this either by setting

received_chars[0] ='\0'; // set the pointer to first index

or

 received_chars ="0";

or

strcpy(received_chars,"0");

after you used the buffer content. By using

static byte ndx = 0;

you just set the pointer and then start to write, as a safequard you should first reset the end terminator and then start to write. This is probably the reason you see characters even if no key is pressed due to a still "full" charbuffer.To prevent heap corruption define your received_chars as a fixed arraybefore setup:

char received_chars[128] ={'\0'}; // 127 chars + terminator

if you use malloc you have to use free, but doing that with a lot of dynamic data causes heap fracturing -> crash in the end

EDIT
The program does now the following

ignores all char not enclosed by <>
check for text and displays everything after = and before;
ignores everything after ; if its not text= again
if its text= again ignores the first and only displays the second param

You do not need strtok here as it deletes chars I use a modified substring routne for char arrays.
Here is the code working as described above:

// command indicators
const char START_MARKER = '<';
const char END_MARKER = '>';

const uint8_t MAX_KEY_VALUE_PAIRS = 3;  // maximum number of key-value pairs in message
const uint8_t MAX_ELEMENT_CHARS = 25;  // the maximum number of characters (+1 for terminator) in a key or a value

// message format: <key1=value1;key2=value2;key3=value3>
const uint8_t MAX_MESSAGE_CHARS = (MAX_KEY_VALUE_PAIRS * (MAX_ELEMENT_CHARS + 1)) * 2 + (MAX_KEY_VALUE_PAIRS - 1) + 2;  // maximum message size

//char received_chars[MAX_MESSAGE_CHARS] = {'\0'};// <- EDIT#1
char received_chars[256] = {'\0'};
bool new_data = false;
char text[25] =  {'\0'};      // the value identified by the "text" keyword, i.e.: in <text=abc;time=814a>, text would be abc.

void ParseData(char *str) {
  // This picks off the ;-delimited key-value pairs and assigns them to a multi-dim array
  char * pch;
  int pairs_count = 0;
  char config[MAX_KEY_VALUE_PAIRS][2][MAX_ELEMENT_CHARS];

  pch = strtok(str, "=");

  while (pch != NULL)  {
    strcpy(config[pairs_count][0], pch);
    pch = strtok(NULL, ";");
    if (pch == NULL) break;

    strcpy(config[pairs_count][1], pch);
    pairs_count++;
    pch = strtok(NULL, "=");
    if (pch == NULL) break;
  }

  for (uint8_t i = 0; i < pairs_count; i++) {
    if (strcmp(config[i][0], "text") == 0) strcpy (text,config[i][1]);
  }
  Serial.println(text);
}

void ReadSerial() {
  // After calling ReceiveText to empty the buffer, if a complete command has been found,
  // parse that command.
  new_data = ReceiveText();
  if (new_data == true) {
    char temp_chars[MAX_MESSAGE_CHARS];  // temporary array for use when parsing
    strcpy(temp_chars, received_chars);
    received_chars[0] = '\0';  // <- EDIT#2
    ParseData(temp_chars);
  }
}

bool ReceiveText() {
  // This dumps the characters on the buffer so far received_chars, searching for an END_MARKER
  // along the way; if it finds one, it goes back to find a START_MARKER; if that is also found,
  // the string within is the ;-delimited set of key value pairs
  static boolean recv_in_progress = false;
  static byte ndx = 0;
  char rc;

  bool new_data = false;
  while (Serial.available() > 0 && new_data == false) {
    rc = Serial.read();

    if (recv_in_progress == true) {
      if (rc != END_MARKER) {
        received_chars[ndx] = rc;
        ndx++;
        if (ndx >= MAX_MESSAGE_CHARS) {
          ndx = MAX_MESSAGE_CHARS - 1;
        }
      } else {
        received_chars[ndx] = '\0'; // terminate the string
        recv_in_progress = false;
        ndx = 0;
        new_data = true;
      }
    } else if (rc == START_MARKER) {
      recv_in_progress = true;
    }
  }
  return new_data;
}

void setup() {
  Serial.begin(115200);
   strcpy (text, "EMPTY");
 //  text = (char*)malloc(25);
//  received_chars[0] = '\0';
}

void loop() {
  ReadSerial();
}

If you could describe what you really want in the end I'm sure we can help with some basic routines.


How the light brightness stays constant when we increase the frequency of stroboscope Well I am trying to make a Stroboscop. I found this code at blow: and tried. It works normally. But if I increase the RPM so decrease the "strobeDelay" time, the brightness of the LEDs goes out. Even if I try the GreatScott code. The same problem persists at high RPM. I am using power LED.
On the other hand there is a stroboscop which is Fluke 820, it says

Features high-intensity 7-LED array—4,800 Lux @ 6,000 FPM/30cm

How they achieve that constant brightness under the high frequency?
    // Gray text are just helpful comments, you don’t need to type them. :)

/******* -----=====!! EASY STUFF TO MESS WITH !!=====------ ******/

  // What analog pin should we use to read the value from the potentiometer?
  int analogPin = 2; // Yep, you heard right: The coolest of the Analog pins...

  // What pin is the LED connected to?
  int ledPin = 13; // Contains a built in resistor!

  // How much time should the light stay on between delays, in Microseconds (millionths of a second)?
    /* Big number = more blur, more perceived brightness
     * Small number = less blur, less perceived brightness  */
  long onTime = 250;

  // What should the minimum delay be in milliseconds (thousandths of a second)?
  // This sets the bottom delay range of the strobe, as a delay of 0 doesn't actually flash =P
  // The strobe starts with this as the "fastest" mode, and goes slower from there, adding to the delay
  int minDelay = 1; // 1 is the lowest we can actually do without a better delay function

  // What should the maximum delay be in milliseconds?
  // This is the longest time that the biggest potentiometer value will be mapped to, and longest
  // time between strobe flashes.
  int maxDelay = 100;

/******* -----=====^^ EASY STUFF TO MESS WITH ^^=====------ ******/

// Initialize the number to hold our strobe delay. Isn't used till we get to the main loop
long strobeDelay = 0;

void setup() {
 pinMode(ledPin, OUTPUT); // Setup ledPin as an output.
}

void loop() {
  // To make the math easier, we use map(value, fromMin, fromMax, toMin, toMax) to convert the
  // 0 to 1023 range we get from analogRead, into our strobe delay range of 1 to 100 :D
  strobeDelay = map(analogRead(analogPin), 0, 1023, minDelay, maxDelay);

  digitalWrite(ledPin, HIGH); // Switch the ledPin to HIGH, turn it on!
  delayMicroseconds(onTime); // Delay while on, for the given onTime.
  digitalWrite(ledPin, LOW); // Switch the ledPin to LOW, turn if off!
  delay(strobeDelay); // Delay while off, for given strobeDelay.
}

For those who wonder there is a video, but another brand same result, brightness constant even if RPM changes. I tried 2 different power LED. on of them is this, the other LED is I found in a broken projector, I used them 2 working strip. No doubt in your mind, this led strip is very bright at low frequency. Both of them same result like this:

To keep the same brightness, you have to keep the same duty cycle (percent of on time over off time).  So to change the rate without changing the brightness, you have to increase
delayMicroseconds(onTime) by the same percent you increase delay(strobeDelay).  But note that as you go slower, the on time will be too long to freeze the motion you are trying to study.  (If it's just for a party effect this may not matter.)


Using Serial as boolean function argument The following program compiles in the Arduino IDE.

void doSomething(bool) {}

void setup() {
  doSomething(Serial);
}

void loop() {}

But, as expected, this one doesn't:

class MyClass {};

void doSomething(bool) {}

void setup() {
  MyClass myClass;
  doSomething(myClass);
}

void loop() {}

The compiler returns the error cannot convert 'MyClass' to 'bool' for argument '1' to 'void doSomething(bool)'

Why is it possible to compile the former? Isn't Serial a normal class instance (of HardwareSerial)? Does it makes any sense to interpret Serial as a bool?

HardwareSerial defines operator bool(), which allows it to be used in a boolean context.


Can I program an ATtiny87 with Arduino I have a project, and I want to use an ATtiny167(ATtiny87), I know that an Arduino can progam ATtiny84 (84/44/24), ATtiny85 (85/45/25), and ATtiny2313 (4313). but I don't know if it can program an ATtiny87?

thank you for your help.

There is a json for ATtiny 167 at https://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips

So add that json to your preferenses.


How can I add some additional 5 volt power I have an Arduino which is being powered by a 9v, 2 amp power supply.  I have about 20 relays which are powered by 5 volts each.  I do not want to over work the voltage regulator on the board, so I would like to add another (possible 2) 5 volt regulator that I bought on amazon.  I am planning to:

Connect the regulators VIN to the Arduino's vcc (9 volt)
Connect the regulator's GND to the Arduino's GND.
Connect the regulator's VOUT to the Relay's VCC

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Absolutely. But don't daisy-chain the regulator to each supply input in turn, connect each one separately directly from the regulator.

  Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

It is not advisable. Small manufacturing differences between regulators can result in them outputting slightly different voltages, which will lead to destruction of hardware.


Make lights come on and off depending on which button is pressed Imagine a strip of LEDs with O being HIGH and X being LOW.

X O X O X

Now if I pressed the button below the second O and wanted it to switch the last two LEDs (4th one to LOW and 5th to HIGH or any opposite value of what it was), but if I pressed the first X wanted it to switch that one HIGH, the second one LOW, and the third HIGH.

I want to continue this type of pattern where each button press will result in two or three of the LEDs changing their effective state.

How might I achieve this? I have researched using the modulo function and can only get it to work every other click of a button. I have also tried using a pullup function and couldn't get it to work at all.

Can someone please just point me in the right direction?

Can someone please just point me in the right direction?

what is "right" is highly subjective. I would consider a good solution to be one where the functionalities desired is broken down into natural modules that are then integrated to perform the desired functions. By that (highly subjective) standard, the solution posted earlier would be a poor one -> due to its tightly coupled / inter-mingled approach.

if I were to take a shot at this, I would consider the implementation below:

  key_state = read_keys(); //read keys / buttons, with or without debouncing
  led_process(key_state);  //process the key_state, and light up / off leds based on key_state

Essentially, you scan the keys / buttons, and based on that, turn on / off the leds.

All you need to do after that is to implement the individual functions based on your particular hardware design, or even software approaches: for example, read_keys() can be implemented in the isr, as can led_process().

A solution like this is highly portable: it works on pretty much anything that supports a C compiler, and is implementation-independent: the logic holds true, and all you do is to change the two functions to perform different kinds of lighting.

To me, modulizing your code is a huge advantage for a high-level language like C, and vital in taking on a real life project of moderate complexity.


L298N Motor Driver with Nodemcu/ESP32 I have seen a lot tutorials on L298N motor driver with nodemcu and ESP 32, which are 3.3v logic boards where the motordriver is a 5v logic board, now in Arduino while doing speed control 255 means 5v or even a high means 5v but in nodemcu/ESP32 this means 3.3v, so my question is how it will work ?

It's not a question of voltage. You make a basic mis-assumption:

in Arduino while doing speed control 255 means 5v

No, it doesn't.  255 means "Provide a logic HIGH signal all the time".
128 means "Provide a logic HIGH signal 50% of the time".
The 255 (or whatever number) is the "duty cycle" of a PWM signal. That is a digital signal that can be LOW or HIGH which is switching on or off rapidly. The duty cycle defines the ratio of ON time to OFF time.
You're not providing a voltage - you're providing an ON/OFF signal.
As long as the HIGH voltage of that signal is above the threshold of the receiving device (the L298N in this case) then it will see it as an ON/OFF signal.
According to the datasheet for the L298 the HIGH logic threshold (VIH) is 2.3V. That means anything above 2.3V is seen as ON and anyting below that is seen as OFF (actually there is hysteresis, so it has to drop below 1.5V to switch to OFF).
So your 3.3V from the NodeMCU is above that ON threshold, so the ON/OFF PWM signal is received properly as such.
Incidentally, it's because of this PWM signal that motors make a whining sound when they start up slowly. Because of this most proper motor drivers run the PWM at above 25kHz instead of the 500-ish Hz of the Arduino, so that whine is above the threshold of human hearing.


Capacitive sensor MPR121 on Arduino Uno—how many will work? I need to attach several capacitive sensors MPR121 with each of them using all of its 12 electrodes to an Arduino Uno.

Could you please tell me, how many will work with the voltage and current Arduino Uno supplies?

The answer is 4 regardless of the current consumption.

You can have 4 MPR121 devices on an I2C bus (by connecting the ADDR pin to the right place to select 1 of 4 addresses), and the Uno has one I2C bus - so that means 4 devices.

You could use software I2C to add more devices on other pins, but that's slow and clunky.

But that aside, if you used something to increase the number of I2C buses available, according to the datasheet the peak current consumption is 1mA during sampling, and assuming 300mA maximum for the Arduino's 3.3V regulator, that would mean a maximum of 300 MPR121 connected to the Arduino.  Note that, if you could actually get to the Arduino amongst that tangle of wires, you'd find it getting rather hot...


Nrf24l01 smd pcb placement tips I am working on pcb design with nrf24l01 smd. I have read somewhere that nrf24l01 module has problem while communication when it is placed with its antenna within the pcb. I want my module to be within the pcb as much as possible to save some space. I will be making the pcb at home and will be placing atmega 328p smd on the opposite layer. Should I fill the opposite layer with ground pad?

You need to keep the ground plane away from the antenna. The rest of the module doesn't care (and having a ground plane under it can help with unwanted EMI).
Here's a design I did recently for a customer with the same module in it. It's placed near the edge of the PCB with the ground plane cut out around the antenna:

That layout is actually set up for either the small SMD, the SMD with PA+LNB or the thorugh-hole version. The important thing is that there is a nice big exclusion zone in the ground plane where the antenna is.


Basic Question - ESP8266 Board Pins I have an embarrassingly simple question.

My experience to date has been limited to Arduino Uno + Wifi101.  I bought an ESP8266 and noticed that the GPIO pins don't match the printed numbers on the board.

When programming and defining pins, does #define <pin name> 16 call the pin with the printed designation D0?

I can't find a straight answer to this anywhere.

Image credit: http://crufti.com/content/images/2015/11/nodemcudevkit_v1-0_io.jpg

Looks like you're using https://github.com/esp8266/Arduino, in which case - yes, 16 is GPIO16, which on the NodeMCU board you have is labeled D0.
I am not entirely sure why the NodeMCU guys had to do this "pin remapping", but the end result is inconvenience when using the module with anything but their Lua.


Arduino unable to read from XBee Series 2 An XBee Series 2 is set to Router AT whose TX and RX pins are connected to an Arduino Nano's Rx and Tx pins respectively. The Arduino is connected to a Mac OSX via USB.

A second XBee Series 2 is connected to a Windows system via USB. It is set to Coordinator API mode.

Using the sketch below on the Arduino, a packet is sent from the Router AT XBee to the Coordinator API XBee, which is seen by XCTU as a Explicit RX frame. However the Arduino LED should blink once if it received a reply packet (should it?)

On another test, I wrote a script to send a frame for the Coordinator API XBee to send to the Router AT XBee. Once again the Arduino LED does not blink, and nothing is seen using Arduino's Serial Monitor.

Testing the Coordinator API XBee

Using the same script to send a packet from Coordinator API XBee to itself, the packet was received as well as a delivery confirmation packet. This shows that both the Coordinator API XBee and the script are working.

// Delivery confirmation
received:  { type: 144,
  remote64: '0013a20040a74613',
  remote16: '0000',
  receiveOptions: 1,
  data: [ 116 ] }

// Received the packet sent to itself
received:  { type: 139,
  id: 1,
  remote16: '0000',
  transmitRetryCount: 0,
  deliveryStatus: 0,
  discoveryStatus: 0 }

Testing the Arduino Sketch Code

Using the same Arduino sketch which continuously sends API frames to the Coordinator, I connected the Router AT XBee's RX pin to Arduino's RX pin, so the frames the Arduino are sending out are going back into its RX pin.

This causes the Arduino's LED to light up! So there is nothing wrong with the code.

Problem: Does this mean the Router AT XBee is not configured properly? I do not think its TX pin is damaged because XCTU can still read the settings off this XBee. Any ideas on how we can troubleshoot this?

Arduino Sketch (Connected to Router Xbee)

#include <XBee.h>

XBee xbee = XBee();
uint8_t payload[] = { 0, 0 };

// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40a74613);
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

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

    Serial.begin(9600);
    xbee.setSerial(Serial);
}

void loop() {
    xbee.send(zbTx);
    delay(1000);

    xbee.readPacket();
    if (xbee.getResponse().isAvailable()) {
        // Response received, blink LED once
        Serial.println('resposne!');
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
}

As I mentioned in my comments to your question, if you are using this library
then it doesn't actually support AT mode. In fact, AT mode (otherwise known as Transparent Mode) is simply attached to the Serial port and accessed directly through the Serial object.

Example: put this into your Arduino attached to the AT Router.

#define LED 13

void setup() {
    pinMode(LED, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(previous != millis()/1000){
    previous = millis()/1000;
    char buffer[5];
    sprintf(buffer,"%04i",previous);
    Serial.println(buffer);
   digitalWrite(LED, !digitalRead(LED));
  }
}

Then open the console on the XCTU software on the API Coordinator watch the packets.

You will see above the received packets from the router. Because the coordinator is in API mode, you see it like this. (In AT mode, you will see the raw packets.

Ichose numbers to send because they are easy to read in this form. Packet 0102 appears in the packets data as 30 31 30 32 0D 0A

In AT mode there is no packet confirmation, validations, status or anything. They are all handled "transparently".

As a side note, I've seen many references that both XBees need to be in the same mode. That is, in fact, incorrect. If we modify our source to include Serial.read you would see data the other way as well.

edit: I thought I would add communications between AT Router and API Coordinator. I have modified the code in the Router to receive a constructed packet from the Coordinator via the XCTU software.

#define LED 13

boolean serialComplete = false;
char bufferIn[64];
char bufferOut[5];
int count=0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(serialComplete) {
    Serial.println(bufferIn);
    serialComplete=false;
    count = 0;
    memset(bufferIn,0,sizeof(bufferIn));
    digitalWrite(LED,!digitalRead(LED));
  }
  if(previous != millis()/1000){
    previous = millis()/1000;
    sprintf(bufferOut,"%04u",(uint16_t)previous);
    Serial.println(bufferOut);
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n' || inChar == '\0') {
      bufferIn[count++]=0;
      serialComplete = true;
    } else {
      bufferIn[count++] = inChar;
    }
  }
}

Then in XCTU construct a packet for the Coordinator. I'm using version 6.1.0.

and click "the create frame using form generator tool"

here is the packet being received by the router. I am only sending 9999 nul terminated.

Then once the pair are running, you can send the constructed packet from the XCTU software and it will be received by the router.


Fail uploading any sketch to ATtiny85 USB I have a Digistump's ATtiny85 (probably a clone ), which fails uploading any sketch, saying: Warning: device with unknown new version of Micronucleus detected. This tool doesn't know how to upload to this new device. Updates may be available. I'm using Ubuntu 20.04 and Arduino IDE 1.8.13.
I used these guides:

Digistump's troubleshooting for linux

Kovo's blog

After using these guides, finally I stop getting this error, but when trying to upload the firmware ( last line at Kovo's ), I get this error:
`guy@desktop:~/tmp/micronucleus/upgrade$ ~/.arduino15/packages/digistump/tools/micronucleus/2.0a4/launcher -cdigispark  --timeout 60 -Uflash:w:~/tmp/micronucleus/upgrade/t85_default.hex:i
Running Digispark Uploader...
Plug in device now... (will timeout in 60 seconds)
> Please plug in the device (will time out in 60 seconds) ...
> Device is found!
connecting: 16% complete
connecting: 22% complete
connecting: 28% complete
connecting: 33% complete
> Device has firmware version 2.4
> Device signature: 0x1e930b
> Available space for user applications: 6522 bytes
> Suggested sleep time between sending pages: 7ms
> Whole page count: 102  page size: 64
> Erase function sleep duration: 714ms
parsing: 50% complete
> Program file is 1594 bytes too big for the bootloader!

Did someone encounter this ?

from Daves Comment
need to download upgrade-t85.hex (which is not t85_default.hex) from link


Arduino with using Adafruit NeoPixel library set one color, fade random pixels in strip on and off So I am trying to get random pixels to fade on and off at one color. I want to create a power moving inside an item effect.  I have several examples of the whole strip fading in and out, but cant seem to nail down how to fade random pixels on and off at different intervals.  I want to have some on and some off, some fading out while others fading in, all on different LEDs at different times.  Can this be done?

You simply have to treat each pixel individually.

Pick a pixel
Add it to a fade list
Fade all the pixels in the list by a step
Remove pixels which are below some threshold
Repeat

How you do those things like picking the pixel is up to you. You'll probably want to brighten some as well, using a similar algorithm.


Regarding Arduino Mega hardware serial I have a doubt interfacing with fingerprint module (R305) with the Arduino Mega.
I have been able to interface it to Arduino Uno before but not Arduino Mega so far.

I have used the Mega's hardware Serial1 pins 19 (Rx) and 18 (Tx) pins.

However, I am unable to get output from the module. How do I connect hardware serial and what is a sketch to do this?

Try Pin digital pins 0 (RX) and 1 (TX), as they also should be Serial0 on ArduinoMega (PWM 0 and 1)

see:
https://www.arduino.cc/en/Reference/Serial

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega's USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your device's TX pin, and the ground of your Mega to your device's ground.


DC motor with slow speed to actuate mirrors I am thinking to use Arduino to control a DC motor and apply a small torque to move the mirrors of my interferometer experiment. I have the components from the Arduino Starter Kit K000007, just to understand how it works because I am approaching it just now.
The mirror mount has a knob with a 2mm Hex hole and each revolution corresponds to a displacement of 50 microns: I would need a speed around 1/50 revolution/second, or even less. Is it possible to move the motor that slow?
Moreover, I should use a coupler to interface the motor with the knob, basically some joint to connect the shaft to a 2mm Hex bar or something: could you suggest a way to do so?

DC motors are made for spinning. Trying to spin it in sub full revolution steps is not really possible. But you can use a geared DC motor, where the rotor after the gear is slow enough for your purpose. Also this can give you enough torque for moving the knob (since small DC motors are often rather weak by their own). You can find geared DC motors with many different values (torque, voltage, speed, gear ratio, size...) at the typical online sellers. The small ones are rather cheap, so you might just buy some and test out, whats fitting for you. Otherwise you would need to set exact requirements for torque and speed (and maybe other parameters) and then search for a fitting one.
Also keep in mind, that you need something like a driver circuit for the motor. Since you will want to drive it in both directions, a H-bridge is needed. You can build those yourself with transistors, or buy a small chip, which incorporates the complete H-bridge (make sure to use one with MOSFETs in it, since they are more efficient). Also don't forget the flyback diode to avoid killing the electronics with the induction voltage from the motor.

I should use a coupler to interface the motor with the knob, basically some joint to connect the shaft to a 2mm Hex bar or something: could you suggest a way to do so?

Yes, you need some kind of coupler. But we cannot really suggest something here. It depends totally on your exact setup. This mechanical part will be something, that you have to design. There are different kinds of couplers available online, but I don't know, if they are good for your purpose.
Also maybe you should make sure to make the coupler flexible on the other axes than the rotation axis. That way the motor will not stall when a small disalignment happens, and the vibrations from the motor might not get transmitted to your mirror as much. I know this principle from my 3D printer, which uses a coupler like this one:


Arduino Zero D0/D1 set output high I am trying to use D0/D1 as normal IO pins but DigitalWrite does not work as on an Arduino UNO.

I know the SAMD21G has SERCOM but I can't seem to find an example of not using D0/D1 as an UART port.

EDIT ** Code I have tried:

#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
  REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
  delay(1000);
  REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
}

void loop() {
}

You can do this by simply calling the right registers:

Example 1, using a MASK

D0/D1 are mapped to to PA10 & PA11 on the M0

/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00

int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)

    while(1){

    }
}

Here is another simple example:

/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00
#define LED1 PORT_PA10
#define LED2 PORT_PA11
int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = LED1 | LED2; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = LED1 | LED2; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = LED1 | LED2; // set state of pin(s) to FALSE (LOW)
    while(1){

    }
}

In the Arduino IDE you can do something like:

#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
}

void loop() {
   REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
   delay(1000);
   REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
   delay(1000);
}


How to convert uint8 to int for maths operation in Arduino? I am receiving a string from my bluetooth terminal in uint8 format. I want to convert it to integer for further processing. How can I do this? I tried toInt() but it is not working. Please help.

Thanks in advance.

I am receiving a string from my bluetooth terminal in uint8 format. I want to convert it to integer for further processing. How can I do this? I tried toInt() but it is not working. Please help.

I am assuming that you are receiving to an uint8_t buffer and that it is correctly null terminated (i.e. zero as the last element).

Try this:

uint8_t buffer[BUFFER_MAX];
...
int num = atoi((const char*) buffer);

Cheers!


Measure the time between 2 inputs I am making a small project, and for that, I need to measure the time between 2 inputs.
basically, a program to measure the time elapsed from when digital pin 2 is high to when it again becomes high.

The way to go depends on the time range, that the event will have. The Arduino framework already includes a function for timekeeping: millis(). It returns the number of milliseconds since the startup (much like a clock) and measures the time via the hardware Timer0 and it's interrupts. This function will work good in the 2 digit millisecond range and above. With single digit millisecond or the microsecond domain, you should instead use micros() with works similar, but returns the microseconds since startup. For the low microsecond range and below you would need to work directly with a dedicated hardware timer, configuring it via its hardware registers.
Here I would show the principle of millis()/micros(), since that is most likely what you need. In the following I will only write millis(), but all the calculations can also be done with micros(). The only difference for the calculations is the factor 1000 between milli- and microseconds.
When you look at your watch and want to measure a time difference, you take note of the start time and the end time. Then you calculate the difference to get the event duration. You can do the same with millis():
unsigned long starttime = millis(); // take note of start time
// here the event to measure
unsigned long endtime = millis(); // take note of end time
unsigned long duration = endtime - starttime; // duration of the event in ms

So in your code you need to check for a rising edge of your signal. On every rising edge you calculate the time difference between the last timestamp and the current time. Then you reset the timestamp. Something like this:
int last_input_state = LOW;
unsigned long timestamp;

//setup here

void loop(){
    int current_input_state = digitalRead(2); // get current signal level
    if(current_input_state && !last_input_state){ //check, if signal is now high and was low before
        unsigned long current_time = millis(); // take note of the current time
        unsigned long duration = current_time - timestamp; // calculate the duration and do something with it
        timestamp = current_time; // update the timestamp with the current time
     }
     last_input_state = current_input_state; // update the last input state with the new measured one
}

Note:

This code is non-blocking. It needs to run fast and continuously to work correctly. You cannot do long blocking things in the rest of your code, like using high delay() calls, but you shouldn't do that either way, since that will block anything from going on.
You can go even further to lift the weight from your CPU and use an interrupt to sense the rising edge. You could use attachInterrupt(digitalPinToInterrupt(pin), service_function, RISING); and provide a void service_function(), which does the timestamp measurement and calculation (basically the same code as in the if statement of the code above).


Arduino time keeping using millis() is not accurate or correct? I have been using the Arduino to record some data. In my Arduino sketch I also used the millis() function so I can keep track of the time at which each value I am measuring is taken. However, I noticed that the timing isn't correct. For example 30 seconds in real life only comes out as 10 seconds (made up example).

Am I correct in saying that the Arduino delay function affects the time keeping using millis()? In other words suppose I have a delay of 50ms, does that mean the millis() function stops for that duration as well and then continues and so on for the duration of the connection? I noticed this when I tried plotting some data and finding that the frequency of the peaks in my data was too frequent given the time which had passed by. So I want to know if that is the reasoning for this mismatch of timing and if so, how do I fix this so that I can keep the time each sample occurs?

To give some context here is my sketch:

#include <eHealth.h>

unsigned long time;
// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);
}

// The loop routine runs over and over again forever:
void loop() {

  float ECG = eHealth.getECG();
  time = millis();
  Serial.print(time);
  Serial.print(" ");
  Serial.print(ECG, 5);
  Serial.println("");

  delay(50);
}

millis() is interrupt driven so delay() won't impact it, at least not on an ATmega based board.

That isn't to say that millis() is totally accurate either. Each tick of the timer is not exactly 1ms, but is 1.024ms. This error gradually accumulates until a correction is made. This can be seen in the implementation of the TIMER0_OVF (timer 0 overflow) interrupt handler.

Another source of inaccuracy is the oscillator/crystal itself, which is not exactly 16MHz. It is pretty close though, and as long as temperature doesn't change too much, is relatively stable.

The above means that you might be about 1ms out when using millis(). This doesn't sound like your problem.

Another potential issue would be what getECG() is doing - it might be very slow.

float eHealthClass::getECG(void)
    {
        float analog0;
        // Read from analogic in.
        analog0=analogRead(0);
        // binary to voltage conversion
        return analog0 = (float)analog0 * 5 / 1023.0;
    }

analogRead() is slow, but not so slow as to impact a loop like this.

Another problem I have seen people have is when they change the clock speed but don't correctly change boards.txt. This means that the constants used in the millis() implementation are wrong and the times are wrong.

If you actually want to read values every 50ms, a much better way of implementing this is to do the following

static long lastUpdate;

if (millis() - lastUpdate > 50)
{
    lastUpdate = millis();
    //Do stuff
}

We'd really need to see the timestamps you are getting. If you actually seeing 30s showing as 10s, then there is something else at work.


NodeMCU - Vin pin as 5V output? I know that Vin can be used to power the board but have also been reading that it can be used as a 5V output. Is it possible to assign Vin as an output as I would any other GPIO?

If I want to power an LED from GPIO 12, I would assign GPIO:

const int LEDpin_0 = 12; // D6, LED power pin

...and in the setup:

pinMode(LEDpin_0, OUTPUT);

I can then turn on and off the LED based on whether or not GPIO 12 goes HIGH or LOW.

Can I do the same with Vin without resorting to relays or other hardware?

There is confusion about what is and what isn't possible with this board. This is because there are different versions with different power arrangements.
NodeMCU 0.9
In this board the USB's 5V and the 5V pin are directly connected together. The combined result is then fed through a diode before entering the 3.3V voltage regulator.
With this arrangement the 5V pin will provide the exact same voltage that the USB port feeds the board. However it is dangerous to connect that pin to any power source - it may kill (or at the very least disable) the USB port in your computer - when the board is also connected to a computer through the USB port.
NodeMCU 1.0 and 1.1
On this version the USB's power is first fed through the diode and then to the 5V pin and the 3.3V regulator together.  This means that the 5V pin will show about 0.5V below whatever voltage is fed in through USB. This isolates the USB from the 5V pin so it becomes safe to provide power through the 5V pin whilst at the same time having the board plugged in to the computer - at the cost of having a slightly lower output from the 5V pin.

Original answer:
The VIN pin not directly connected to the USB's 5V supply (at least on the LoLin v3 board). this means the pin cannot be used as a 5V supply output.

You cannot control that voltage. It is always on, and always 5V (or whatever your USB port happens to provide - 4.75v - 5.25v).
You must never ever connect VIN to a power source and connect the USB socket. That can destroy the USB port in your computer. There is zero back-powering protection on that board.
Drawing more than 500mA from the VIN pin could cause the USB port of your computer to be shut down.


Arduino IDE Permision Denied For Upload, Ubuntu I am having issues uploading to my Arduino from the IDE on Ubuntu 18.04. The error message I have received is:

  Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Uno"
  avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied

I have checked other questions similiar to this one and have tried adding myself to the dialout group running:

sudo usermod -a -G dialout username

and added permission to write:

sudo chmod a+rw /dev/ttyUSB0

After, when I run:

ls -l /dev/ttyUSB0

I get:

crw-rw-rw- 1 username dialout 188, 0 jūl  2 16:09 /dev/ttyUSB0

However,I still get the same error message from the IDE.

Any help would be greatly appreciated!

As mentioned on the official guide for Linux, you need to run

sudo usermod -a -G dialout <username>

with the <username> replaced with the username of your system.
After running this, log out and log in and you should be good to go.


Problem with Arduino Uno and SIM900 shield logical communication (rx & tx) The logical communication(rx & tx) between the shield and Arduino Uno doesn't  work. Arduino (rx & tx) supply  is 0 & 5 V but this is 0 & 2.8 V. What am I to do?

Use a logic level converter.

A logic level converter is a small device that converts between different logic levels, for example between 5V and 3.3V.

I am not affiliated with Sparkfun, I just think they are the most informative source.


Adjust time calculation after Timer0 frequency change I have an Arduino Nano with an 328P and need all 6 PWM pins.

Thus, I had to adjust the prescaler and WGM Mode of Timer0.

It is now in phase correct PWM mode with a prescaler of 1.

TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);

Now I need a working time calculation for other libraries, but since
Timer0 had that duty everything is out of order now.

I tried adjusting the wiring.c

// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

to this

#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))

But it's like I didn't change anything.
(tested other settings that were changed so it was compiled anew )

Whole Code:

void setup() {

  // Set Timer 0, 1 and 2
  // Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
  // Register B: Pre Scaler to 1.
  TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
  TCCR0B = _BV(CS00);

  TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
  TCCR1B = _BV(CS10);

  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(CS20);

  pinMode(8, OUTPUT);

}
void loop() {

  digitalWrite(8, LOW);
  delay(65000);
  digitalWrite(8, HIGH);
  delay(65000);

}

Fixing the timekeeping functions with your PWM settings is not so
simple. You should at least try to rewrite ISR(TIMER0_OVF_vect),
micros(), and probably delay(). Here is why:

First, there is a rounding problem. Time is kept using two global
variables:

volatile unsigned long timer0_millis;
static unsigned char timer0_fract;

The first one is what millis() returns. The second one keeps track of
how much time has passed since the last full millisecond, and it does so
in units of 8 µs. The two variables are incremented by
ISR(TIMER0_OVF_vect) like this:

m += MILLIS_INC;  // temporary copy of timer0_millis
f += FRACT_INC;   // temporary copy of timer0_fract

On a normal Uno configuration, the ISR is called every 1024 µs.
Then MILLIS_INC is 1 and FRACT_INC is 3. With your timer
configuration, the ISR is called every 31.875 µs (510 cycles), then
MILLIS_INC should be 0 and FRACT_INC should be 3.984375. But since
we are dealing with integers, it will be rounded down to 3, and your
millis() will tick about 25% too slow.

A simple fix would be to

#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

in order for FRACT_INC to be 4 and millis() to be 0.4% too fast. Or
you could make timer0_fract a 16-bit variable and have it count clock
cycles, just to avoid this error. Either option should fix millis(),
but you still have a problem with micros().

micros() works by reading both timer0_overflow_count (incremented by
1 in the ISR) and the actual counter value. Since your counter is now
going alternatively up and down, it will be harder to compute a
microsecond count from these readings. Maybe you could take two
consecutive readings of the counter, just to know whether it is going up
or down...

And then there is delay(), which relies on micros(). If you fix
micros(), delay() should work fine. If not, You could rewrite
delay() to use millis() instead, which should be easy but you will
loose some accuracy.


Use of struct and sizeof in C for Arduino I am a newbie in C and I can not understand the point of using a structure in C. Could someone explain to me what is the point of defining a structure in C programming?

For example, this code(written in C for Arduino)

struct books
{
  char name[30];
  char author[30];
  int ID;
} Mybook, Yourbook;

void setup()
{
  Serial.begin(9600);
  // put your setup code here, to run once:
  strcpy(Mybook.name, "Girl in the train");

  strcpy(Yourbook.name, "Gone");

  Serial.print("Name of the book is:");
  Serial.println(Mybook.name);
  Serial.println((long)&(Mybook.name));
  Serial.println((long)&(Mybook));
  Serial.println((long)&Mybook);
  Serial.println(sizeof(Mybook));

  Serial.print("Name of the book is:");
  Serial.println(Yourbook.name);
  Serial.println((long)&Yourbook);
  Serial.println(sizeof(Yourbook));
}

Would use the same amount of memory as defining

char Mybookname[30];
char Yourbookname[30];

And you should type the same amount of lines.
So what is the point?

I have another question:

Why I get 62 for the sizeof(Mybook)? I have not defined it anywhere. Is it set automatically?

Consider the following:

void printBook(const books &theBook)
{
    Serial.println("Name of the book is: ");
    Serial.println(theBook.name);
    Serial.println("author is: ");
    Serial.println(theBook.author);
    Serial.println("ID is: ");
    Serial.println(theBook.ID);
}

void loop()
{
    printBook(MyBook);
    printBook(YourBook);
}

You should appreciate this avoids the code duplication you have in your
example.

  Why I get 62 for the sizeof(Mybook)?

30 bytes for name[30] (each char is one byte)
30 bytes for author[30]
2 bytes for ID (the AVRs have 16-bit ints)

No padding between the members because this architecture has no
alignment constraints.


Not detecting Arduino Mega 2560. It worked before but now not detecting I am using Windows 8.1 64 bit. I have an Arduino Mega 2560. I configured and installed it with the Merlin firmware before. I had a system format in between. I tried to connect my Arduino again.

I have the following problems:

Not detecting any hardware when plugging in the Arduino board: the green LED is on and the yellow LED is blinking. I checked the Device manager. It doesn't come in either COM ports or other devices. (The last time it came in COM ports as Arduino Uno). I installed legacy hardware on COM 3 (which was used before) and tried to update the driver from a newly downloaded version of Arduino. No success. I disabled the certification signature requirement from boot menu and tried: again no success.
The serial port on Arduino is greyed out.

I need some help. I am running out of ideas. I tried uninstalling COM port. I cleaned the registry with CCleaner. I uninstalled all Arduino software. I rebooted the system. I downloaded everything again, then connected the board. Still not detecting the new hardware. :P

Help me out.

What you said has happened to me before.This happened to me as I supplied over 20v to the arduino.Did you supply a higher voltage than recommended or pull too many amps from the board?If you did so,it is almost futile to try to repair it.


How To Get Data From Arduino Uno Onto My Laptop Through The USB I want to write a c++ program that does something with the data from one of the input analog pins as the program runs, but I want to know how to get the value from the arduino uno though the USB port (that I am also using to power the uno) and into my laptop for using. IS there any documentation I should read?

My laptop runs Ubuntu 18.04 if that matters.

EDIT: I am not talking about the Serial monitor by the way

The "Serial Monitor" is merely a window to the Arduino's serial port. You don't have to use it to use Serial. It's just a (very simple) built in way of seeing the data.

You can use the Serial interface with your own software, or with third party software. It's not tied to the Serial Monitor in any way at all.

So:

Use Serial.print() etc to send data to the PC
Write your own PC software in your language of choice to process that data, or
Use some third party application to read and process the serial data


Talking to ADS8698 (18-bit ADC) over SPI I want to talk to an ADS8698 over SPI (see page 36 for details on their SPI implementation) using a Teensy 3.2. Right now I'm only getting zeros back and I feel like (perhaps wrongly) that I've followed the datasheet correctly. I believe my SPI mode is correct and, given the clock rates I'm using, I should be observing the timing constraints properly.

(1) Is there a glaring error here? I haven't coded that many SPI interfaces, so I might have a novice mistake in there.

(2) Is there existing code for a product that uses a nearly identical SPI interface to the ADS8698 (any product that has a similar timing diagram would do)?

#include <SPI.h>

#define USB_RATE 19200//usb transfer rate
#define SPI_CLOCK 10000000//spi clock frequency

#define CS0 10

SPISettings ADC_SPI(SPI_CLOCK, MSBFIRST, SPI_MODE1);

void setup()
{
  // disable both multiplexers
  pinMode(CS0, OUTPUT);
  digitalWrite(CS0, HIGH);
  // prepare serial protocols
  Serial.begin(USB_RATE);
  SPI.begin();
}

void read_ADC()
{
  // begin the session by taking CS0 low
  SPI.beginTransaction(ADC_SPI);
  digitalWrite(CS0, LOW);// slave select disable
  // delayMicroseconds((int) (1e6 * 20/SPI_CLOCK));// wait > 16 clock cycles
  // transfer 16 bits while the ADC performs conversion
  SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
  SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
  // data should be ready, so try to read it
  Serial.println(SPI.transfer(0));
  Serial.println(SPI.transfer(0));
  // end the session by taking CS0 high
  digitalWrite(CS0, HIGH);// slave select enable
  SPI.endTransaction();
}

void loop()
{
  delay(1000);
  read_ADC();
}

The system is wired like this:

Per the Datasheet PG47

During power-up or reset, the default content of the command register is all 0's and the device waits for a command to
be written before being placed into any mode of operation.

If your still working with this I'm going to be tackling this same thing very soon, hopefully I can get it to work with DMA.
https://forum.pjrc.com/threads/34863-Teensy-CC-Dummy-Load-300W/page4


Measuring car speed between two points: What sensor to use and how to cover the distance? PROBLEM
Cars regularly exceed the speed limit in our street
SOLUTION
Measure each car's speed and clearly display the speed to the driver
EXECUTION

Measure the time the car takes to cover a set distance (e.g. 25 meters) to calculate the speed
For this I'd set up two sensors and calculate the difference between the timestamps recorded between the car passing the first and second sensors -> then convert into km/h
Display the result on an LED screen

CHALLENGES & QUESTIONS
A. What sensors should I use here? Photoresistor with laser diode, digital or analog IR sensor, ...
B. How can I best cover the distance between the sensors and connect them to the Arduino? Long wire, wireless, connect two Arduinos, ...
Thanks!

Why 25meters? If you place the two sensors 1 meter apart, you only need 1ms accuracy to get km/h (assuming a 50km/h speed limit). The Arduino can handle 1ms resolution with ease.
I'd probably go with 3-5 meters, so you don't need your setup to be that precise (i.e. distance and alignment of the two sensors). Lowering the distance also makes it less likely for two cars, from both directions, to simultaneously be inside your sensor area.
For the sensors, the biggest problem is the legal one. Having objects on/near the road could cause some liability issues. The laser solution is probably the least likely to cause this issue. Though I'm unsure about having a display next to the road.
You could go with laser and photo-transistor on one side of the road. And a reflector/mirror on the other side. I'd probably go with an IR laser, so it's invisible. You'd have to shield the photo-transistor as much as possible from ambient light, so a sudden cloud won't trigger it. You probably still need to do some filtering in software.
There are radar modules available, but I think they are pretty expensive.
Another option is a Laser range sensor, like this one from sparkfun


How to Simulate and Tune a PID I've been trying to simulate a PID using Brett Beauregard's PID library in order to understand it better. Here is my code.

#include <PID_v1.h>

const unsigned int numReadings = 500;
double analogVals[numReadings];
unsigned int i = 0;
int angle = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()

{
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin(115200);
  Setpoint = 300;
  myPID.SetOutputLimits(-2,2);
  myPID.SetSampleTime(100);
  Input = random(292, 302) ;
}

void loop()
{
  if (i % 2 == 0) {
  Input += random(-2,3);
  }
  angle += 1 % 360;
  Input += sin(angle*355/(113*180));
  myPID.Compute();
  Input += Output;
    analogVals[i] = Input;
    i++;
    if (i>= numReadings)
    {
      for (int j = 0; j < i; j++) {
      Serial.println(analogVals[j]);
      }

      i = 0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
    }
}

Even if I restrict the output of the PID to a very small value, I get huge nonsense results of this code. It oscillates like -1000 to 1000. I've read this https://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops
and tried to adjust my parameters, but they're just shots in the dark really, I can't even damp these massive oscillations. How would I tune a PID to cancel out a sin error ?

Thanks in advance

I do not have your PID_v1.h, but I made a simple experiment trying to control your example with a simple P-Controller instead of the PID lib. I made the following changes to your code:

...
double K_P = 1;
...
//myPID.Compute();
  Output = K_P*(Setpoint - Input);
  Input += Output;

This is working for very small amounts of K_P, but as soon as K_P gets higher than 2.0 it gets instable very fast. I guess this is what you are observing. The reason for me is, that you have implemented a ideal control path. In real control tasks you will always have some transfer behavior

Therefore I added a simple PT1 element (first-order lag element) to your code, now your system is much more stable and you can experiment with the K, I and D factors. Here it works with K_P even higher than 400:

// #include <PID_v1.h>

const unsigned int numReadings = 500;
double analogVals[numReadings];
unsigned int i = 0;
int angle = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
double Input_PT1;
double K_P = 20;
//Specify the links and initial tuning parameters
//PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()

{
  //turn the PID on
  // myPID.SetMode(AUTOMATIC);
  Serial.begin(115200);
  Setpoint = 300;
  // myPID.SetOutputLimits(-2,2);
  //myPID.SetSampleTime(100);
  Input = random(292, 302) ;
}

void loop()
{
  if (i % 2 == 0) {
    Input += random(-2, 3);
  }
  angle += 1 % 360;
  Input += sin(angle * 355 / (113 * 180));
  //myPID.Compute();
  Output = K_P * (Setpoint - Input_PT1);
  Input += Output;
  // start PT1
  Input_PT1 -= Input_PT1 / 25;
  Input_PT1 += Input / 25;
  // end PT1
  analogVals[i] = Input_PT1;
  i++;
  if (i >= numReadings)
  {
    for (int j = 0; j < i; j++) {
      Serial.println(analogVals[j]);
    }

    i = 0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
  }
}

Some hint:

The sketch above does not initialize Input_PT1, so it takes some secondes until you reach a steady value of 300, if you do not want to wait, just initialize Input_PT1 with 300. But this is exactly where you can start increasing first I, then D factors to try to increase speed for reaching a steady value of 300 and experiencing what influence I and D part will have.
Input_PT1 is not a good naming, since this is the output of the PT1 element, but since you are using it as the PID Input, I did not change.

Here a drawing of what I implemented in contrast to your sketch (at least I hope so ;-))


Program Upload Loading problem Please help me about this program uploading problem.
 Arduino: 1.6.13 (Windows 10), Board: "Arduino Nano, ATmega328P"

Sketch uses 930 bytes (3%) of program storage space. Maximum is 30,720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "\.\COM1": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

It can have many options, the main reason is it cannot communicate with the Nano.

I try to create a list with options:

Hardware issues

Nano is broken (solution: change Nano)
USB cable is broken (solution: change cable)
USB port is broken (solution: change USB port)

Software issues

USB port 'corrupt' (solution: use another USB port)
USB connection incorrect (solution: reconnect USB cable)
IDE is corrupt (solution: reinstall IDE)
Nano in illegal state (solution: reset/reconnect power of Nano)
Serial communication is used (remove RX/TX wires)


Capturing interrupt on both edges when it's set on RISING or FALLING I've been trying to capture rising edge of an IR sensor output. This sensor's Vcc connected to Arduino 5V and it has a digital output pin. I've observed the digital output pin on an Oscilloscope. It's not noisy.

When I attach a rising edge interrupt on digital pin 2. It somehow captures both rising and falling edges. This response is the same for when it's set for FALLING or CHANGE.

I've tried code at below both on Arduino Uno and

volatile bool caughtAnInterrupt = false;

void setup() {

  Serial.begin (19200);

  pinMode(2, INPUT);

  attachInterrupt(digitalPinToInterrupt(2), test, RISING);
}

void loop() {

  if (caughtAnInterrupt){

    Serial.println("Rising edge detected");

    caughtAnInterrupt = false;
  }
}

void test() {

  caughtAnInterrupt = true;
}

I've solved the issue with the reply by eventHandler to another post. Here it is;

  The problem you are having is because the button glitches are
  producing many interrupts on each button press. You can find a good
  description and a way of solving it using hardware here.

  Let me explain, when you press the button, the mechanical contact will
  have a transcient state in which it will fluctuate ON-OFF for a short
  period of time. The same effect might happen when you release the
  button.

  One way of solving this problem is using a capacitor parallel to the
  load. Another "easier" way would be done by software. The idea is to
  set a fixed arbitrary time in which you don't allow new interrupts.
  You could use the millis() or micros() library to set this time. The
  code would look something like this.

unsigned long lastInterrupt;

void ngt()
{

  if(millis() - lastInterrupt > 10) // we set a 10ms no-interrupts window
    {

    state = !state;

    lastInterrupt = millis();

    }
}

  This way you don't process new interrupts until 10ms have elapsed.

  Note: adjust the time to your requirements.


Comparing a text string to text output (DHT22) Lately I've received a DHT22 sensor. I've started to create a small temperature and humidity monitor station. One of the things I noticed was if you pulled out the sensor while in use, it displayed "nan". What I wanted to do was if the variable "temp" (for the temperature) equaled "nan", my LCD would display a message. But I keep getting a scope, conversion, and declaring errors. I've tried every variable and a lot of online forums, documentations, and the official Arduino reference site. My code looks like this:

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <LiquidCrystal.h>

const int rs = 53, en = 51, d4 = 49, d5 = 52, d6 = 48, d7 = 47;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define DHTPIN 27
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

int chk;
float hum;
float temp;

byte bigdot[8] = {
  B00000,
  B00000,
  B00000,
  B01110,
  B01110,
  B01110,
  B00000,
  B00000
};

byte circle[8] = {
  B00110,
  B01001,
  B01001,
  B00110,
  B00000,
  B00000,
  B00000,
  B00000
};

void setup() {
  lcd.createChar(0, bigdot);
  lcd.createChar(1, circle);
  lcd.begin(16, 2);
  dht.begin();
  do {
  lcd.setCursor(5,1);
  lcd.write(byte(2));
  lcd.setCursor(4,0);
  lcd.print("Loading");
  delay(500);
  lcd.clear();
  lcd.setCursor(7,1);
  lcd.write(byte(2));
  lcd.setCursor(4,0);
  lcd.print("Loading");
  delay(500);
  lcd.clear();
  lcd.setCursor(9,1);
  lcd.write(byte(2));
  lcd.setCursor(4,0);
  lcd.print("Loading");
  delay(500);
  lcd.clear();
  dht.readHumidity();
  dht.readTemperature();
  } while (hum > 90 || temp > 50.00);
  Serial.begin(9600);

}

void loop() {
    hum = dht.readHumidity();
    temp = dht.readTemperature();
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Temp: ");
    lcd.print(temp);
    lcd.write(byte(1));
    lcd.print("C");

    lcd.setCursor(0,1);
    lcd.print("RH:   ");
    lcd.print(hum);
    lcd.print("%");

    if (temp == a) {
      lcd.clear();
      lcd.home();
      lcd.print("Whoops! An");
      lcd.setCursor(0,1);
      lcd.print("error occured!");
    };
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");
    delay(2000); //Delay 2 sec.
 }

Thanks in advance!

A "float" number has multiple possible states, besides just being a number (It never, though, can be compared to a string):

A real floating point number
Infinity
Something that isn't a valid number

The latter is what you want - that is, the internal data of the float variable doesn't represent a valid number.

There are two functions in the standard math library that deal with this for you.

Is the number infinity? ininf(x)
Is the number invalid? isnan(x)

To use it:

if (isnan(temp)) {
    lcd.print("Invalid");
}


How does Arduino decide when to go into flashing mode and normal mode? Just this general question.As the titles says.

How does Arduino decide when to go into flashing mode and normal mode?

Is it by connecting certain pins to ground,so it's a hardware check or does it have to do with the code?

Other similar arduino like products such as the esp8266 work the same way as long as they use the same chip?

It first runs the bootloader. If there is no data coming into the serial connection within a certain amount, i.e. it's not being programmed, it will exit the bootloader and start the actual sketch.

In the UNO you will notice a 3 second delay between providing power, and your sketch starting.


how to change variable when a button connected to pin 2 is pressed Hi i am writing a code where, i have to switch a variable called toggle from 0 to 1 to 0.... every time the button is pressed (the button is on a 2 pin). I am a little lost as I am new to arduino need some help. Thank you

Go here --> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.

Those 3 are key.

Also, I wrote a buttonReader (debouncing) library here.

Sounds like you're a beginner, so check out Adafruit's tutorials here.

And lastly, I've compiled links to all my knowledge at the bottom of my article here.


LCD is not printing strings, only integers with Arduino As mentioned in the title I'm facing a problem in printing strings in the LCD. It's printing actually weird characters.

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);

  lcd.print("hello, world!");
}
void loop() {

 lcd.setCursor(0, 1);
  lcd.print(millis()/500);
}

You can find the output of the LCD in the picture below:

Whenever I use an LCD display I make sure to use the I2C backpack.  It takes actual effort to hook it up wrong if you use them.  So if this were me, I would desolder all those pins and get one.

Here is a good description of how they work:
https://learn.adafruit.com/i2c-spi-lcd-backpack/overview


Measure revolutions per second with reed switch I'm trying to measure speed of a fly wheel with a reed switch with one magnet (1 pulse per full rotation). I have an 100nf cap connected to switch to help with debounce.

#include <Arduino.h>

int speedPin = 2; // switch is connected to pin 2
int ledPin = 13;

int debounceTime = 7;

long speedPulseTime = 0;
int speedPulseCount = 0;
int speed = 0;
long speedLastSample = 0;

long serialLastReport = 0;
int serialReportFreq = 40;

void speedPulse()
{
  long time = millis();
  if ((speedPulseTime + debounceTime) < time)
  {
    speedPulseCount++;
    speedPulseTime = time;
  }
}

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

  pinMode(speedPin, INPUT_PULLUP);     // Set the switch pin as input
  attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);

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

void loop()
{
  long time = micros();
  if (speedPulseCount >= 4 || (speedLastSample + 1500000) < time)
  {
    detachInterrupt(speedPin);
    int tempSpeed = 1000000 / ((time - speedLastSample) / speedPulseCount);
    if (tempSpeed < 0)
    {
      speed = 0;
    }
    else
    {
      speed = tempSpeed;
    }

    //reset sample
    speedLastSample = time;
    speedPulseCount = 0;
    attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);
  }

  if ((serialLastReport + serialReportFreq) < millis())
  {
    Serial.print(millis());
    Serial.print(",");
    Serial.println(speed);
    serialLastReport = millis();
  }
}

Here the code I have so far. The problem I have it jumps around a little bit. What could I change to ensure more accurate readings?

It sounds like occasional "misses". Possible causes include:

the magnet passing far enough from the reed switch to "only just" trigger it [narrow the gap.];
the magnet's passage being too short for the reed switch/capacitor to respond [use a wider magnet or move closer to the center of rotation];
Too much capacitance [reduce it or debounce in software];

Update:

  Would it be better to debounce in software and what would be the best way to do it.

If you have an oscilloscope available, you could look at the raw switch signal (no capacitor) to find out how long it bounces. I'm guessing that it will be around 10ms for such a small switch. If the entire [make/break/make/break....] sequence takes less than 50% (being conservative) of the wheel rotation time (1/max_RPS), you can probably count the first pulse and ignore the switch for (0.5/max_RPS), or 1/2 of the fastest rotation. You appear to be doing something like this already. If you want to be a little bit more rigorous, you might do:

see a HIGH;
ignore switch for debounce_time;
if still HIGH,
   count++;

Also, don't forget that variables shared between your Interrupt function and the main-line code need to be:

declared as volatile, to tell the compiler not to expect that this variable has the value it had last time the mainline code read it; and
Turn interrupts off briefly while reading or writing such a variable (if it is multi-byte) in your mainline, to prevent it being changed by the interrupt function between byte-reads/writes by the mainline.


PWM generation using Arduino uno How to obtain four PWM outputs at 100 kHz using an arduino uno board? The requirement is that all four PWM outputs should have controllable duty ratios individually.

You can't squeeze 100kHz out of an Arduino without a major software rewrite (at which point you will be using an AtMega chip rather than Arduino). analogWrite defaults to ~500Hz and can be boosted to 62.5kHz on some Arduino models, and only for 2 pins. Other PWM pins are capped at 31.4kHz.

You can achieve 100kHz PWM by toggling pins manually and busy-waiting, but you won't be able to do anything else during this. Or you can make use of interrupts, which is a big leap from Arduino ecosystem as I already said.