Receiving serial data in acsii, how to split it. Hello I want to know how to split an incoming serial message that comes in this format CxxxLxxx, x=number, so i can take the 3 numbers after the C and save them and then take the 3 numbers after the L and also save it, i have a code for this but it doesn't always work, can anyone tell me where I´m wrong or is the approach I´m taking is not the right one. Thanks.

int value = 0;
int channel;
int x;
String str;
int y;
String str1;
int le;

void loop()
{
if (Serial.read() == le)
{ }
  else
       {
        str = Serial.readStringUntil('C');
        str1 = Serial.readStringUntil('L');
        channel = Serial.parseInt();
        value = Serial.parseInt();
      DmxSimple.write(channel, value);
      le = Serial.read();
      Serial.println();

       }
}

This:

if (Serial.read() == le)
{ }

looks very suspicious - sometimes it can read the C or L and therefore render the rest of your code useless.

Also Serial.parseInt shall be avoided - it returns the first thing which looks like a number, and will not wait for all three numbers.

However, your problem is likely the DMX write speed. While the DmxSimple.write is getting executed, no new incoming message can be processed. Depending on your actual Arduino board and chip, there is some buffer, but the solution is not rocket-proof at all.

You can:

make a solid protocol between the PC and the Arduino, i.e. the PC sends one command, arduino sends it out over the DMX, and Arduino answers an OK to the PC. The PC will not send out any new command unless it has received an OK first.
avoid these ad-hoc mess, i.e. serial-reads and serial.printlns here-and there.

For example, if you change the protocol so: CxxxLxxxE (E stands for end) you can utilize readStringUntil to read the input until a separator, and then use the toInt method to actually convert the read data to integer:

void loop() {
    strDummy = Serial.readStringUntil('C');
    strC = Serial.readStringUntil('L'); // xxx from CxxxL
    strL = Serial.readStringUntil('E'); // xxx from LxxxE
    channel = strC.toInt();
    value = strL.toInt();
    DmxSimple.write(channel, value);
}

After learning that it is not possible to change the protocol, here is a new plan

int channel;
int value;
void loop() {
    if (Serial.read()=='C') { // wait for a C
        channel=Serial.parseInt(); // parse till first non-number
        value=Serial.parseInt(); // parse till first non-number
        DmxSimple.write(channel, value);
    }
}

See https://www.arduino.cc/en/Tutorial/ReadASCIIString for a tutorial. Note that Arduino Serial commands are pretty confusing sometimes :) for example, parseInt will actually consume one non-number character implicitly after parsing a number.

Also note that this solution works well if the command is sent as one batch. If you are trying to send the command manually, e.g. from a terminal window, character by character, parseInt may time out. Consider increasing the timeout to 10 seconds or more by https://www.arduino.cc/en/Serial/SetTimeout


How do I get the request params from a ESPAsyncWebServer? I currently have the following code

server.on("/on", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("ON hit.");
    String message;
    Serial.println(request->url());
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = " not specified";
    }
    request->send(200, "text/plain", "On, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);
....

When sending in a request I get the out put, "Device not specified".

I take a look at the request-params() which gives me back a count of params that are in there and it's returning 1. I write this out:

server.on("/off", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("OFF hit.");
    String message;
    int params = request->params();
    Serial.printf("%d params sent in\n", params);
    for (int i = 0; i < params; i++)
    {
        AsyncWebParameter *p = request->getParam(i);
        if (p->isFile())
        {
            Serial.printf("_FILE[%s]: %s, size: %u", p->name().c_str(), p->value().c_str(), p->size());
        }
        else if (p->isPost())
        {
            Serial.printf("_POST[%s]: %s", p->name().c_str(), p->value().c_str());
        }
        else
        {
            Serial.printf("_GET[%s]: %s", p->name().c_str(), p->value().c_str());
        }
    }
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = "not specified";
    }
    request->send(200, "text/plain", "Off, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);

and get the output now of

1 params sent in
_POST[device]: puddle
Device not specified

If I try to do something like request->getParam(0)->value().c_str()
I get a stack dump of a bunch of hex values that I have no idea what it means: but it looks like a big fat error.

For POST request the hasParam needs to know if you want to test the url parameters or x-www-form-urlencoded parameters in body of the POST request. The second parameter of the hasParam is boolean post and it has default value false. Use hasParam("device", true).


Ams1117 worked fine on battery, up in smoke with 12v power supply I have a circuit that worked fine on a a 12v lead acid battery for a day. Once connected to a 12v 3a power supply it didn't work properly and then the ams1117 5v burned up and so did a 3.3v one within a few minutes.
The 12v power supply is a cheap Chinese model from eBay. My meter shows 12.3v but I don't have a scope.
I understand that ripples in the output of the power supply have probably caused this but what does that mean and how has it exceeded the rating of the converter? Is there a simple fix so I can use the power supply?
Would a 12v motor or relay be susceptible to the ripples?
I'm going to run my esp8266 from a different source but I'd like to keep using the power supply for the motor and 12v relays.

Running an Arduino board with 12V is almost always too much. With only a few leds the voltage regulator on the Arduino boards gets too hot.

The best voltage is 7.5V. Then the voltage regulator has only little power dissipation and it is just high enough to turn off the USB 5V power.
Or power the Arduino board with a 5V (from a USB charger, or USB power pack) to the USB connector.

Never use a power supply that is not certified. It is a safety risk that can be avoided with a few dollars more.
The cheap power supply can have ripples, but it can for example have noise in the MHz range, or a voltage spike when turned on, or voltage overshoot when more current is required.  There can also be a coupling to the mains as @Majenko wrote. I have had a few of those. Nasty stuff!
Even with a scope, you can not tell if the power supply is really okay.

If you have a unreliable power source or a voltage that is too high, then a DC-DC converter can convert it into a nice steady voltage.
However, you should first get rid of that cheap power supply and buy a good one.


Serial Print, String And Variable On Same Line How can I print to the serial monitor a string or just single character followed by a variable like "L 55"

int Var = 55;
//Do it in 2 lines e.g.
Serial.print("L ");     // String
Serial.println(Var);    // Print Variable on same line then send a line feed


Communication with two XBee's and Arduinos over serial I have two XBee's connected to two Arduino Uno boards (one for each XBee). I connected each XBee to the X-CTU software, and have set the following:

XBee 1

Pan ID = 4270
DL = 10
MY = 20

XBee 2

Pan ID = 4270
DL = 20
MY = 10

Both

DD = 10000
IC = FF
IR = 32

Therefore, they should be on the same network and see each other as the 'other person' each is talking to. I'm using the TX and RX pins of the arduino and the XBee to communicate over the serial port.

When testing if each can hear the other, I loaded one arduino with this code:

#include <SPI.h>

void setup() {
// put your setup code here, to run once:
  Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
  Serial.print('x');
  delay(1000);
}

Then another with this:

#include <SPI.h>

void setup() {
// put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(7,OUTPUT);
  digitalWrite(7,LOW);
}
void loop() {
// put your main code here, to run repeatedly:
  if(Serial.available())
  {
    char getData = Serial.read();
    if(getData == 'x')
    {
      digitalWrite(7,HIGH);
      delay(500);
      digitalWrite(7,LOW);
      delay(500);
    }
  Serial.print(getData);
  getData = ' ';
  }
}

This works perfectly. One LED will light up on the correct arduino in half second intervals. However, when I try to make them both communicate at the same time to each other, nothing happens. Neither LED will light up. The code for both arduino's is:

#include <SPI.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(7,OUTPUT);
  digitalWrite(7,LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print('x');
  delay(1000);
  if(Serial.available())
  {
      char getData = Serial.read();
      if(getData == 'y')
      {
        digitalWrite(7,HIGH);
        delay(500);
        digitalWrite(7,LOW);
        delay(500);
      }
      Serial.print(getData);
      getData = ' ';
    }
}

But for one arduino I change the code to Serial.print('y') and if(getData == 'x') to listen for the other one. I also have tried delaying one arduino in the setup by one second to offset the sending and recieving, but that also doesn't help.

I need them to be able to listen and talk to each other, maybe even at the same time like this example. I'm trying to create a proximity sensor in, lets say the 'back', area communicate with the 'front' area, and an accelerometer and two switches from the 'front' communicate with the 'back'.

Is there any settings I can change in X-CTU, such as the baud rate or the amount of packets re-sent, to overcome this problem? Or is this merely a code issue?

I do have the power connected to the 3.3V pin of the arduino, and I'm using 470/220 Ohm resistors as voltage dividers for the output pins from the arduino to the XBee, so I don't think voltage is an issue here.

Also, I have disconnected the arduino from the computer. I'm powering it via the USB-A to USB-B cord -> 13000 mAh 5V DC rechargeable battery, so there should be no interference with the serial data lines. Pin 2 (RX) of the XBee is connected to pin D0 (RX) of the arduino, and pin 3 (TX) of the XBee is connected to pin D1 (TX) of the arduino.

Thanks for your help.

Did you set one of your modules into coordinator mode?
Every xBee network needs a coordinator. Therefore, you need to put one of your Xbee modules into coordinator mode using the "Function Set" dropdown box in X-CTU. The coordinator has the fixed address 0, so you need to set DL and HL address parts of the other module to 0. On your coordinator, you can set DL to FFFF and HL to 0, which is the broadcast address.

Softserial won't help you. It's just a way to use some of the pins as an additional serial port. Don't use that if you can use a hardware serial port.


Which Arduino Board should I start with? I am interested in Arduino projects. I want to learn to develop my own Arduino based system. The problem is I am not sure which Adruino board must I start with. Any ideas are appreciated, I have searched many discussion forum but could not find a satisfactory answer.

My questions are:

Which Arduino Board should I start with?
Is it possible to work on Arduino based projects without the board; like having a simulation of the board? If so how?

My advice:
 - get a model with USB port (some do not have one)
 - the DUE might seem attractive, but you have less libraries available and less examples, I'd recommend it more as follow up
 - you will get frustrated if you do not know how to code, at least a bit, so if you have not programmed before, you might want to spend some time trying simple stuff just with your PC
 - same about electronics: if you do not have previous experience, it might be preferable to play a bit with a breadboard and some components (LEDs, resistors, switches, etc.); this will reduce the likelyhood that you fry your Arduino. Remember to buy some cables MM/MF/FF, you will end up needing all of them, sooner or later. For powering the board, you can find nice power supplies that cn be powered by a USB cable.

I have bought UNOR3 clones at $4-$5 on ebay, so if you can afford it, I'd suggest you buy a couple, that will enable you playing with I2C master slave and similar configurations.


Creating an array with the length coming from a library When creating an array like in the sketch

#include <Lib.h>

int myArray[Lib::len];

void setup() {}

void loop() {}

the variable len must be an integer constant that is known at compile time. Like shown in the sektch, I want to put the length of the array into a library and get it from there. The problem is that for this to work, you have to initialize the constant already in the .h file, which is against proper library standards. This is how you would do this (.h file of the library):

class Lib {
  public:
    static const int len = 4;
};

The .cpp file doesn't even have to contain anything in this case. The proper way to do things in a library would be like this though:

The .h file:

class Lib {
  public:
    static const int len;
};

The .cpp file:

#include "Lib.h"

const int Lib::num = 4;

But if done like this, len doen't have a value at compile time since the sketch only includes the .h file and not the .cpp file.

Is there any way to intitialize an array in a sketch with its length coming from a library while maintaining proper library design?

There is absolutely nothing wrong with putting it in the header.

  §9.4.2/4 If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Since you're just using it as a simple constant "integral" value there is nothing wrong with putting it in the header.


ESP 8266 with sdk 1.5 By compiling using sdk v1.5 i got following error.Any idea how to resolve it?

mingw32-make.exe -f C:/Users/abc/worksorg/mesh/Makefile all
AR build/app_app.a
LD build/app.out
c:/Espressif/ESP8266_SDK/lib\libmain.a(app_main.o): In function `user_uart_wait_tx_fifo_empty':
(.irom0.text+0x5c4): undefined reference to `user_init'
c:/Espressif/ESP8266_SDK/lib\libmain.a(app_main.o): In function `user_rf_pre_init':
(.irom0.text+0x85a): undefined reference to `user_init'
c:/Espressif/ESP8266_SDK/lib\libwpa.a(wpa_auth.o): In function `wpa_receive':
(.irom0.text+0x9a0): undefined reference to `aes_wrap'
c:/Espressif/ESP8266_SDK/lib\libwpa.a(wpa_auth.o): In function `__wpa_send_eapol':
(.irom0.text+0xd73): undefined reference to `aes_wrap'
collect2.exe: error: ld returned 1 exit status
C:/Users/abc/worksorg/mesh/Makefile:187: recipe for target 'build/app.out' failed
mingw32-make.exe: *** [build/app.out] Error 1

Add the crypto library to your build, Makefile or whereever your IDE expects it.

--> http://bbs.espressif.com/viewtopic.php?f=46&t=1442


ESP8266 NODEMCU V3, HOW TO USE AND CONTROL V3 OUTPUT POWER this is my very first post in here so I apologise if I am not giving you all the information that I should.

I am creating this topic to ask you help regarding how to control and use the v3 output of my Nodemcu.

I have a script which is working fine to power on and off a led by using one of the GPIO and the ground. However, my project requires to power on a small motor for about 2 seconds and then stop it. If I connect this motor to one of the GPIO and the ground I can control it but it runs very slow. If I connect the motor to the 3V output it goes fine but I can't turn it on or off. The motor requires 3V to run properly. How can I turn it on and off by powering it from that 3V output?

What am I missing?

I have a 4n25 chip which I saw in a video that has been used for a similar project however the vide is in Portuguese and I am not able to follow it properly.

Can please someone advice?

Thank you for your time,

Ade

You cannot control the "V3" output. It's a 3.3V power supply output. Think of it like a battery. It's always on and always giving power.

Instead, you need to add a "switch" to control that power that the ESP8266 can itself control, such as a MOSFET or a motor driver (H-Bridge).


Nano V3 values "overwritten" randomly When I assign a global var to a certain value inside an if-block it has been changed to another value in the next statement. Somehow the address of the var is overwritten by some other process. It also does not stop at 1 value, this happens to the next vars that are assigned another value too. The vars are not defined in a row but should be close.
I already installed a newer version of Arduino IDE, no change.
Example:

menuActive=1;
Serial.print(menuActive);

gives results in the range 40 to 57 as far as I have seen till now. Further actions assign always the SAME value to next vars I assign after this.
Anyone some idea what could cause this? Am I low on memory for local vars?
This is compile message:

Sketch uses 21790 bytes (70%) of program storage space. Maximum is 30720 bytes.
Global variables use 1454 bytes (70%) of dynamic memory, leaving 594 bytes for local variables. Maximum is 2048 bytes.

edit:

As I already said, it is 21k of code. But I show you the part of the code that mishaves:

while ((digitalRead(rotSwPin) == 0) && lpress <= 200) {
    delay(10);
    lpress++;
    if (lpress > 200) {
        menuActive++;
        menuLvl=0;
        menuPos=0;
        subPos=0;
    }
}

Normally I use menuActive=1. Within the braces, it is still 1, out of that it changes. Maybe change from byte to bool.

I found the problem. I could see that the false value is the character code of the minute I am displaying. I display hours and minutes and there was a declaration that was 3 characters short for the string I got as a result for hours added to minutes. Yes, it was memory corruption. So be very careful to dimension enough places for your C-strings including 1 extra for 0. If you are not so short on RAM then a few more characters will do no harm, the end of the string will be the character before the 0 in memory.
When strange things happen start looking at this matter!


sizeof() on custom library constructor returns wrong result I made a custom library (let's call it DigitalOutput.h) to learn a bit about librairies and to simplify my work. Here is the basic constructor in the .h file:

DigitalOutput(uint8_t pin);

Here is the code in the .cpp file :

DigitalOutput::DigitalOutput(uint8_t pin)
{
    _pin    = pin;
    _status = LOW;
    pinMode(pin, OUTPUT);
}

So very simple stuff. Now, in my program, I call the function the usual way:

DigitalOutput LED(7); // pin #7 will be configured
                      // as an output pin to control the LED

Now the issue comes when I create an array and then use the sizeof() function.
Here is the code from my program (using an Arduino Mega):

DigitalOutput   LED_array[] = {22,23,24,25,26,27,28,29,
                               30,31,32,33,34,35,36,37};

So, the array contains 16 elements. But when I do for instance...

#define         LED_NUMBER    sizeof(LED_array)
//...
void setup(){
    //...
    Serial.println(sizeof(LED_array));
    Serial.println(LE_NUMBER);
}

...I get 160 as a result in both cases instead of 16...

So I end up doing a weird #define LED_NUMBER sizeof(LED_array) / 10 in order to get the proper result which is then used throughout the program. Any idea of why this isn't working right?

It is working perfectly correctly.

sizeof doesn't return the number of elements in an array, it returns the number of bytes the array takes up. Since each entry in your array is an instance of your DigitalOutput class, the size is the number of elements multiplied by the size of the class - in this case 10 bytes.

To get the number of elements you must divide the number of bytes by the size of one element:

int numEles = sizeof(LED_array) / sizeof(DigitalOutput);

or

int numEles = sizeof(LED_array) / sizeof(LED_array[0]);


How is this simple transistor circuit suppose to work? I've tried to replicate this circuit today.

My motor is a computerfan, they apperntly don't need a flyback diode since there are no brushes.
I used a 12V power source for my arduino and hooked it up via
VIM.
I used the arduino ground as external power source.
I verified that the transistor worked as expected with a voltmeter.

Here is the transistor I used:

As I understand this, the transistor is stimulated to "steal" electrons away from the motors circuit. But it seems connected to the base. Why would you do that?

There are many bad schematics and pictures online, and these pictures are really bad.

Do not try to make that. You may damage the Arduino board and the transistor.

Even the picture of the BC548 is wrong. The BC548 is always
called "BC548" and never "BC-548".
The BC548 is not a good choice to drive a motor. It can only
do 100 mA continuous.
The DC barrel socket has plus and minus wrong connected.
The 12V plus is connected to the Arduino GND.
That is not okay.
The transistor in the first picture is probably a
transistor with the pins in BCE order.
A resistor is missing to the base of the transisor.
Because of the missing resistor, the Arduino board
can be damaged.
When the breadboard has a bad connection to GND,
the 12V can go to pin 9 of the Arduino board.

@Dorian, there are no mystical higher alien intelligent thoughts for that schematic. It is obvious a wrong circuit that is meant to drive a motor with PWM using a transistor.

And last but not least:
There are a few different types of computer fans. Some have a capacitor inside and some will only accept a PWM signal to a PWM input.
Are you sure that your fan is able to accept PWM for the 12V power?


Which timer does Arduino Nano use for each PWM pin? I'm unable to find which Timer controls each PWM pin (3, 5, 6, 9, 10 and 11) in an Arduino Nano Board (ATmega328).
Any guesses?

Thanks in advance,

Eduardo

This is a good pinmapping picture of the Nano : www.pighixxx.com/test/portfolio-items/nano/

A timer has sometimes two outputs, A and B. The pins with OC0A and OC0B are timer outputs of Timer0. OC1A and OC1B are Timer1, OC2 and OC2B are Timer2.

Everything is also in the datasheet of the ATmega328P, but that picture is a lot easier.


Do gyroscopes purposefully show erroneous data? I tested an MPU-6050 (GY-521) using an Arduino Nano. I used the I2CDevLib and opened the MPU6050_DMP6.ino with the Arduino IDE. I opened the MPUTeapot.pde Processing-file with Processing. A few changes was necessary to make it work:

MPU6050 mpu;

was changed into:

MPU6050 mpu(0x68);

Additionally I commented out this line:

#define OUTPUT_READABLE_YAWPITCHROLL

and uncommented this line:

#define OUTPUT_TEAPOT

When turning everything on, the arrow (Processing) would turn with 5 degrees/s clockwise around the z-axis (plus a very small amount around the other two axes). After about 20 seconds, it would stop, and turn around the x-axis pretty fast for 3 seconds. Then it would stop. Now, the gyroscope+accelerometer would work perfectly. This happens every time I test it.

This happens only when the gyroscope is perfectly still on the ground. It does not stabilize if I move it around. Only after it is left completely still, it'll stabilize after 23 seconds.

Is this how it should work, or is it a problem with the gyroscope? Could it even be caused by the I2CDevLib? Can anybody else confirm this?

MPU6050 is a chip that has an intenal (closed and unknown) algorith to calculate orientation. Because you ar reading ANGLE, that means you are using that algoritm, and that "time" may be the time needed for the calibration.

what do you have as output on the serial?


Can I have help interperting this code? char variable somehow storing big numbers I have this GSM module I got for my arduino project and I am trying to access the call feature, but the function makes no sense.

  boolean Adafruit_FONA::callPhone(char *number) {
  char sendbuff[35] = "ATD";
  strncpy(sendbuff+3, number, min(30, strlen(number)));
  uint8_t x = strlen(sendbuff);
  sendbuff[x] = ';';
  sendbuff[x+1] = 0;
  //Serial.println(sendbuff);

  return sendCheckReply(sendbuff, "OK");
  }

This is the function however how is char being used to display a phone number in the parameter?

It's passed as a char*. This can be derived from either a string literal (e.g. "212555121") or from a String via its c_str() method.


Arduino stopped showing up in /dev and dmesg without response Arduino suddenly stopped being recognized.
It is not listed in /dev and
dmesg -w shows no activity at all when un/plugged.
I'm on Fedora 33. The Arduino is MKR-Zero. The cable is ok - other devices work well. I tried it on windows machine - same result - in Arduino IDE the option for port is greyed out.
Very weird thing happened before this issue- when I was trying to flash sketch, audio connected to docking station switched to speakers in laptop and keyboard + mouse connected to the docking station powered down (back light on keyboard went off and could not be turned on) however the Num lock light was on.
I'm afraid that I burned the Arduino - how do I verify if that is the case.
The "ON" LED is lit up when plugged in

Ok, I have no idea what the hell is this, but when I double-press the reset button (while connected/powered on ofc) it works again.
This can be seemingly cycled - press once and it goes wrong, press twice and it's ok again... round and round. Seems more like some retarded "feature"


I2C multi sensors reading on Arduino I have several sensors (Grove multichannel gas sensor, Air Pressure Sensor MPX4115A, Temperature and Humidity Sensor DHT11) where most of them uses I2C communication.
I wonder if it is possible to read all of them using the I2C communication on a single Arduino board?

Should be easy enough.  Do you already know how to connect and communicate with one I2C device?  If so, connecting multiple should be simply a case of connecting them in parallel.

If you don't know how to communicate with a single I2C device, then...

For the Arduino software you can use Wire to talk to devices over I2C.

For the hardware, connect the I2C clock and data lines from the Arduino to the I2C devices.  More on that here.


Can't communicate with arduino using python (Windows) I am new to programming and am trying to communicate with my arduino using python through serial communication. I am using the following code:

Arduino code:

int ledPin = 11;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin,OUTPUT);
}

void loop() {
  digitalWrite(ledPin,LOW);
    if (Serial.read() == 'M'){
      digitalWrite(ledPin,HIGH);}
}

Python code:

import imaplib
import serial
ser = serial.Serial("COM3",9600)
ser.write(b'T')
ser.close()

I get the following error on running the python script:

  serial.serialutil.SerialException: could not open port 'COM3': PermissionError(13, 'Access is denied.', None, 5)

More than likely you ran the Arduino program from the Arduino IDE, and left the terminal window open. You must close it before you run the python program, as it will already 'own' the port until it closes. You dont have to quit Arduino IDE, just close the terminal window.


Why is my boards.txt file not being found? I'm using the ino command line tool for the first time. When attempting to build my first sketch I run:
ino build in the project directory.

I get the following error:

Searching for Board description file (boards.txt) ... FAILED
Board description file (boards.txt) not found. Searched in following places:
  - /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino
  - /usr/local/share/arduino/hardware/arduino
  - /usr/share/arduino/hardware/arduino

What's going wrong here?

I've found an open issue here: https://github.com/amperka/ino/issues/240
But I'm wondering if anyone has a workaround.

I got a hack to work  (macOS) by symlinking the files to where ino expected them to be.  But now I'm running into this issue: https://github.com/amperka/ino/issues/149

FWIW:

cd /Applications/Arduino.app/Contents/Resources;
ln -s Java ../Java;
cd /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino;
ln -s boards.txt avr/boards.txt;

Did it for me as far as finding boards.txt goes.

Still Broken otherwise. (Not marking as answer)


Coin Slot Sensor Using AttachedInterrupt Hi Im having a problem on my code How can I properly use the attached Interrupt on my coin Sensor so that it will not have any problem on detecting coins
#include <Adafruit_Fingerprint.h>    //Libraries needed
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
#define I2C_ADDR 0x27          //LCD i2c stuff
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
const int coinSlot = 9;
int relayPin = 4;

String Names[] = { "RAVEN", "Surtr", "Tech",}; //Those are the names affected to the fingertemplates IDs
//The first on which is Names[0] : "" has the ID 1 in the fingerprint sensor

SoftwareSerial mySerial(2, 3);                  //Fingerprint sensor wiring RX 3, TX 2
LiquidCrystal_I2C lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin); //LCD declaring

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);                    //Fingerprint sensor declaring

volatile int coinCount = 0;
int requiredCoins = 1;
boolean coinInserted = false;

void setup()
{
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH);
  pinMode(coinSlot, INPUT_PULLUP);
  lcd.write(EEPROM.read(5));
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(9), coinInterrupt, FALLING);
  finger.begin(57600);              //Sensor baude rate
  lcd.begin (16, 2);
  lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.setCursor(0, 0);
  lcd.print("SECURED VAULT");
  lcd.home();
  finger.getTemplateCount();        //Counts the number of templates stored in the sensor flash memory
  delay(2000);
}

void loop() {
  int FingerPrintResult = getFingerprintIDez();

  if (FingerPrintResult != -1) { //This function keeps looping and waiting for a fingerprint to be put on the sensor
    OpenDoor();
  }
  else
  {
    if (coinInserted) {
      coinInserted = false;
      coinCount++;

      EEPROM.write(0, coinCount);
      Serial.println(EEPROM.read(0));

      lcd.setCursor(0, 0);
      lcd.print("TOTAL:");
      lcd.setCursor(0, 1);
      lcd.print(coinCount);
    }

    void coinSlot() {
      coinCount++ ;
      insert = true;

      else {
        lcd.clear();
      }
    }
  }
}
//Only the modifications are commented
int getFingerprintIDez() {
  uint8_t p = finger.getImage();        //Image scanning
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();               //Converting
  if (p != FINGERPRINT_OK)  return -1;

  lcd.clear();                     //And here we write a message or take an action for the denied template
  p = finger.fingerFastSearch();     //Looking for matches in the internal memory
  if (p != FINGERPRINT_OK) {         //if the searching fails it means that the template isn't registered
    lcd.print("Access denied");
    delay(2000);
    return -1;
  }
  //If we found a match we proceed in the function

  lcd.print("Welcome");                  //Printing a message for the recognized template
  lcd.setCursor(2, 1);
  lcd.print(Names[finger.fingerID - 1]); //Then print the name we gave it and the -1 is to remove the shift as the ID starts from "1" but the array from "0"
  return finger.fingerID;
}
void OpenDoor() {
  digitalWrite(relayPin, LOW); // turn on solenoidlock
  delay(5000);
  digitalWrite(relayPin, HIGH); // turn off solenoidlock
}

Please how can I get the code working and what line of code should I focus to make the code work

Again, it makes sense to just use an attachInterrupt capable pin; but if can't for some reason:
Library install
Applying what I suggested in the answer on your other question to the code you've provided here, means installing the mentioned library:

And searching for and installing the library from the manager:

Code changes
Including the header
Patterned after documentation and an example for the library, your code would need to include the header for the library:
#include "PinChangeInterrupt.h"

Replacing attachInterrupt
Your attachInterrupt call would need to change to attachPinChangeInterrupt; likewise with the function that maps the pin to the interrupt number:
attachPinChangeInterrupt(digitalPinToPinChangeInterrupt(9), coinInterrupt, FALLING);

That is about all there is to it.  On the UNO/Nano or broadly ATMega328P-based Arduinos, only pins 2 and 3 work with attachInterrupt.  attachPinChangeInterrupt will work with most pins of most AVR-based Arduinos; any pins that have an PCINTn signal routed to them.  These are not as desirable to use, for performance reasons that you don't need to worry about for push buttons or your coin detector, and for easy-of-use reasons that are taken care of for you by this library.


Arduino Nano ATmega328P bootloader difference There are two ATmega328P bootloaders, old and current.  What is the difference between these bootloaders?

I'm aware that Nanos sold by Arduino use the new bootloaders but I haven't been able to find any release notes about the bootloader.

The bootloader currently shipped on the official Arduino Nano boards and selected via the Arduino IDE's Tools > Processor > ATmega328P after choosing Tools > Board > Arduino Nano is the same version of optiboot used by the Arduino/Genuino Uno:
https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L152

nano.menu.cpu.atmega328.bootloader.file=optiboot/optiboot_atmega328.hex

https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L72

uno.bootloader.file=optiboot/optiboot_atmega328.hex

The bootloader selected via Tools > Processor > ATmega328P (Old Bootloader) is the "ATmegaBOOT" bootloader.

As used by the Nano hardware definition, there are two significant differences between the two bootloaders:

Optiboot will not go into an endless reset loop after a watchdog reset. ATmegaBOOT will.
Optiboot expects the upload communication at 115200 baud. ATmegaBOOT, 57600. This is the reason why the old boards don't work with the Tools > Processor > ATmega328P selection and vice versa.

There is another very significant difference between the two bootloaders that, sadly, you will not benefit from with the new Arduino Nano board/hardware definition: Optiboot will fit in a 0.5 kB boot section, while ATmegaBOOT requires a 2 kB boot section. Unfortunately Arduino forgot to change the BOOTSZ fuse accordingly and so the opportunity to free up 1.5 kB of precious flash memory for the users of the Nano was lost. The willingness of Arduino to knowingly release flawed hardware has historic precedent.

  I haven't been able to find any release notes about the bootloader.

Arduino's release notes have not yet adapted to the fact that hardware packages may be released independently of IDE releases ever since Arduino IDE 1.6.2. There is a note about the bootloader change in the IDE release notes for the next IDE release:

https://github.com/arduino/Arduino/commit/ec179e5af67b7f1eeb5e46d22034798f8b24b7cb

Other than that, you can consult the commit history:

https://github.com/arduino/ArduinoCore-avr/commit/1b14cc07331268e95eddcce2cc67e29ed667e62f


How to get HTTPS on Arduino? Put plainly: is there a way to get an HTTPS connection on the Arduino?

I have been looking in to it, and I have found it is impossible with the standard library and the Ethernet shield, but is there a custom library that can do it?

What about a coprocessor, i.e. like the WiFi shield has? Anyone know if the Arduino yún has ssl?

MCUs mounted on Arduinos don't have the horse power to handle https connections.

Yún does handle https on the linux side, with software like curl, wget or python. Your sketch can just delegate the task to the linux side.

While curl works fine, despite having python preinstalled, you need to manually install python-openssl, since it's not available out of the box (due to disk space constraints)


Making Serial act as an interrupt I am trying to make a program to control a stepper motor with serial inputs, and in writing a function to jog it, I am having trouble figuring out how to make a serial input stop the loop that steps the motor without making the time per step inconsistent.  Is there a way where I can have a new serial input act like an interrupt and break any loop that's in progress.

void jog() {
  if(input[1] == 0) sd.setDirection(0);
  else sd.setDirection(1);
  while(true){
    if(Serial.available() > 0) break;
    sd.step();
    delayMicroseconds(10);
  }
  sd.setDirection(0);
}

Right now I have this (I'm using a Pololu library that defines the steps), but for some reason this does nothing or at least moves so slow it's imperceptible (a single step only moves the motor 0.007 degrees).  It moves the motor very smoothly if I delete if(Serial.available() > 0) break; but then I can't stop it.

void loop() {
  getData();
  switch(input[0]){
    case 'r':
      Serial.write('r');
      ramp();
      break;
    case 'c':
      Serial.write('c');
      cycle();
      break;
    case 'j':
      //Serial.write('j');
      jog();
      break;
    default:
      break;
  }
}
void getData(){
if(Serial.available() > 0){
  for(int i = 0; i < 200; i ++){
    input[i] = 0;
  }
  for(int i = 0; i < Serial.available(); i++){
    input[i] = Serial.read();
    Serial.print(input[i]);
  }
}
Serial.flush();
//Serial.print(input[0]);
}

This is the relevant code that calls jog()

How do you know, that there is nothing in the Serial buffer, when you enter the jog() function? You don't check for this.

I think your problem is actually in your getData() function. The for loop

for(int i = 0; i < Serial.available(); i++){

might not work as you think, because i increases in every loop iteration while Serial.available() decreases in every iteration. So you actually read less data, than is available on the buffer. For example let's assume, that you have 2 Bytes on the buffer. Serial.available() returns 2. In the first for loop iteration i is 0, while Serial.available() is 2. When you read from the Serial buffer in the iteration, Serial.available() decreases to 1 (since you removed one byte from the buffer by reading it). At the end of the iteration, the for loop will increase i by 1 (due to the i++). Now in the condition of your for loop, you have 1 < 1 (because both i and Serial.available() are 1), thus the for loop will exit without any further iterations. But you still have 1 Byte left in the buffer, that you didn't read.

As I read from the documentation of Serial.flush() (though the documentation is notoriously bad) and from this question, I see, that it will only wait until the output buffer is emptied by the interrupt routines. It does nothing with the input buffer. So you still have data in your RX buffer after this line.

That means, that you really have data in your RX buffer, when you get into the jog() function. Thus it will directly exit without doing any step.

To solve the issue, you should first correct your getData() function to read all the available data from the RX buffer. You can change your for loop like this:

for(int i = 0; Serial.available() > 0 && i < INPUT_BUFFER_SIZE; i++){

This will loop until the RX buffer is empty (when Serial.available() returns 0) or until your input[] array is full (Please add a constant or a define for the input buffer size. Maybe you already have it. You didn't include the full code. But I guess it is 200).

After the for loop, you can empty the buffer by reading from it, until there is nothing left (Please see the linked question for that). You can even do this at the start of your jog() function. This ensures, mostly, that no data is in the buffer at the start of the jog() function (mostly, because the timing of data reception could be, that you receive a byte between the emptying of the RX buffer and the loop. Little probability, but not impossible).

Though - as Nick Gammon states in the linked answer - it is not the best way to empty the RX buffer and use every serial input as interrupt (sometimes you don't have exact control, when exactly the data is received). A better solution is to implement a message protocol, where the end of a full message is marked with a special character. Then you read from serial, until a full message is received (you can even do this non-blocking, so that you can do other things until the message is complete), and only then act upon the message. This would need bigger changes in your code. You would have to rewrite your getData() function and then remove all blocking code from the sketch (for example all delays) and work with non-blocking code instead (for example using the micros() function. The principle is explained in the BlinkWithoutDelay example, that comes with the Arduino IDE (though it uses millis() instead of micros() it is the same principle). You would call the jog() function repeatedly, which would only do a step, if it is time to do one. In the meantime the rest of the code can receive new messages. This makes you more flexible and independent of the exact timing of data reception. Since this would be a big rewrite of your code, you have to decide yourself, if you want to go this way, or stay with the simpler and more imperfect solution.


Arduino IDE documentation for WiFi.connected() I'm including this library "ESP8266WiFi.h" at the top of my sketch.
I can find documentation on WiFiServer.available(), but didn't find for WiFi.connected(), which is called in a server sketch after getting the client.

Clearly it's a test whether (once? I believe) the client is connected or not (and hasn't been explicitly closed in the server's side). It may seem obvious but some documented info would be helpful though.

You'll find it defined in WifiClient.h. The version I am using is, in WifiClient.cpp:

uint8_t WiFiClient::connected() {
  if (!_client)
    return 0;
  return _client->state() == ESTABLISHED || available();
}


how does serial port communication work under the hood? im just looking for how to send/ write date to pc over serial port from arduino..vice versa.

I have few Question to ask after taking so much time and couldn't figure it out myself. I hope you guys can guid me please.

First, i found i can use Serial.println() function to send some data then, on the pc side, it just checks and reads the port (/dev/tty..). But, how does this process actually work under the hood? So, if you use serial.println() it knows about where to write?

Second i also found it's something to do with UART communication.. But, inside Hardware.cpp file, i couldn't find any function call to the one for UART.

Third there is the code like extern HardwareSerial Serial; Then where is the definition of this Serial?

Fourth There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

please, forgive my silly question.. i'm just so curious about this..

The first question already got a perfectly good answer. I am answering the other ones.

  i couldn't find any function call to the one for UART.

There are no "UART functions" in the MCU. The UART is controlled by reading and writing into special registers. These come by names like UCSR0A, UCSR0B, UCSR0C (USART 0 Control and Status Registers A, B and C), UBRR0L, UBRR0H (Low and High bytes of the USART 0 Baud Rate Register) and UDR0 (USART 0 Data Register). These registers are all referenced in HardwareSerial.cpp. You can check the datasheet for their meaning.

  where is the definition of this Serial?

In HardwareSerial.cpp, by the end of the file, right after the comment "Preinstantiate Objects".

  There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

There are actually two ring buffers: the receive buffer (_rx_buffer) is filled by an interrupt service routine and is emptied by you calling Serial.read(). The transmit buffer (_tx_buffer) is filled by you calling Serial.write(), Serial.print() or Serial.println() (the line _tx_buffer->buffer[_tx_buffer->head] = c; in HardwareSerial::write()), and is emptied by an interrupt service routine.

These interrupt service routines are defined in HardwareSerial.cpp. They start with lines like ISR(SOMETHING_vect). They are triggered by the hardware UART. The transmit ISR is triggered when the UART is ready to accept a new byte to transmit (when it is done transmitting byte n, it starts transmitting byte n+1 and is ready to accept byte n+2 in its TX buffer). The receive ISR is triggered when a new byte has been received.

  when does it get initialised?

When you call Serial.begin().


How to have precise measurements I need to display measurements of a sensor which need to be presented on a precise time-scale.
Since the loop function is not quite precise, how can i make sure that i can measure at say for example exactly 1ms?
( I am using an ADXL345 sensor )
Thanks a lot!

The ADXL345 has both a FIFO and data rate setting. This allows sampling to be done with a precise frequency without having to use timers, etc, on the MCU. The MCU/Arduino has to fetch data before the FIFO overflows. The max sampling frequency depends on the communication protocol (I2C or SPI), i.e. how fast the MCU can empty the FIFO.

It is possible to use the ADXL345 in stream mode, collect samples at a fixed rate, and get an interrupt when the FIFO has been filled to a specified level (watermark). The samples can then be read in burst mode.

The samples will be on a "precise time-scale".

There are even more advanced usages of the device with tap, double-tap and free fall detect.

Please see Data Rate setting and FIFO control in datasheet.

Cheers!

PS: Using I2C at 100 KHz will take 1 ms just to address the device. Addressing a register will take another ms and a ms per data byte. Reading the data register (six bytes) will take at least 8 ms. Realistic max sample rate with I2C at 100 KHz is 10-100 Hz. There is also limited amount of memory for buffers.


running a dc motor with a small L298N module and an arduino and the L298N library I have a small L298N module which I would like to use to run a couple of dc motors. The module I have is smaller than most of the ones you see on eBay, it looks like this...

I am trying to use the following library :
https://github.com/AndreaLombardo/L298N

I have managed to get the motor going forwards and backwards, but the problem is, this module doesn't have a pin for enable ( EN for PWM from the Arduino) and the library seems to require this; therefore I can't control the speed of the motors.

Does anyone have any experience with these modules? Is there a different technique I should be using? Is there another library that works with these kind of modules?

All help appreciated.

PWM is used to control the duty cycle and not the voltage directly so your PWM will work directly on the input pins of motor driver and you will be able to control the speed.
just use analogWrite on the input pin which was held HIGH and HOLD the other pin to LOW. If you desire to change the direction while simultaneously controlling the speed. just analogWrite both the pins. Just keep in mind that the duty cycle of both the pins should not be tweaked simultaneously. while the speed is being controlled in one direction the other pin should be at analogWrite(other,0).


PWM signaling with Arduinos: What is the reason for the ground connection? This may sound like a very dumb question and I apologise in advance.

I've gone through reading about PWM and working on some example sketches to control PC fan speeds using PWM and Arduino.

In all documents I read, it is mentioned that "PWM is a signal".

My questions:

Is PWM really a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?
If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

Is PWM really a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?

At the most basic, it is a signal because we call it such. Even a constant voltage can be a signal, signalling that e.g. a window has not been broken. A PWM signal indicates that we want to apply a certain fraction of full power to a load.

  If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

Because it is a voltage-based signal, and ground serves as the reference for this voltage. Voltage only exists between two points.

  This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

Radio signals are photon-based; the oscillation of photons at a given frequency being broadcast from a location are what define the signal. Since frequencies are absolute, they can be discriminated without a (relative) reference.


Help understanding circuit for button example I´m working on the button example
.Basically, i don't quite get the use of this connection.

Also, the breadboard i'm using is not quite the ones i see on most tutorials.

is there any 'mapping' i could make between them?

I really appreciate any help you can provide.

The connection in that picture is pointless.  They are just putting power and ground on the top set of rails, but they aren't using it.

Your breadboard has only one rail on either side.  So you'll have to designate one for power and one for ground and you'll need some slightly longer wires for some of the connections.


How to install a dependency library to an Arduino compilation environment? Following approach A from this Arduino SE answer, I managed to kick off an Arduino CLI compilation in a Docker environment.

However, the project I am trying to compile has a dependency on a LCD control library.

Error output:

...../OpenSourceVentilator/OpenSourceVentilator.ino:494:116:
fatal error: LiquidCrystal_PCF8574.h:
No such file or directory
compilation terminated.

What is the proper way to link dependencies to the compilation environment of an Arduino project?

While the source suggests a direct compiler call, maybe I need a Makefile instead of the following?

arduino-cli compile --fqbn esp32:esp32:esp32 -o ignored.bin OpenSourceVentilator.ino

If the library is installed the Arduino IDE (or CLI I assume too) just finds it and compiles/links it for you.


LiquidCrystal library and timers don't seem to be compatible If I set timer2 to Compare Match mode, my LCD display stops working. If I use Overflow Interrupt it works fine.

Here's my test code. I have a loop() function which does its thing, and a timer interrupt which increments another variable, just to show it's working.

#include <LiquidCrystal.h>
#include <avr/interrupt.h>
#include <avr/io.h>

LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD:

int i;
volatile int j;
void setup()
{
  i=0;
  j=0;
  //button adc input
  pinMode( A0, INPUT ); //ensure A0 is an input
  digitalWrite( A0, LOW ); //ensure pullup is off on A0
  //lcd backlight control
  pinMode( 10, OUTPUT ); //D10 is an output
  digitalWrite( 10, HIGH ); //backlight control pin D10 is high (on)
  //set up the LCD number of columns and rows:
  lcd.begin( 16, 2 );

  // setup timer interrupt
  cli(); //disable global interrupts
  TCCR1A = 0;   //set tccr1a and tccr1b to 0
  TCCR1B = 0;
  //set cs10 and cs12 bit so timer runs at clock iSpeed/ 1024
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);

  // Compare Match Mode **Doesn't work**:
  //set compare match register
  OCR1A = 15624;
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Overflow mode **Works**
  // enable overflow interrupt
  // TIMSK1 = (1 << TOIE1);

  //enable global interrupt
  sei();
}
void loop()
{
  lcd.setCursor( 0, 0 ); //top left
  lcd.print(i);
  lcd.setCursor(0,1); //bottom left
  lcd.print(j);
  delay(500);
  lcd.clear();
  i++;
}

ISR(TIMER1_OVF_vect)
{
  j++;
}

If I use overflow interrupts it works fine, the loop() counter is displayed on the top line and the interrupt counter on the second, but by using overflow interrupts I'm limited to the whatever timing the various prescalers give me.

If I use compare match the LCD display just shows faint flickering squares on its first line, like it's doing something but too quickly for the LCD to display.

I looked at the source for liquidcrystal.cpp, and it doesn't seem to use any timer or interrupts, so I'm completely mystified.

Dang, it was a bit of a noobish error. I had the interrupt handler setup for the overflow interrupt, but when I swapped the code in for the Compare Match interrupt I didn't make a handler for it. So since there's an interrupt without a handler it seems it just resets, hence the flashy-flashy garbage I was seeing on the LCD.

Adding this fixed the problem:

ISR(TIMER1_COMPA_vect)
{
  j++;
}


Open source PLC Wifi I'm working on a project that involves a device called the plduino (aka Open Source PLC). This is the website for the device:

https://www.digital-loggers.com/plc.html

and the GitHub:

https://github.com/digitalloggers/PLDuino

Using the examples on the GitHub, I've been able to figure out other parts- storing on the SD card, the GUI, digital IO, etc. But I haven't been able to figure out the WiFi module (which seems to be through a ESP8266 device). I looked through the libraries directory on the GitHub link, but didn't find anything that looked like it connected to the internet or could send or receive data. The documentation says the device can connect to wifi, but is otherwise very little help.

Has anyone used this before? How do I make this device connect to wifi?

This is not particularly easy to figure out. The ESP8266 is addressable via a serial port. The ESP8266 firmware is called NodeMCU, which sits on top of the ESP8266 firmware and allows you write Lua code to implement custom Wifi functions. The PLC comes with example Lua that starts a webserver and publishes a webpage that allows you to check and set the status of the PLC (but only if you connect to the PLC, which is in access point mode.)

If you want it to behave like wifi on a normal desktop computer, you have to do some Lua programming (I could not find any Lua code online that did basic things out of the box, but there are a fair number of examples and snippets on the NodeMCU sites.)

In spite of how cool this device is, I ultimately decided it was just too much work to get the Wifi integration working (the Arduino stuff is of course pretty easy). You also have the problem of how to get your data logs somewhere. Since the data is on the Duino and the ESP8266 is the web interface, you either have to poll the Duino (which the example code does) and upload to a site (e.g. AWS), or log the data on the Duino, then send it over the serial port for upload -- MORE Lua and Duino coding. Plus if you want to put your data on AWS IoT (for example) the Duino/NodeMCU technically does not support the TLS 1.2 and X.509 cert handling you need to register (although they are apparently some workarounds now.) Life. Is. Too. Short. For. That.

I switched to Raspberry Pi, which is about 1000 times simpler, even though it does not have the cool features like open collectors and optical isolators. I'm now looking at Pi enclosures, such as the nice BC packaging from Phoenix Contacts. I decided it was simpler to make my own custom PLC for my home HVAC automation project than it was to code the DL-PLC. Bummer. Maybe they'll do a Pi version of this someday.

The repositories for my DL-PLC and RPi projects are on GitHub (https://github.com/dglcinc/HVAC-plc and https://github.com/dglcinc/HVAC-pi), you may find my Lua code and implementation notes useful if you want to get the wifi working on the DL-PLC. I did get it working in station mode (so you can join it to your home access point, address it with a DHCP IP, etc.) but that's about as far as I got.


Is it possible to load both the arduino bootloader and a sketch onto an atmega328p via icsp? i am familiar with uploading an arduino bootloader onto an atmega328p using another arduino via the arduino IDE. i have also installed software 'sketches' using that process which i believe leaves out the bootloader(meaning one wouldnt be able to upload new sketches in the future via usb). my question is: is it possible to load both the bootloader and a software program onto the chip via icsp? many thanks in advance.

The Arduino builder creates for AVR boards not only hex file for the sketch, but it creates a combined hex with bootloader and sketch too. It is for example for Blink.hex a Blink_with_bootloader.hex. If you use in IDE the "Export compiled binary" command in Tools menu, the builder puts the hex files next to ino file in your sketch folder.

If you want the command "Upload using programmer" to upload hex with the bootloader, modify in platform.txt the tools.avrdude.bootloader.pattern key to use "-Uflash:w:{build.path}/{build.project_name}_with_bootloader.hex:i"


Nano 33 IoT rescue from the dead: No USB. No upload mode First of all: my board used to work fine.

Now my Nano 33 IoT turns ON (green light) when connected to USB on Mac but:

doesn't enter in upload mode after pressing twice on board button.
doesn't shows up in any serial port: nor /dev/cu.usbmodem14*01, neither /dev/tty.usbmodem14*01

For reasons too long to explain, I want to connect via ANY pins to the SAMD21 and force the burning of a new bootloader.

Is that possible in any way? Any idea is welcome!

Tx

Use the SWD interface and a programmer to burn the bootloader to SAMD.

source of the picture https://medium.com/@manuel.bl/arduino-in-circuit-debugging-with-platformio-9f699da57ddc

I had luck with Adafruit DAP library using an Arduino M0 to burn a bootloader to MKR Zero.


WizNet W5100 not connecting to modern switches and routers I have an Arduino data collector with a W5100 module (see bottom of picture). Simple fixed IP connection:

 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 byte ip[] = { 192, 168, 1, 242 };
 Ethernet.begin(mac,ip);

This works with my old routers (Asus WL500, TP-Link MR3420), but fails to connect when plugged in a gigabit switch or my new router (D-Link DWR-116). The connection LED on the new devices does not lit up or blinks slowly, showing repeated connection attempts. So the W5100 fails to make the physical connection.

I made it work by adding my 10-year old Surecom switch to the mix, but wonder what the problem could be. Is there some cable configuration that is used by the W5100 but have been removed from these new network devices? (Not sure if the cable is cross or straight, trying another cable is messy, the whole thing is built in the wall.)

I think your problem is due to the MAC address that is being loading into the W5100.  Try setting the 2 low order bits of the first byte to 0.

These bits define whether the MAC address is unicast or multicast and whether it is private or universal.  Some switches appear to block ARP requests if these bits are set incorrectly.

I changed the first byte of the MAC address from x'47' to x'44' and things started working.


Using HC-05 to play a sound on an app I connected a HC-SR04 Ultrasonic Sensor to Arduino Uno and built the circuit as shown in the link below. I also used the code below the link. Together, this code and the circuit detect any motion that occurs in front of the ultrasonic sensor. When the sensor detects motion, the console in the Arduino IDE prints that it detects motion and how far away the moving object is. Otherwise, nothing is printed.

I created an app using MIT App Inventor. Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.

Does anyone have any suggestions for how I should build the circuit and what code I should use?

arduinobasics.blogspot.de/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

int prevdist = 0;

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);

 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 if (distance >= maximumRange || distance <= minimumRange){
 //Print "Out of range when there is no object within the range of the ultrasonic sensor.
 Serial.println("Out of range.");
 digitalWrite(LEDPin, HIGH);

 }
 else {

 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */

   if((prevdist - distance) > 10 || (prevdist - distance) < -10)
   {
     prevdist = distance;
     Serial.println("[OBJECT MOVED]");
     Serial.print("Detecting object ");
     Serial.print(distance);
     Serial.println(" cm away");
     Serial.println();
     digitalWrite(LEDPin, LOW);
   }
 }

 //Delay 1 millisecond before next reading.
 delay(1);
}

Every time the Arduino detects motion, I want a sound to be played on the phone of the person with the app. In order to do this, I plan on using a HC-05 Bluetooth Module.
Does anyone have any suggestions for how I should build the circuit and what code I should use?

The Arduino sketch above is a good start.
The first step is to connect the Bluetooth module so that the Serial output can be sent. The circuit is simply connecting the Bluetooth module to RX/TX on the Arduino. I am assuming that you have written an app that can read from Bluetooth on the phone and write to the screen.
The second step is to parse the output and play the sound. That is also part of the app and not the code on the Arduino. To make this easier the sketch output statements can be changed to something easier to parse (detect).
All and all the work is mainly app programming.
Cheers!


Control Stepper via Serial Monitor I would like to control my stepper via serial monitor and unfortunatley the code below did not work. Serial monitor works (Serial.println()), but it does not execute the stepperOne() part. Any ideas why would be awesome.
Thank you.

#include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

String msg;

unsigned int DEST = 800;
unsigned int SPD = 1600;
unsigned int ACCEL = 1600;
const int TEST = 3;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,HIGH);
  Serial.begin(9600);  // Start Serial

}

void loop() {

if (Serial.available()>0) {
    msg = "";
    while (Serial.available()) {
      delay(10);
      char tmp = Serial.read();
      // msg += tmp;
     if( tmp!='\r' && tmp!='\n' ) msg+=tmp; // Does not work either
    }
    msg.replace(" ","");
    if (msg=="G") {
      stepperOne();
      Serial.println("Stepper turned.");
    }
    Serial.flush();
  }
}

void stepperOne() {

  AccelStepper stepper(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper.setMaxSpeed(SPD);
  stepper.setAcceleration(ACCEL);
  stepper.move(DEST);
  if (DEST > 0) {
    while ( stepper.distanceToGo() > 0 ) {
      stepper.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }

I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. But in case someone encounters the same problem R3 did it for me.


How to use tone in two pins? I have a buzzer and an IR led emitter so I have to use the tone function to sound the buzzer and to modulate the output of the LED.
I have connected the led pin 5 of the arduino, the buzzer pin A0.

int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  tone(cr_pin, 38000);  /* For modulation at 38kHz */
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
  Serial.println("Hello");
}

This is my code but I can not make the led and the buzzer work at the same time, apparently the buzzer is affected by the tone line (cr_pin, 38000); / * For modulation at 38kHz * /.

I tried to remove (cr_pin, 38000); / * For modulation at 38kHz * /. of the setup and leave code in the following way.

int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
tone(cr_pin, 38000);  /* For modulation at 38kHz */
      Serial.println("Hello");
noTone(cr_pin);
    }

In the first code the LED works but not the buzzer and in the second code the buzzer now works but not the LED.

Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the same pin, the call will set its frequency. Source: arduino.cc - tone().

noTone() Stops the generation of a square wave triggered by tone(). Has no effect if no tone is being generated. Source: arduino.cc - noTone()


ATtiny85. How do I burn a bootloader? What is the process? I want to use all six I/O pins of an ATtiny85, that means also using the reset pin as an I/O pin, however, I found out that if I disable the RESET pin, I can no longer program the ATtiny using an ISP programmer.

However, I found out that there are bootloaders for ATtiny which, as far as I understand, allow me to program the ATtiny through USB, without the need of the RESET pin.

My question is: How do I burn such a bootloader (such as micronucleus for example) to the ATtiny85? And how do I need to connect the ATtiny to USB after that (like this?)? How do I program it after that? Keep in mind that in terms of burning bootloaders and modifying fuses, I am a complete newbie.

Also, I'm using the ArduinoISP sketch as my ISP programmer since I don't have a real ISP programmer, but as far as I read, that won't be a problem.

EDIT: I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:

Yes, there are USB interfaces for ATtiny85. Just look at one of the open hardware designs out there, e.g. Digispark.
An USB interface is going to require two pins, so using one to save one pin doesn’t strike me as cost effective.
I agree with @FAD, that you don’t really need an USB stack, and simply could do a time-delay-at-boot thing with the UART pins.
HVSP (the high voltage programming) is not hard to do. If you’re already comfortable with ArduinoISP, you can try ScratchMonkey, which uses the same approach (with a 12V power supply and one transistor) to do HVSP programming.


Serial 3 vs Software Serial So I have a program that works great on the Mega, it uses serial 3 to read and streams out to the USB (I posted a previous question which someone answered)  I tried to use Serial (D0) to read and then write to serial, which did not work.  So now I am looking in to Software Serials

Is there a difference between a real serial and software serial as it does not seem to be working, It all runs a bit slower

#include <SoftwareSerial.h>

const int DesiredRPM=300;  // Setting Desired RPM Here.
const int MotorPWMPin=4;
int inByte = 0;         // incoming serial byte
unsigned char Data_status=0;
unsigned char Data_4deg_index=0;
unsigned char Data_loop_index=0;
unsigned char SpeedRPHhighbyte=0; //
unsigned char SpeedRPHLowbyte=0;

int SpeedRPH=0;
const unsigned char PWM4dutyMax=255;
const unsigned char PWM4dutyMin=100;
unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
    pinMode(MotorPWMPin, OUTPUT);
    Serial.begin(115200);  // USB serial
    Serial3.begin(115200);  // XV-11 LDS data

    // prints title with ending line break
    Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

    // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
    analogWrite(MotorPWMPin, PWM4duty );

    mySerial.begin(115200);
}

void loop() {
    // if we get a valid byte from LDS, read it and send it to USB-serial
  if (Serial3.available() > 0) {
    // get incoming byte:
    inByte = Serial3.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

  if (mySerial.available() > 0) {
    // get incoming byte:
    inByte = mySerial.read();
    //Serial.print(inByte, BYTE);
    //Serial.write(inByte);
    Serial.print((char)inByte);
    decodeData(inByte);
  }

}

void decodeData(unsigned char inByte){
  switch (Data_status){
  case 0: // no header
  if (inByte==0xFA)
  {
    Data_status=1;
    Data_loop_index=1;
  }
    break;
  case 1: // Find 2nd FA
    if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_status=2;
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      Data_loop_index++;
    }
    break;
  case 2: // Read data out

     if (Data_loop_index==22){
      if (inByte==0xFA)
      {
        Data_loop_index=1;
      }
      else // if not FA search again
      Data_status=0;
    }
    else{
      readData(inByte);
      Data_loop_index++;
    }
    break;
  }

}
void readData(unsigned char inByte){
  switch (Data_loop_index){
    case 1: // 4 degree index
    Data_4deg_index=inByte-0xA0;
//      Serial.print(Data_4deg_index, HEX);
//      Serial.print(": ");
    break;
    case 2: // Speed in RPH low byte
    SpeedRPHLowbyte=inByte;
    break;
    case 3: // Speed in RPH high byte
    SpeedRPHhighbyte=inByte;
    SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

    SpeedControl ( DesiredRPM ) ; //
//      Serial.print(SpeedRPHhighbyte, HEX);
//      Serial.println(SpeedRPHLowbyte, HEX);
    break;
    default: // others do checksum
        break;
  }
}

// Very simple speed control
void SpeedControl ( int RPMinput)
{
 if (Data_4deg_index%30==0) {  // I only do 3 updat I feel it is good enough for now
  if (SpeedRPH<RPMinput*60)
     if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
  if (SpeedRPH>RPMinput*60)
     if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
  }
  analogWrite(MotorPWMPin, PWM4duty ); // update value
}

There are huge differences. The most important ones are:

SoftwareSerial is half duplex (it can send or it can receive, it cannot do both at once)
SoftwareSerial is blocking - while it is sending or receiving nothing else can happen

SoftwareSerial is very much a poor-man's serial port. It should only really be used for very low volume data (things like NEMA messages once a second or so) and only if you have absolutely no choice (and, let's face it, you always have a choice).


Serial Communication between ESP8266 and Arduino ( Sofware and Hardware ) I wish to connect an Arduino ( any of 328P family ) which its 5v, with ESP8266 (ESP-01, or even NodeMCU or Wemos D1 mini ) which is 3v3 logic. My goal is that ESP8266 will be in-charge of MQTT messages and other remote abilities, while Arduino board will be in charge of UP/Off/Down rocker switch and 2 relays ( For reliability I rather have this setup ). Both MCU's code is written by me using Arduino
I Know of 2 main ways: voltage divider and level shifter ( and 3rd will be to use a 3v3 logic as pro-mini - but let's leave for now ).
My questions are:
A) Does Rx Tx need a voltage to be the same ( some on-line tutorial ignore this at all )? if so, is it needed both ways ?
B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?
C) Does SofwareSerial library is recommended (again - reliability ).

Just adding a little flesh to @chrisl's excellent answer with some added technical detail:

B) Some Tutorial mention that using a voltage divider create some communication interference. It is true and/ relevant for use as explained ?

The problem here is that the resistors and the input pin's capacitance form a low-pass filter. Too high a resistance and you deform the nice clean square wave of the serial data. This limits the baud rate you can reliably use. Reduce the resistor values and you increase the frequency of the filtering, thus allowing higher baud rates, but at the cost of increased current draw from the TX pin.

Does SofwareSerial library is recommended (again - reliability ).

The problem of SoftwareSerial is twofold: it's very much a "blocking" system, whereby the MCU can't be doing anything else when a byte is being either received or transmitted, and it's very picky about timing, partly because of that blocking.  There are two factors that affect the maximum speed you can use: how fast the MCU can process the incoming signal to work out what it is, and how fast the MCU can process that decoded signal to get it stored in the buffer.
While it's possible to receive reliably a byte at 115200 baud the problem comes when receiving multiple bytes rapidly. The Arduino is not always able to take that received byte and store it in the RX ringbuffer fast enough before the start bit of the next byte arrives, so it misses it. This causes corruption in the data stream.
For this reason I never recommend more than 9600 baud (or maybe 38400 at a pinch) to give the Arduino more time to process the bytes as they arrive. However that then means that more time is spent doing the sending or receiving, which blocks the rest of your program during that time for longer.
Also SoftwareSerial is strictly half duplex: when you're receiving you can't send, and when you're sending you can't receive. It's only really of any use in a "call-response" style protocol where switching between sending and receiving is predictable.


How do I transfer more than 1 byte at once via SPI bus? I have an AD5685R DAC that I am trying to communicate with over SPI. Per the datasheet,

  ...These [24] bits are transferred to the input register on the 24 falling edges of SCLK and are updated on the rising edge of /SYNC

where /SYNC is used as chip-select.

I believe Arduino's SPI.transfer waits to receive 8 bits after sending 8 bits. But for this particular DAC, I need to send 24 straight bits on 24 clock edges before releasing the chip-select. Is this possible?

I believe Arduino's SPI.transfer waits to receive 8 bits after sending 8 bits.

Incorrect. With SPI, a byte is clocked in at the same time as a byte is clocked out. It may be that this byte is simply a dummy byte though, if the slave has nothing to say.

So for 24 bits, simply clock out 3 bytes without deasserting the select. Since SPI is a synchronous protocol there should be no issue with having a delay in between bytes provided the select is maintained.


Create a library without a class? I'd like to know if it's possible to create a library for Arduino that does not contain a class, just functions.

I know how to create a library with a class, but I'd like to create a library of general purpose functions that don't need to be instantiated to be used. Just used like the standard functions included in the Arduino IDE:  sizeof(), etc..

Is this possible?  If so, can anyone point me in the direction of a template?  I've been searching, but haven't found anything.

Thanks!

Yes, it's possible.

Just don't make a class. Just make functions instead.

Like a class-based one, have a .cpp and a .h file. In the .cpp file (or .c file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions.

In the .h file place prototypes for them. I am in the habit of adding the extern keyword, but you don't actually need to for functions.

For example:

foo.cpp:

void doSomething() {
    // whatever
}

foo.h:

extern void doSomething();

Then you can include your .h file and call your functions:

#include <foo.h>

// ...

doSomething();


What sensor do I use to measure the intensity of direct sunlight? I'm trying to measure how bright the day is on a particular day to see how it affects plant growth. The brightest sun can be 120,000 lux. It possible to measure such a large brightness? What sensor do I use?

The best options I've found is the BH1750FVI since its sheet says, "[i]t is possible to detect min. 0.11 lx, max. 100000 lx"

However, it still doesn't go high enough.

Note: I live "only" 3,494 km (2171 miles) from the equator, and it can get fairly bright here.

You can use a photo resistor. It is also known as an  LDR (Light dependent resistors) and here is a great tutorial to do just that. You can also find a conversion from the 8-bit analog value to lumens if you wish. Here is a tutorial:
https://www.instructables.com/id/Measuring-Light-Using-Light-Sensor/
You can also use a LUX which is the advanced version of a LDR. Here is a tutorial:
https://www.instructables.com/id/How-to-Measure-LUX-With-Arduino/


Infamous white squares for LCD display I would like to know what I've done wrong. I configured my circuit using the "Hello world tutorial. I got the infamous white square pattern

D7 to pin 2
D6 to pin 3
D5 to pin 4
D4 to pin 5
E to pin 11

My code:
// include the library code:
#include <LiquidCrystal.h>

//LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(2, 3, 4, 5, 11, 12);      // put your pin numbers here

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 0);
  // print the number of seconds since reset:
  lcd.print("hello, world!");
}

Your picture does not give a clear view of the connections between the Arduino Uno and the LCD module.  However, if we are to follow your description of your connections ...

D7 to pin 2
D6 to pin 3
D5 to pin 4
D4 to pin 5
E to pin 11

... and we assume D7, D6, D5 & D4 are pins on the LCD, then we see that the code is incorrect ...
LiquidCrystal lcd(2, 3, 4, 5, 11, 12);      // put your pin numbers here

... given the LiquidCrystal description here of the syntax of the overloaded (means there are more than one pattern to the passed parameters to the identically named constructor) class ...
Syntax

LiquidCrystal(rs, enable, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

... instead, try:
LiquidCrystal lcd(?, 11, 5, 4, 3, 2);      // put your pin numbers here

... as you didn't tell us how you connected the RS line I have left that value above as a "?".  So this will not compile until you fill in the missing information.
It should be added, based on what can be seen in the picture, that a connection has been made to the LCD's RS & RW pins and no connection has been made to the LCD's E (enable) pin.  But in all the constructor's overloaded versions, there is always an E (enable) pin.  Please take a closer look at your design to determine if this is a problem.


How to explain the need/advantage for volatile in terms of microcontroller instruction flow I know there are already many questions why volatile is used when it comes to interrupts.

But explanations like this doesn't help to picture what really happens:

  Specifically, it directs the compiler to load the variable from RAM
  and not from a storage register, which is a temporary memory location
  where program variables are stored and manipulated. Under certain
  conditions, the value for a variable stored in registers can be
  inaccurate.

Above is from the official Arduino website:

And below is the basic Atmega328 architecture:

Is it possible to explain the use/advantage of volatile by comparing it to the usual declaration way considering the above architecture?

I mean such way: If volatile int x is used, the CPU fetches this from this  by this way ect. And if instead int x is used the instruction flow works like this so forth and so on.

Unfortunately I have difficulty to understand from plain two sentence explanations.

As you see my question is about after the compilation what do we observe as a benefit inside the hardware during the instruction flow.

Short answer: no, volatile cannot be explained in terms of the
figure you show in your question.

Longer answer: there is no direct link between the meaning of volatile
and the architecture depicted in the figure. If you insist in linking
them together, it is possible to find a very weak and indirect link
as follows:

Volatile is all about preventing the compiler from doing some
optimizations when translating your program to assembly. Looking at the
generated assembly can help understanding the effect of volatile.
When learning the assembly language, the figure you show is helpful
in understanding the assembly instructions themselves.

As you see, the link is indirect, mostly because we are talking about
different abstraction levels. Also, the link is weak because the figure
describes specifically the AVR architecture, whereas volatile applies
to any architectures for which there is a C compiler.

To illustrate the first point above, here is an example program which
shows the effect of volatile:

volatile bool volatile_flag;
bool plain_flag;

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

void loop()
{
    Serial.print("Waiting for volatile flag... ");
    while (!volatile_flag) ; /* wait */
    Serial.println("done.");

    Serial.print("Waiting for plain flag... ");
    while (!plain_flag) ; /* wait */
    Serial.println("done.");
}

As such, the program is not very interesting, it will just hang on the
first loop. But you can imagine there being some ISR that can set the
flags when some external event happens. Then the wait loops would start
to make sense, as they wait for the external event.

Here is the disassembly of the loop() function:

    Serial.print("Waiting for volatile flag... ");
  ce:   60 e0           ldi r22, 0x00   ; 0
  d0:   71 e0           ldi r23, 0x01   ; 1
  d2:   82 e5           ldi r24, 0x52   ; 82
  d4:   91 e0           ldi r25, 0x01   ; 1
  d6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!volatile_flag) ; /* wait */
  da:   80 91 51 01     lds r24, 0x0151
  de:   88 23           and r24, r24
  e0:   e1 f3           breq    .-8         ; 0xda <loop+0xc>
    Serial.println("done.");
  e2:   6e e1           ldi r22, 0x1E   ; 30
  e4:   71 e0           ldi r23, 0x01   ; 1
  e6:   82 e5           ldi r24, 0x52   ; 82
  e8:   91 e0           ldi r25, 0x01   ; 1
  ea:   0e 94 d0 02     call    0x5a0   ; 0x5a0 <Print::println(char const*)>
    Serial.print("Waiting for plain flag... ");
  ee:   64 e2           ldi r22, 0x24   ; 36
  f0:   71 e0           ldi r23, 0x01   ; 1
  f2:   82 e5           ldi r24, 0x52   ; 82
  f4:   91 e0           ldi r25, 0x01   ; 1
  f6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!plain_flag) ; /* wait */
  fa:   80 91 50 01     lds r24, 0x0150
  fe:   81 11           cpse    r24, r1
 100:   01 c0           rjmp    .+2         ; 0x104 <loop+0x36>
 102:   ff cf           rjmp    .-2         ; 0x102 <loop+0x34>
    Serial.println("done.");
 104:   6e e1           ldi r22, 0x1E   ; 30
 106:   71 e0           ldi r23, 0x01   ; 1
 108:   82 e5           ldi r24, 0x52   ; 82
 10a:   91 e0           ldi r25, 0x01   ; 1
 10c:   0c 94 d0 02     jmp 0x5a0   ; 0x5a0 <Print::println(char const*)>

The important thing to notice is how the compiler implemented the
waiting loops. The first one is essentially

0:  lds r24, volatile_flag  ; load the flag from RAM
    tst r24                 ; test it
    breq 0b                 ; if zero, loop back

whereas the second loop is:

    lds r24, plain_flag     ; load the flag from RAM
    cpse r24, r1            ; if zero, skip the following jump
    rjmp 1f                 ; jump over the next loop
0:  rjmp 0b                 ; infinite loop
1:

You may appreciate the first loop has been translated to assembly in a
very literal way, whereas in the second loop the compiler optimized away
all but the first read of the variable. That could be translated back to
C as

if (!plain_flag) {
    for (;;) ;  // hang in an infinite loop
}

The compiler assumed the flag cannot be changed by some external event,
so there is no point in reading it repeatedly. The volatile keyword
prevents the compiler from making such assumption.

And how is all this related to your figure you may ask? Well, if you
happened to not understand the assembly code above, you could check the
AVR Instruction Set Manual to see what each instruction does,
and that's when the figure becomes helpful.


TMP36 not working with arduino uno? I have an Arduino Uno hooked up with a TMP36 and an ESP8266 to send the temperature reading to a PHP file which receives the post request and stores it in a text file.

The ESP8266 and PHP works fine and I'm positive of that. But the temperature my code gets are ridiculous and change a lot. I'll include my code and a Fritzing sketch and the URL to the data.txt (you can see the results real time). It might be a problem with my code or something else I'm not sure I've fiddled around to no success and hopefully some fresh eyes will help.

Most of the code is copypasta as I've never used ESP8266 before.

#include "SoftwareSerial.h"

String ssid ="correctssid";
String password="correctpwd";

float val=0;
int temppin = 2;
float volts=0.0;
float tempC=0.0;

SoftwareSerial esp(6, 7);

String data;
String server = "www.elijahdur.co.uk";
String url = "/arduino/esp8266/file.php"; //I've changed this just well because

void setup() {
  esp.begin(9600);
  Serial.begin(9600);
  reset();
  connectWifi();
}

void reset() {
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") ){
    Serial.println("Module Reset");
  }
}

void connectWifi() {
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);

  if(esp.find("OK")) {
    Serial.println("Connected!");
  }

  else {
    connectWifi();
    Serial.println("Cannot connect to wifi");
  }
}

void loop () {
  val = analogRead(temppin);
  volts = val * 5.0;
  volts /= 1024.0;
  tempC = (volts - 0.5) * 100;

  String string = (String) tempC;
  data = "data=" + string;
  httppost();

  delay(30000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }

  delay(1000);

  String postRequest =
  "POST " + url + " HTTP/1.0\r\n" +
  "Host: " + server + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Content-Length: " + data.length() + "\r\n" +
  "Content-Type: application/x-www-form-urlencoded\r\n" +
  "\r\n" + data;

  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

  esp.print(sendCmd);
  esp.println(postRequest.length());

  delay(500);

  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
  }

  if( esp.find("SEND OK")) {
    Serial.println("Packet sent");
  }

  while (esp.available()) {
    String tmpResp = esp.readString();
    Serial.println(tmpResp);
  }

  esp.println("AT+CIPCLOSE");

}

The txt file is located at http://elijahdur.co.uk/arduino/esp8266/data.txt

Sometimes is will straight up give -50 and it's because it reads 0 and takes away the 5V from the analog.

Any help is greatly appreciated thank you!

EDIT: Apologies, but I had mixed up my sensors and was using an LM35, it still does not work however so I'm still stuck :/

First off, as a general debugging tip: Always use a minimal example to only test one component to make sure it works. You should have tested the temperature sensor on its own, then the ESP8266 WiFi connection.

Second, regarding this code:

  /* as global variable */
  float val=0;

void loop () {
  val = analogRead(temppin);
  volts = val * 5.0;
  volts /= 1024.0;
  tempC = (volts - 0.5) * 100;

  String string = (String) tempC;
  data = "data=" + string;
  httppost();

  delay(30000);
}

The line String string = (String) tempC; looks very suspicious to me. You are casting a float to a String object, i.e., you re-interpret it with a cast operator. That should not work because a float is not a String object.

What should work is creating a new String object using its constructor, i.e., write

 String string(tempC);

If this is does not work, use the sketch at https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor, change sensorPin to 2, double check your wiring and remove the ESP8266.

And as 3rd note: You are hooking up your Arduino's TX directly to the ESP8266's RX pin, according to your schematic. This will damage the ESP8266 module, because it is a 3.3V device and should only receive 3.3V signals -- your Arduino Uno outputs 5V as a logic 'high'. You need a voltage divider or a logic level shifter between them.


Bluetooth signal returns 0 I have started programming Arduino in the last month. Now I'm working with a bluetooth module. But when I send some data from the Android device to the Arduino, it stays for a very short time and after that  immediately it becomes 0.

Why does it become 0? And how can I get rid of that problem?

Here is my code:

int x,y;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  if(Serial.available()>0)
  {
    x=Serial.parseInt();
    y=Serial.parseInt();
    Serial.print("x:");
    Serial.print(x);
    Serial.print("\n");
    Serial.print("y:");
    Serial.print(y);
    Serial.print("\n");
  }
  else
  {
    ;
  }
}

and here is the result:

Serial.parseInt() has a timeout. If something arrives on the serial, or is left over from a previous transmission and hasn't been read yet, Serial.parseInt() will start looking for a number to parse. When that fails it times out (and so does the second one immediately after it). When that timeout occurs parseInt() just returns 0.

IMHO the Arduino serial parsing routines are very poorly written and should be avoided. I have some tips on how to properly read serial here.


Why is my Adafruit motor shield not spinning my motors? I'm using the Adafruit Motor Shield v2.3. I'm powering the Arduino with a USB cable and I'm powering the motor shield with a 9 volt battery.

I removed the vin pin, and I'm using this tutorial/code to make the DC motor spin.

I've tried 3 different kinds of DC motors, but none of them will do anything. The Arduino works for normal sketches, like lighting up LEDs, but I can't get the motors to work.

Any ideas?

Edit: I'm using Adafruit's "Motor Test" code from the Motor Shield v2 library, as shown below. The motor is on port 1.

// Adafruit Motor shield library
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!

#include <AFMotor.h>

AF_DCMotor motor(4);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");

  // turn on motor
  motor.setSpeed(200);

  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tock");

  motor.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tech");
  motor.run(RELEASE);
  delay(1000);
}

A couple of things I see...

1.) Your motor leads may be shorting out of the housing of the motor. make sure they are not.

2.) You may have the motor on the wrong port for the given code:

On line 7 of the code it reads: AF_DCMotor motor(4);

So try switching physically your motor to port 4.

3.) Also, this board has an I2C address and I dont see that addressed anywhere in the code. You can check to see what the I2C address is with this code. It will also show you that the motor control board is indeed responding.

// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknow error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}


L298 module - unusual power specs I would like to purchase this dual H-bridge module. I plan on connecting it to an Arduino Uno. In the products datasheet the specified power supply (Vd) is 6.5-12V, and the voltage for the motor control pins is 2.3V HIGH and -0.3V LOW.

My question is whether this product is compatible with the standard 5V of Arduino Uno for both the power supply and logic; i.e. can I connect the Vd to the 5V terminal of the Arduino and the control pins to the digital terminals?

If not, what modifications do I need in order to use this H-bridge with an Arduino?

Note: Originally I bought this cheap module and connected the motor control pins to the Arduino, but each output returned a different output voltage!

That's a very poor datasheet. I think it's using equals signs where it means less-or-equal, so:

  High level: 2.3V = Vin = Vss

Intends to say that Vin between 2.3 and Vss will be considered high, and

  Low:-0.3V = Vin = 1.5V

Intends to say that Vin between -0.3 and 1.5V will be considered low.

"Vss" in the high level definition is confusing, because in the rest of the datasheet, "VD" is used for the logic voltage and "VS" is used for the motor; you'd expect the upper limit to be the logic voltage.

The diagram at the end of the datasheet shows how it can be used with an Arduino. A 7.5V source is going into the Vin pin (instead of the barrel jack, which is unusual). There's a protection diode on the power input which incurs a ~1V voltage drop, so the Arduino Vin pin should be outputting 6.5V, which drives the board. The digital outs from the Arduino, when driven high, are at 5V, well above the 2.3V threshold given on the datasheet.

I'd recommend powering the Arduino through the barrel jack with a 7.5V or 9V supply to drive the logic side of the board. (Powering through the USB port will put 5V or less on the Vin pin.)

You'll want a more robust supply for the motor side, because the Arduino can't deliver very much current.


Is it possible to send a float Array over I2c I have tried it several times myself but i never could send or receive it properly. I am asking myself if it is possible and if so could someone explain how?

Cheers.

Below is a simple rewrite of the Master Writer/Slave Receiver Wire Tutorial, https://www.arduino.cc/en/Tutorial/MasterWriter, for a vector of floating-point numbers.

Master Writer Sketch

#include <Wire.h>

const int DEVICE = 8;

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

void loop() {
  const int VEC_MAX = 6;
  float vec[VEC_MAX];
  uint8_t* vp = (uint8_t*) vec;

  Wire.requestFrom(DEVICE, sizeof(vec));
  while (Wire.available()) {
    *vp++ = Wire.read();
  }

  for (int i = 0; i < VEC_MAX; i++) {
    Serial.println(vec[i]);
  }

  delay(500);
}

Slave Receiver Sketch

#include <Wire.h>

const int DEVICE = 8;
const int VEC_MAX = 6;
float vec[VEC_MAX] = { ... };

void setup() {
  Wire.begin(DEVICE);
  Wire.onRequest(requestEvent);
}

void loop() {
  delay(100);
}

void requestEvent() {
  Wire.write((uint8_t*) vec, sizeof(vec));
}

  Is it possible to send a float Array over I2c

So I would answer - Yes.