Whats the difference between RF options (wifi, xbee, NRF24L01) When doing RF, you have many options.
Three of the most basic are in the title box

WiFi
Xbee
NRF24L01

What are the practical differences in using them. What is the purpose of each other and the pros and cons. What would you use depending on the application you had?

I do not have a project in mind, but i want to start learning about Rf. I searched ebay for wireless devices. but i couldnt understand the differences. My goal is simply learning

There are many different type of RF networks with various advantages and disadvantages. The main things I consider when choosing a wireless communication method are network topology, data rate and power consumption.

WiFi:

High data rate (54Mbit/s +) but also high power consumption. Used when you need to connect directly to the internet, such as an internet-of-things device, and have an external power source.

XBee:

Low data rate (250kbit/s) and low power consumption. Used to make mesh-type sensor networks; each XBee device can communication with each other, and through each other via the mesh to devices that are out of range. Used for networks of devices, particular home automation and sensors. link.

Bluetooth:

Medium data rate and medium power consumption. IEEE standard has different device profiles to enable interoperability between devices. 'Pairing' type network however, so not useful for sensor networks, but good for controlling devices using a laptop or phone which usually have Bluetooth on board. Communicates with Arduino via serial RX and TX pins. link.

Bluetooth Low Energy, ANT, etc:

Very low data rate and very low power. These RF chips can run for years on an AA battery and so are used for things like heart rate sensors. The data rate is quite low so only good for transferring a small amount of data such as sensor readings. Most devices are setup as peripherals and can only connect to one 'central' device, so no good for sensor networks. Bluetooth low energy is supported by the latest mobile phones and laptops however. Useful to enable control of a device using a phone or laptop, for example a LED lamp. (See redbearlab for some Arduino options)

GSM

Phone connection. TODO

nRF24L01 / RFM12B / RFM22B(SI4432)

Popular proprietary transceivers. They can connect via SPI and have a lot of fancy features like low power modes, multiple channels, channel hopping, frequency calibration, CRC, retransmit and so on. The nRF24L01 from Nordic Semiconductor link operates in the 2.4GHz band, others use the ISM band 433/470/868/915Mhz.
These are todays state of the art highly integrated and low cost hardware for  reliable telemetry and consumer applications. The range is between 10m and 150m. The SI4432/RFM22B has the range of about 1.5Km.

Other RF modules

Simple and cheap serial devices. Single transmitter/receiver or transceiver that operate in the ISM band link. Often used as garage door opener. Useful for sensor network where interoperability with other devices is not required and you can implement your own protocol. link


Micro-servo 9g SG90 not rotating I have an Arduino nano. I am a beginner to Arduino, so I tired the example sketches. The "Blink" sketch worked well. So now I am trying to get this Micro Servo (9g SG90) to work. No codes built in or the ones if look up on internet are making it rotate. Would love to hear how Icould make the example program "Sweep" is work.

Servo sg90 is small and can be powered from your computer or laptop connected to the Arduino. The problem does not lie there, but maybe about your connection. Make sure about these things:

Brown is connected to GND
Orange is connected to VCC
Yellow is connected to digital PWM pins.

You could use this code that I am hooking up, with several servos and using external supply but if you try doing the same make sure all the motors are properly grounded.
#include<Servo.h>
Servo ServoBase;
Servo ServoLeft;
Servo ServoRight;
void setup(){
  ServoBase.attach(6);
  ServoLeft.attach(5);
  ServoRight.attach(3);
}

void loop(){
  ServoBase.write(140);
  ServoLeft.write(120);
  delay(1500);
  ServoBase.write(40);
  ServoLeft.write(30);
  delay(1500);
}


Data transfer to and from Arduino to Raspberry Pi I am trying to transmit MPU6050 accelerometer data + data from 3 potentiometers from Arduino to Raspberry Pi. I do post processing here (on Raspberry Pi) and then transfer the data back to Arduino to move actuators. However my problem is that when I try to write the processed data back to Arduino, I see that even the stream of incoming data from Arduino starts getting corrupted and everything becomes really slow . Even If I just read serial data from Arduino, things are slower if than if I do the processing on Arduino directly. Also, the accelerometer data seems to become unresponsive i.e. its value doesn't change if I move the accelerometer. Everything just works fine if all the processing is done on Arduino. I don't know what is going wrong. Below are my Arduino and Python functions / codes.

Arduino Code:

void send_rec_data(){

    Serial.print(Kp);
    Serial.print(",");
    Serial.print(Kd);
    Serial.print(",");
    Serial.print(Ki);
    Serial.print(",");
    Serial.println(Theta_x);

    delay(20);

  if (Serial.available()>0){ // Read data sent by Raspberry Pi / Piserial

    str_data = Serial.readString();

    int firstCommaIndex = str_data.indexOf(',');

    cmd = str_data.substring(0, firstCommaIndex); // This stores the Scaled output from the Raspberry Pi

    param1 = str_data.substring(firstCommaIndex+1); // This stores the error from the Raspberry Pi to decide motor roattion direction

    Output = cmd.toFloat(); my_error = param1.toFloat(); // Change the outputs from string to float

    blink_led(); // Blink LEDS if data is received from Raspberry Pi

  }

}

Python Code:

while 1:

    data = cont.get_serial_data(arduino)

    time.sleep(0.02)

    if data is not None:

        Kp, Kd, Ki, Theta_x = data

        print(" \n Arduino sent Kp = ", Kp , "Kd = ",Kd , "Ki = ", Ki, "Theta_x = ", Theta_x)

        cont.set_tunings(Kp, Kd, 0)

        Output_scaled = cont.Compute_PID_Output(Input = Theta_x) # Compute the output of PID Algorithm

        ff = str(Output_scaled)+','+str(cont.error)

        arduino.write(ff.encode())

        print("\n Computed data sent TO ARDUINO Output_scaled = ", Output_scaled, "Error = ", cont.error)

arduino.close()

I have spent quiet sometime to resolve the issue byputting delays, flushing buffer but nothing has worked so far. Can someone please help.

Thanks.

Ok, without rewriting all your code, one thing I'm seeing here is a lot of sloooow string functions.

Pythons print function is extremely slow, for example. You should insert some timers in your code and see how long everything's taking. I think you will be surprised.

For a real-time application, which it sounds like this is, you need to be very careful and use timeouts and non-blocking code to make sure that everything doesn't grind to a halt unexpectedly.

You really need to re-write all this code, but I'll point out a few specific problems.

delay(20);
if (Serial.available()>0){
   ...
}

This is sloppy. If your python code does not process and return data before the 20ms elapses everything is going to go out of sync.

str_data = Serial.readString();

A look at the documentation reveals that this will only return on timeout, so this is guaranteed to block for 1s (I think that's the default), so there's another show-stopper problem. See this question for more info.

cmd = str_data.substring(0, firstCommaIndex);

This is also not sufficient. There is no synchronization between the pi and the arduino, so you have no guarantee that you won't get half of a previous transmission tacked onto the front of your data string (or worse). You need to make your own buffer and parse for the datastring. Or do some careful buffer clearing and use generous timeouts.

So TLDR; here's what you want to do (assuming you want to block while this exchange happens)

Clear the arduino receive buffer.
Send data packet from arduino.
Start receiving. Add received bytes to a char buffer.
Continuously search that buffer for your complete data packet.
Timeout after x ms. Handle the lack of returned data somehow.
If you do find the complete data packet, then process it.

On the Pi:

Poll for serial data. Add it to a buffer as it comes in.
Start deleting the oldest characters from the buffer if it's longer than 2x the longest data packet
Continuously search the buffer for your data packet. If you find it then continue below.
delete the data packet from the receive buffer.
process the data.
Send out return data packet to arduino.


Keyboard input arduino speed I have an Arduino clone of a Leonardo and I was just wondering how many keyboard commands I can send to the computer per second via USB. I'm not talking about the delay between send and receive (because that could vary between computer), I'm talking about the minimum possible time between something like stimulating a key press down and key press up as fast as possible.

From my tests, it has been at least 1 millisecond, however, it can depend on what is running simultaneously on the Arduino.


Calculating the time between the signal when its ON and when it gets OFF class Channel
{
    private:
        uint8_t _pin;
        uint8_t _state;
        uint32_t _rise;
        uint32_t _fall;
        uint8_t _count;
        uint8_t _channel;

        static uint8_t channelCount;

        void display()
        {
            uint32_t diff = (_fall - _rise) / 1000;
            uint32_t secs = diff % 60;
            uint32_t mins = diff / 60;
          //  Serial.print(",");
            Serial.print(_channel);
            Serial.print(",");
            Serial.print(mins);
            Serial.print(",");
            Serial.print(secs-4);
            Serial.print(",");
            Serial.println(_count);
        }

    public:
        Channel(int pin) : _pin(pin), _count(0)
        {
            _pin = pin;
            _count = 0;
            _channel = channelCount;
            channelCount++;
        }
        void process()
          {
            int s = digitalRead(_pin);
            if (s != _state)
              {
                _state = s;
                if (s == LOW)  // Fell
                  {
                    _fall = millis();
                    _count++;
                    display();
                  }
                else
                  {
                    _rise = millis();
                  }
                }
            }
        void begin()
        {
            pinMode(_pin, INPUT);
        }
};

uint8_t Channel::channelCount = 0;

Channel channels[] = { 3,5 };
#define NUM_CHANNELS (sizeof(channels) / sizeof(channels[0]))

void setup()
{
    Serial.begin(115200);
    Serial.println("Channel,Minutes,Seconds,Count");
    for (unsigned int i = 0; i < NUM_CHANNELS; i++)
      {
        channels[i].begin();
      }
}

void loop()
{
    for (unsigned int i = 0; i < NUM_CHANNELS; i++)
      {
        channels[i].process();
      }
}

This code works normally in some cases, (i.e.) It provides the exact time between the signal when it's ON and when it gets OFF in seconds.

In some cases, it spits out a 10 digit number. The correct value follows the unknown number in the screenshot attached below

I suspect secs is 0 sometimes, because of _rise being 0? In that case unsigned int subtraction causes this: secs(0) - 4 = -4 % 2^32, resulting in your 4294967292


How to connect GPS to IMU? I'm planning to connect GPS to IMU, Is't possible ? I tried my best to find an article that can help solving my curiosity.  How can i connect GPS and MPU to arduino uno?

Is not really connecting GPS to IMU, is more like you read GPS values, read IMU values and after apply what is called a sensor fusion algorithm.

One of the most common used sensor fusion algorithms is called Kalman filter (the Extended Kalman Filter more likelly). However, if you do not have some basis on control theory you may have more trouble in applying it.

here is a good example of use of this kind of sensors and fusion algorithms. It is also very commonly used in drones or autonomous vehicles.

The implementation will be specific to what you are trying to do.


How do I "conditionally" include libraries and declare global objects of them? I'm trying to write a generic "Test Bench" type of sketch using booleans to indicate whether or not to include specific libraries.  After those are defined, I'm attempting to use preprocessor #if statements to determine if the libraries need to be included and create the objects if need be.

Example:

const bool useLCD = true;

...

#if (useLCD)
  #include "NHD_4x20.h"
  NHD_4x20 lcd(9);
#endif

These statements are before the setup() and loop() functions.  This in itself doesn't generate compiler errors, however I get "lcd has not been defined in this scope" when trying to use the object in the setup() and loop() functions.

Is there some simple trick to accomplish this that I'm overlooking here ?

Thanks in advance !

const bool useLCD = true;

should be:

#define useLCD 1

Here is a complete working example of how to use preprocessor macros for conditional compilation:

#define USE_A 1
// #define USE_B 1

#if (USE_A)
int a = 4;
#endif

#if (USE_B)
int b = 6;
#endif

void setup() {
    Serial.begin(115200);
    Serial.print(F("The result is: "));
#if (USE_A)
    Serial.println(a * 2);
#endif
#if (USE_B)
    Serial.println(b * 2);
#endif
}

void loop() {
}


Using only Rx pin to receive data from HC 05 and attiny85 (Arduino IDE) I was building a Bluetooth car with attiny85 (Arduino IDE) and HC05 bluetooth module. I need 4 IO pins to control the car. Since attiny have only 5vIO's, I am left with only 1 pin to connect to HC05. I would only be receiving data from HC05. So, I want to use that leftover pin as RxD to receive data.

#include //the software serial library
#define RxD 4

SoftwareSerial blueToothSerial(RxD);

But when I do this It gives the following error

No matching function for call to 'SoftwareSerial::SoftwareSerial(int)'

Though it works fine, when I also define a TxD pin. But I want to use only one pin (RxD). Please help.

I suggest you get rid of SoftwareSerial and use instead this Simple
ATtiny USI UART. This is a driver
for a receive-only UART that uses the USI port of the ATtiny85. It is
superior to a software-only UART as it makes good use of the hardware,
leaving more time for the CPU to do more useful things (or sleep and
save battery). Also, unlike SoftwareSerial, it does not need to block
interrupts for long periods, which is a good thing.


How to find the time of any point on the graph on an Arduino serial plotter or Processing software? I am plotting the graph of some sensor values on my Arduino serial plotter which looks something like this -

But what I want to do is hover over any point on the graph and display the time at that point. Is there any way to do that, if not with Arduino serial plotter, with Processing? Or any other tool is fine too. Thanks.

The Arduino Serial Plotter is not meant for this. It just directly draws, what you send. You can solve this in processing, by calculating the time from the number of the current sample (which is what you see on the x axis in your plot) via the used sampling rate.


const char* to double I'm trying to use an if statement to check when the time goes past a specific point and run a specific function. To do this I'm looking to convert time into a double and running something along the lines of if(timeCurrent >= 8.30). I seem to however have an issue with the conversion part, normally I'm aware the standard practice in C++ would be to do the following:

DateTime now = rtc.now();
static char buffer[80];

sprintf(buffer, "%02d.%02d", now.hour(), now.minute());
String str(buffer);
double timeCurrent = strtod(str);

However, this doesn't work for Arduino. What can be done to create the same desired function?

Don't do that. Converting a time to double is highly inefficient.
Moreover, your approach suffers from a rollover issue every 24h.

If you just want to compare the time of day with 8:30, you can do it in
a very straightforward way:

if (now.hour() > 8 || (now.hour() == 8 && now.minute() >= 30))

If the long if annoys you, you can put the comparison logic inside a
static inline function. If you really want to combine hour and minute
into a single number, then convert to an integer rather than a double:

if (now.hour() * 100 + now.minute() >= 830)

This can be made more efficient if you think in binary rather than
decimal: you can build a 16-bit number with one byte holding the hours
and the other byte holding the minutes:

if ((now.hour() << 8) | now.minute() >= (8 << 8) | 30)

Again, you may encapsulate the ((a)<<8|(b)) in a macro or static
inline function if it helps with readability. If you want to compare to
an absolute time, your best option is to build a DateTime object
representing the deadline, and compare with now as:

// Assume timeout should be today at 8:30.
DateTime timeout(now.year(), now.month(), now.day(), 8, 30, 0);
if (now.secondstime() >= timeout.secondstime())

Here the secondstime() method is used to convert the DateTime into a
scalar number (a 32-bit integer of type time_t) that can be easily
compared and is far more efficient than using floats.


Simple webpage serve with Arduino ethernet shield on SD card I have been experiment with the arduino uno board from few days but can't seem to make it serve web page stored in SD card of ethernet shield.

If I print the contents of the file to serial it works properly, even embedding the HTML code works fine, but client.write() just produces a never ending garbage text of ÿÿÿÿÿÿÿÿÿÿÿÿ

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 115);
EthernetServer server(80);

File webFile;

void setup()
{
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.begin(9600);

// initialize SD card
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;
}

Serial.println("SUCCESS - SD card initialized.");
// check for index.htm file
if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
}
Serial.println("SUCCESS - Found index.htm file.");
}

void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
        if (client.available()) {   // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            // last line of client request is blank and ends with \n
            // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
                // send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");
                Serial.println("starting to open htm");
                client.println();
                // send web page
                webFile = SD.open("index.htm");        // open web page file
                if (webFile) {
                    while(webFile.available()) {
                        client.write(webFile.read()); // send web page to client
                    }
                    webFile.close();
                }
                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            }
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
} // end if (client)
}

Sorry for the poor formatting, I just copied it from tutorial, please help me out.

"ÿ" is character code 255, the erased state of a Flash/EPROM/SD. Check if your SD card format OK, 'index.htm' file is there, and your code can read it.


How to use the eclipse arduino scope? I am quite new to the Arduino stuff. I have got the Arduino IDE installed side by side with Eclipse. I am using Eclipse with the Arduino plugin, which is working well for me, including the SerialMonitor.

If you're using Eclipse with the Arduino plugin, it'll also add two new views. One is the serial monitor, the other one is called scope. Scope is a 6 channel Oscilloscope. But I don't know how to get values displayed there.

I am just curious how to use the scope there. I can't find any tutorial for this.

Can somebody explain how to show something inside the scope?

The simplot library (referenced below) is an excellent example of how to use the scope which works as advertised.
Firstly, readers should note that there are two different Arduino plugins for Eclipse ("Eclipse C++ IDE for Arduino" and "Arduino Eclipse plugin named Sloeber V3"). Only the latter has a scope and a seriel monitor that allows data to be sent.
Getting simplot and the scope to work, however, can be a problem depending on the platform. On a Mac, with the latest version of Eclipse (Neon.2 Release Candidate 2) and the Sloeber V3 plugin, the default path to the Private Library is Users/yourname/Arduino/libraries. Unfortunately, this path doesn't (necessarily) exist.
One could spend hours trying to figure out how and where to import a library when the critical library folder doesn't exist.

The solution (at least on a Mac):

Create a folder (arbitraily) named "Users/yourname/Eclipse/libraries".
Include this folder in Eclipse - Preferences - Arduino - Private Library Path
Download jantje's entire Github Arduino Library, unpack it and move the "simplot" folder into your Private Library Folder. "simplot" should now show up in the libraries.
Use: Arduino - Add a Library to the Selected Project
Or build a project using the simplot.ino example.

It should work beautifully.


Serial.availableForWrite versus Serial.flush Is there a difference between the following two line codes?

    while (Serial.availableForWrite <= 0) {}

versus

    Serial.flush()

Thanks!

The line

while (Serial.availableForWrite() <= 0) {}

waits until the serial output buffer is not full. Whereas

Serial.flush();

waits until the serial output buffer is empty.


Why does an LED sometimes flash when increasing brightness? This is admittedly a cross-post from LED fade malfunction (random flash)  but I can't get an answer on the Arduino forum.

I was mucking around with some very basic code and I noticed that when repeatedly holding an LED at 0 brightness for 1 second and then fading in to full brightness, a small flash would occasionally happen at the beginning of each fade (seemingly random).

int led = 11;
int brightness = 0;

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

void loop()
{
  if(brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    analogWrite(led, 255);
    brightness = 0;
  }
  analogWrite(led, brightness);
  if(brightness == 0)
    {
      delay(1000); //LED off for 1 second
    }

  brightness+=1; //increment brightness
  delay(20);
}

So, the thing that has me completely perplexed is that I can use a different piece of code (below) and the flash goes away!

int i = 0;
int led = 11;

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

void loop()
{
analogWrite(led, i);
delay(6);
if(i%256 == 0)
{
  i = 0 ;
  delay(1000);
}
i++;
}

Has anyone got any clue as to why this would happen? Both programs have basically the same code, except for that i is reset to 0 in the first program whereas in the second, i keeps incrementing past 255 so that analogWrite 'overflows.' I think it must be a firmware, (or maybe a software?) problem.

There is a video on youtube of it happening here, Arduino - fading LED problem.

According to the links you provide from the arduino.cc forum the question is more or less answered. If not that important, just avoid analogWrite(led,0) and make it analogWrite(led,1)

if you still want that analogWrite(led,0), I've tested your code with the advice and it seems to work OK when changing the register manually:

#include "wiring_private.h"

int led = 11;
int brightness = 0;

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

void loop()
{
  if (brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    brightness = 0;
    sbi(TCCR2A, COM2A1);
    OCR2A = 0; // set pwm duty
  }

  analogWrite(led, brightness);
  if (brightness == 0)
  {
    delay(1000); //LED off for 1 second
  }

  brightness += 1; //increment brightness
  delay(20);
}

Edit: to explain what those "strange codes" are

I'm not very expert in this field to explain how exactly this works but basically sbi is function defined in a macro by Atmel (?), it stands for "set bit in" and is used to change registers of ATmega chips. So basically what I did was change register defined by the macro TCCR2A (why? because it is the register that controls PWM in pin 11) and pass the bitmask COM2A1 (this is a mode of compare defined in datasheet) and OCR2A is a register used to store the compare value that defines duty cycle. Imagine a counter that every time it receives a tick from a signal clock it compares the value of the counter with the value stored in OCR2A and it sets the pin high or low if that value as been passed or not (more or less like this, depending on the mode stored on TCCR2A).

But in fact I've not done some black magic. I just looked into the code of analogWrite() and that is the way they use to set a value of PWM in pin 11:

void analogWrite(uint8_t pin, int val)
{
    // We need to make sure the PWM output is enabled for those pins
    // that support it, as we turn it off when digitally reading or
    // writing with them.  Also, make sure the pin is in output mode
    // for consistenty with Wiring, which doesn't require a pinMode
    // call for the analog output pins.
    pinMode(pin, OUTPUT);
    if (val == 0)
    {
        digitalWrite(pin, LOW);
    }
    else if (val == 255)
    {
        digitalWrite(pin, HIGH);
    }
    else
    {
        switch(digitalPinToTimer(pin))
        {

...

          #if defined(TCCR2A) && defined(COM2A1)
            case TIMER2A:
                // connect pwm to pin on timer 2, channel A
                sbi(TCCR2A, COM2A1);
                OCR2A = val; // set pwm duty
                break;
          #endif
...

}

So basically I just used that info to set the register to zero, as suggested from the arduino.cc forum link that you have.

If you want to know more about PWM in Arduino, this site has a lot of info and explains a lot of the modes of registers also.


Arduino Nano not visible in Serial Ports (Mac OS) I have used by Arduino countless times over the past few years and only after installing an update to Mac OS Sierra did the device stop showing up under the Serial Ports. Now only tty-bluetooth shows up no others. I have looked a countless threads where people suggest installing drivers or uninstalling drivers or rebooting. I have tried everything but still no device shows up.

I switched to my Windows partition using Bootcamp and lo and behold it works perfectly there but not in Mac OS. I would still like to use Mac OS to programme my Arduino. If anyone has any suggestions I would be very grateful!

Is it an original Nano or a clone?

The original Nano uses FTDI's FT232 ship, whereas clones use the CG340 USB-to-TTL chip. The former works fine straight away Mac OS Sierra, whereas the latter needs a driver.

The CG340 driver doesn't work under Mac OS Sierra. Fortunately, someone patched the driver and made it available at GitHub. There you'll also find some troubleshooting instructions that can help (hopefully).

From Adrian Mihalko's repository at GitHub:

ch340g-ch34g-ch34x-mac-os-x-driver

Latest macOS Sierra-compatible driver for devices using the CH340G, CH34G or CH34X chipset. This chipset is used in several Arduino-clones.

Introduction

Version 1.3 (2016-09-27) of the OEM driver for the CH34x chipset currently causes a kernel panic (a.k.a. crash) when installed on macOS Sierra. To resolve this issue, please download and install the driver in this repo.

Installation

Remove the old driver by issuing one of the following commands (depending on your installation):

sudo rm -rf /System/Library/Extensions/usb.kext
sudo rm -rf /Library/Extensions/usbserial.kext

Restart your Mac.
Double-click on the CH34x_Install_V1.3.pkg file.
Restart your Mac.
Plug in your device. It should now be listed under the /dev directory. Examples:

/dev/cu.wchusbserial1410
/dev/cu.wchusbserial1420

Troubleshooting

If, and only if, the device is not recognized after the installation (or you cannot install the driver), please disable System Integrity Protection:

Reboot your Mac into Recovery Mode by restarting your computer and holding down Command+R until the Apple logo appears on screen.
Open the Terminal (Applications > Utilities > Terminal).
In the Terminal window, type in csrutil enable --without kext (or to fully disable: csrutil disable) and press Enter.
Restart your Mac.

Please share this page!

Regards,
Adrian Mihalko


Arduino UNO + Arduino GSM Shield + Sparkfun Venus GPS I am using an Arduino UNO that is connected to an Arduino GSM shield (http://www.arduino.cc/en/Main/ArduinoGSMShield).

Now, I want to connect the SparkFun Venus GPS module to this combination. (*unfortunately due to my rep I can only post two links)

The Venus GPS works fine with the Arduino UNO by itself, but I am having some trouble getting the GPS module to communicate with the Arduino when the GSM shield is stacked on top.

The GPS powers on and begins blinking (which means it has a lock), but the serial monitor is not showing any information.

Coming from the programming side of things, I really don't understand much about electronics, so please pardon me if I am missing something basic here.

Based on what I've managed to figure out so far, I think it has something to do with the shield requiring 5V operating voltage and the Venus operating at 3.3V.

I think that when the GSM shield is plugged in, its expecting a 5V input, but the Venus GPS is only capable of sending a 3.3V signal.  Furthermore, any other 5V sensors that I am currently using don't have any problems communicating with the UNO through the GSM shield.

So, I actually have two questions:

Is this assumption correct or could something else be the cause of my issue?
If this is correct, could I use something like this logic level converter (https://solarbotics.com/product/50550/) to step up the Venus GPS input signal?

Thank you in advance for any help and guidance you are able to provide.

I received my logic level converter today and wired it in between the Venus GPS and the Arduino GSM shield.

The issue seems to be resolved and I'm able to properly receive information from the TX on the Venus GPS.  It would seem that my assumption was correct and I needed to "step-up" the 3.3V TX signal from the Venus GPS in order to use it with the GSM shield.


How to make Arduino communicate with MySQL? I am trying to send data from my Arduino to my database but it seems that the process is not successfully beginning. Here is my code for Arduino:

#include <Process.h>
#include <Bridge.h>
int temperature;
void setup() {
  Bridge.begin();  // Initialize Bridge
}
void loop() {
  int temperature = random(0, 100);
  Process p;
  p.begin("143.248.181.36/db.php");// 143.248.181.36 address of localhost.
  p.addParameter(String(temperature));
  p.run();
  delay(5000);
}

I am using xampp and I put db.php inside the htcocs folder. Can anyone point out why it does not work?

I'm not familiar with those libraries, but a quick look gives me the impression that Bridge and Process are used together to make system calls over serial connection on the host system. Based on that..

First, looking at Arduino Process Tutorial Process.begin() should call the process that you want to call. Maybe something like this:

p.begin("curl"); // Assuming you have curl installed on your host system
p.addParameter("http://143.248.181.36/db.php?temperature=SOMEVALUE");

Second, your PHP script is broken.

/ check connection

^ That comment is missing a second slash /

You should definitely get the PHP/MySQL part working standalone before attempting to integrate Arduino in the process. I'm a bit doubtful that $argv gets populated unless you're running the script from command line. If you're making a GET HTTP request (as you would with curl) you might wanna try instead

$temperature = $_GET['temperature'];

If the above works as a workaround, you should get an entry into your MySQL table if you visit the URL below with your browser.

"http://143.248.181.36/db.php?temperature=100"

In any case, get the PHP script working first in your browser. One step at a time.


What NRF24L01 module is this? I received my NRF24L01 Module today but I'm having a hard time finding any resources about this particular combination of modules!
https://imgur.com/a/HrzpvdR
I tried searching up the v200 1812A but no results...You would think the seller would have some documentation on his page but nothing.
Does anyone know what I'm dealing with here?
Thank you!

They are transparent bridge modules that are designed specifically to work together. It's intended to be kind of like a wireless UART.
This AliExpress Seller details how to use them.
You need one UART and one USB module. You plug the UART module into the USB module and plug the USB module into your computer. After about 10 seconds the modules are paired together.
You then separate them, and you can connect the UART module to your Arduino or other board.
Now you have a wireless UART between your computer and your Arduino.
Alternatively, since they have an STM32F0 chip controlling them you could hack them to do other things using stm32duino.


Arduino Zero timer setup Where would I find information on how to configure the Arduino Zero's timers?

Because this...

  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 150;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV256 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

Is completely indecipherable and highly error prone.

BOTTOM UP

The arduino Zero uses an Atmel samd21 µController. This video explains how to program the samd chips in a bottom up fashion, or at least how to gather all required information to do so. In case the video doesn't work anymore, i'll briefly rephrase it here. The main steps are:

Figure out the required registers by reading the data sheet
Consult the Atmel Software Framework(ASF) to figure out the corresponding data structures
Setup your sketch inside the arduino IDE

The bottom up process can be very time consuming, because you are searching a needle out of an haystack like, the datasheet and the ASF. So you need to tackle all the tiny bits before building the whole thing.

TOP DOWN

For some situations it is better to look for a working example program and try to figure out how its done. For this i recommend the arduino github repository. It is a very good resource for figuring out how arduino uses the ASF and helps me tune certain functions.

The top down process therefore allows to decompose a large working function into its smaller parts and dig into the interesting parts. However, it requires something to work with at the start which is not always available.

INDECIPHERABLE

Some code examples aren't understandable from the start. Once you know what the code is doing, i recommend splitting up the large pieces like this register and bit modification section into smaller ones. Extract these sections into functions with self explanatory names, and if done correctly you can get rid of the comments.

Hope this helps ;)


After update via ICSP can't use usb for Serial Reading and Usb for programming board after update software on my arduino Nano board via ICSP i can't use USB for serial monitor and update software, why?

Assuming you have reprogrammed the Arduino Nano's Atmel processor (an ATmega328) directly using the processor's ICSP pins, you may have erased the Arduino boot loader from the processor.  In such a case you no longer have an Arduino.  Rather you have an ATmega328 processor surrounded by some hardware.

To recover you need to reprogram the ATmega328 processor with the Arduino boot loader.


Arduino serial communication input string checking I am trying to check whether the input string in my serial is inside my string array, but it seems like that the condition if(array[i]==inputString) does not print true.

So here is my code:

String array[4]={"hey","jude","jane"},inputString,test;
boolean stringComplete=false;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  //int store=0;
  serialEvent();
  if(stringComplete){
    Serial.println(inputString);
    for(int i=0;i<4;i++){
      Serial.println("..");
      //test=array[i];
      Serial.println(array[i]);
      if(inputString==array[i]){
        Serial.println("true");
        break;
      }
    }
  inputString="";
  stringComplete=false;
  }
   //Serial.println(store);
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

First, you declare an array of 4 items and provide an initializer for 3. Don't know how it can even compile, maybe it is tolerated but in doubt

String [] array = {"hey","jude","jane","foo"};

Also, your serialEvent function appends \n to the string. Even if you receive string jane, you will compare jane from array with jane\n from serial

char inChar = (char)Serial.read();
if( inChar == '\n')
   stringComplete = true;
else
   inputString += inChar


How to understand the "power economy" of a voltage up-converter (boost converter)? My online video Arduino instructor makes use of various devices to amplify signals, currents, and voltages. This seems like magic to me.

For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.

I'm going to assume there must be some tradeoff here, because otherwise we can just use a giant string of these up-converters to give the world infinite energy from a single AA battery. I found the Wikipedia articles on this topic a little hard to understand, but basically gathered that if Voltage is boosted then it's at the expense of current. My questions are:

Is my understanding correct (higher voltage = lower current)?
If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?
What are the practical limits of this type of conversion?

I would appreciate a plain-language (easy to understand) answer. I'm also kind of curious how the conversion works, but I assume that will be highly technical.

He is describing a boost converter which steps up voltage at the expense of current. To quote from the Wikipedia page on that subject:

  A boost converter (step-up converter) is a DC-to-DC power converter that steps up voltage (while stepping down current) from its input (supply) to its output (load). It is a class of switched-mode power supply (SMPS) containing at least two semiconductors (a diode and a transistor) and at least one energy storage element: a capacitor, inductor, or the two in combination.

As an example, an Arduino Uno consumes around 50 mA from the power jack (at 9V) running a "do nothing" sketch like this:

void setup () {}
void loop () {}

You could say that this is consuming 450 mW of power.

9V * 0.050A = 0.450W

To run from a lower voltage the boost converter (say, 3V) you still need to get 450 mW of power, so therefore it will consume a higher current:

0.450w / 3V = 0.150A

In other words, we now need 150 mA (3 times the current) since we have 1/3 of the voltage.

Also, these converters are not 100% efficient. Say a particular converter is 90% efficient, that means it requires even more current (150mA / 0.9 in this case, being 166 mA).

The efficiency is not linear anyway. It varies somewhat depending on the input voltage and the load. There is a question and answer on Electronics Stack Exchange (Boost Converter Efficiency goes down as Duty Cycle goes up?) which discusses this.

  Is my understanding correct (higher voltage = lower current)?

Yes - in the sense that the device consumes power. Thus a higher voltage requires a lower current to deliver the same power. Conversely, if you drop the voltage you need to increase the current to get the same power.

  If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?

Yes it matters. You need a certain voltage, with the capability of providing enough current. In this particular case if your batteries can supply 166 mA then the Arduino can still run.

  What are the practical limits of this type of conversion?

You will eventually exceed the capacity of your battery to supply enough current. A more elaborate Arduino circuit may involve LEDs and motors. The higher current drain may exceed what the battery can supply, or possibly it will just be drained quickly.

Another factor is that batteries are less efficient when supplying higher current (the quoted mAh figure for a battery is usually for quite a low current). In other words, if you double the current drawn from a battery, the time the battery lasts is not half the time, it is less than half the time. One of the reasons for this is that batteries have an equivalent series resistance (ESR). At higher current drains there is a larger voltage drop over that resistance (some power gets turned into heat, in other words). Thus it isn't practical to try to get 10 amps from an AA battery. The battery will just get very hot.

  For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.

This is actually quite inefficient in the first place. The Arduino nominally can run from 5V (if sent directly to the 5V pin on the board) and 4 * 1.2V is 4.8V which should be close enough for practical purposes.

His idea is to step up the 4.8V using a boost converter to 9V (which in itself has some inefficiency) and then use the voltage regulator on the Arduino to drop the 9V back to 5V which is also inefficient because some power is now being dissipated as heat.


Is a power off sufficient to avoid problems with the Watchdog on Arduino Mega 2560? I'd like to offer some context about what I'd like to do because I might have misundertood something.

I'm trying to reduce power consumption on my device, an Arduino Mega 2560, and I've found this library

https://github.com/rocketscream/Low-Power

which uses the Watchdog to put Arduino on power saving for a predetermined interval of time; after that it reactivates what has been disabled and let the program continue its flow.

I searched for more information about the Watchdog and I found out several warnings about dealing with Watchdog on an Arduino Mega 2560, stating that it would only work with a modified bootloader:
This scared me a bit because I'm not very keen on risking to brick my Arduino (I absolutely need it to work on the next few days).

Now, I only have two Arduino Mega 2560 at my disposal and if I'm not mistaken, flashing the bootloader on an Arduino Mega 2560 using another Arduino Mega 2560 as a programmer can't be done because the procedure ends with errors:

( see http://forum.arduino.cc/index.php?topic=126160.0 )

Hence my most important question: if I test the watchdog functionality on my code (the sketch) and the Arduino happens to continually reset, can I fix the situation by powering off the Arduino?

(if you can help with my other issues as well, I'd be very grateful, I'm not sure I completely understood how these things work)

The problem you have is that once the watchdog is turned on it is very hard to turn it off again. There are certain procedures you have to go through to ensure it's turned off.

The default bootloader doesn't turn the bootloader off, and a reset doesn't turn it off either. The watchdog then fires whilst the bootloader is still waiting for communication from the PC thus making it reboot before your sketch has had a chance to run. Hence the change needed in the bootooader.

The only way to clear the watchdog is to remove the power. However as soon as your sketch runs and turns the watchdog back on you are then back at square one.

So you need to upload a new sketch to stop that happening, but that is tricky, since the watchdog keeps resetting and interrupting the bootloader. So what do you do? Well, there's a specific sequence you need to do.

Unplug the mega
Compile the new sketch
Hold the reset button on the mega
Plug in the mega
Press upload
As soon as avrdude starts release the reset button.

That way you have a chance of the bootloader running without your sketch having run first and enabled the watchdog. The bootloader runs just the once when the computer is tryung to upload the sketch, and with luck that will happen instead of your sketch running.


what is the use of "<<=" operator? I recently read this piece of code and I dont know what is the use of "<<=" in the for loop:

for (mask = 0x01; mask>0; mask <<= 1) {
    if (data & mask){ // choose bit

This is the entire code:

//Created August 23 2006
//Heather Dewey-Hagborg
//http://www.arduino.cc

#include <ctype.h>

#define bit9600Delay 100
#define halfBit9600Delay 500
#define bit4800Delay 188
#define halfBit4800Delay 94

byte rx = 6;
byte tx = 7;
byte SWval;

void setup() {
  pinMode(rx,INPUT);
  pinMode(tx,OUTPUT);
  digitalWrite(tx,HIGH);
  delay(2);
  digitalWrite(13,HIGH); //turn on debugging LED
  SWprint('h');  //debugging hello
  SWprint('i');
  SWprint(10); //carriage return
}

void SWprint(int data)
{
  byte mask;
  //startbit
  digitalWrite(tx,LOW);
  delayMicroseconds(bit9600Delay);
  for (mask = 0x01; mask>0; mask <<= 1) {
    if (data & mask){ // choose bit
     digitalWrite(tx,HIGH); // send 1
    }
    else{
     digitalWrite(tx,LOW); // send 0
    }
    delayMicroseconds(bit9600Delay);
  }
  //stop bit
  digitalWrite(tx, HIGH);
  delayMicroseconds(bit9600Delay);
}

int SWread()
{
  byte val = 0;
  while (digitalRead(rx));
  //wait for start bit
  if (digitalRead(rx) == LOW) {
    delayMicroseconds(halfBit9600Delay);
    for (int offset = 0; offset < 8; offset++) {
     delayMicroseconds(bit9600Delay);
     val |= digitalRead(rx) << offset;
    }
    //wait for stop bit + extra
    delayMicroseconds(bit9600Delay);
    delayMicroseconds(bit9600Delay);
    return val;
  }
}

void loop()
{
    SWval = SWread();
    SWprint(toupper(SWval));
}

In simpler terms mask <<= 1 is shorthand for mask = mask << 1

In general

variable operator= operand

is the augmented assignment operator which means

variable = variable operator operand


Seeed Studio motor shield My goal is to have my Arduino fire two stepper motors.  They need not be simultaneous. I'm using an Arduino Uno with 2 motor shields - specifically, the Seeed Studio Motor Shield v1.0. I know this shield uses D8-13.

Question is, how can I get the Arduino to use both shields?  Is there a way to make one of the shields take D0-D7?  If I could do that that'd be great. As far as I can tell, there's no way. The motor shields cannot be physically mounted either.

Some shields let you use jumpers or something to change the pin assignments, but I don't believe the Seed motor shield does.  What you can use is a go-between shield between the two shields to remap the pins on the top shield.  Then in your code, you just initialize the second instance using different pins.  You just have to make sure the alternate pins have the features you need, like pwm.


Arduino receives HIGH when the button is LOW I just got a simple scheme where i have a button connected to the 5V connector and to the 4th digital PIN and then i got a led connected to the 2nd PIN and to the GND. When i press the button the LED should switch on and when i don't press it, it shouldn't bright. The problem here is that i got a True value when i'm not pressing the button. What could it be? Here goes the code:

int Button=0;

void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT);
pinMode(4, INPUT);
}

void loop() {

Button = digitalRead(4);

Serial.println(Button);

if (Button == HIGH) {

  digitalWrite(2, HIGH);

} else {

  digitalWrite(2, LOW);

}

  delay(200);

}

You will need a pushbutton connected as follows:

The signal labeled Vout will connect to digital pin 4.

Explanation:

When the pushbutton is NOT pressed, no current flows through the resistor, and Vout = 0V. When the pushbutton IS pressed, current flows through the resistor, and Vout = 5V.

This resistor is called a pull-down resistor, because it pulls the signal down to ground. A pull-up resistor would reverse the operation of the pushbutton (i.e. Vout = 5V when not pressed, and 0V when pressed.)


Relay does not trigger Its my first attempt to work with relay
I tried to test my relay with this simple code

int Relay = 2; void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(Relay,OUTPUT);
}

void loop() {

  digitalWrite(Relay,HIGH);
  delay(1000);
  digitalWrite(Relay,LOW);
  delay(1000);
}

Connected to
IN -> Digital 2
GND -> GND
VCC -> 5V

The only thing is happened is the LED of the relay blinking in every sec. but can not hear the clicking sound from the relay box or testing with a multimeter's diode function the two(NC and COM) OUTs aren't close
I tried to test other relays(from the same type) but does not do anything else.

thank you for your help
What can be wrong?

NC is "Normally Connected" - this contact is connected to COM ("common") if coil of the relay is not powered - the relay is disconnected.

NO "Normally Open" is connected to COM when the coil of the relay is powered - the relay is connected.

Some relays have the coil powered when the signal from MCU is LOW.

If the coil of the relay doesn't click, but the signaling LED lights up, then VCC is not connected. Check if you plugged the wire really to 5 V on Arduino side.


Basic makefile for avr-gcc I would like to make a makefile for compiling c programs for the arduino. I am somewhat familiar with make but have never used it with avr-gcc. What is the simplest way I could put the commands below in a makefile?

$ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c
$ avr-gcc -mmcu=atmega328p led.o -o led
$ avr-objcopy -O ihex -R .eeprom led led.hex
$ avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

It's no different to working with Make and any other form of GCC.  Just set your CC variable and CFLAGS variable accordingly and work as per normal.

For instance, I just knocked this one up:

CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

That's saying that any automatic C compilation will be done with avr-gcc and the flags specified in CFLAGS.  It will by default make the hex file using OBJCOPY, which is set to the avr one, which relies on the file led.elf - so to get that file it runs the led.elf target, which links the object file led.o with the default libraries using whatever was set in CC. To do that it needs led.o, and it makes that automatically using the program specified in CC and the flags in CFLAGS.  You can then optionally to make install which will run avrdude to install the hex file into the chip.

You can make it even more generic so you can copy it in to other projects and make the minimum changes necessary:

BIN=led
OBJS=led.o test.o

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} -o $@ $^

install: ${BIN}.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:$<

clean:
    rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

That uses "automatic variables" and simple name replacement.  BIN contains the "base" of your binary files, OBJS contains the list of object files.  $@ is the name of the current target, $< is the name of the first prerequisite, and $^ is the list of all the prerequisites.  Just change BIN and OBJS to suit.  As a bonus I have thrown in make clean to remove the compiled files and just leave you with the source.


What are the sizes of each primitive datatype on a Metro M4 Express SAMD51? What are the data sizes of all the primitive datatypes on a Metro M4 Express SAMD51 C++ implementation? In some C++ implementations, int has 16 bits and in other implementations it has 32 bits. Is

And that is the only difference in fundamental type sizes. On 8-bit Arduinos int is 16 bit and on 32-bit int is 32 bit.

short is 16 bit
long is 32 bit
long long is 64 bit

https://en.cppreference.com/w/cpp/language/types


Arduino nano digital pins not working with external power source We are using an Arduino Nano for simple serial comms to fire a relay from a Windows 10 PC.

Initial issue we had was windows not recognizing the device (COM Port) when the pc is powered off (as per this link: Arduino Nano - USB not present after reboot ) so we powered the arduino nano over a 5V pin and now when Windows starts up the device is recognized.

However, as I'm learning with these chips, nothing is ever that simple. Now the relay that we are firing does not work with external power, but if you unplug the external power then the relay does fire (powered over USB)

The units are at a mine and at the moment and I believe that the problem is that the serial chip is now not responding as per this - from the official Arduino Nano page:

The FTDI FT232RL chip on the Nano is only powered if the board is being powered over USB. As a result, when running on external (non-USB) power, the 3.3V output (which is supplied by the FTDI chip) is not available and the RX and TX LEDs will flicker if digital pins 0 or 1 are high.

Note - I included the above from another question but this no longer appears on the official arduino nano page (can't past link as it's my first post)

The question is how can we get the digital pins on the arduino nano to fire using an external power source and input from a Windows PC?

Thanks

Diagram:

I think you may need to back up and start over again.

Rather than changing the power supply, you need to fix the problem that made you think you needed to change power supplies.

Following a link in a comment on the question you linked  to leads to this thread on the Arduino forums.

The suggestion there is that a particular pin on the FTDI chip on the Nano isn't connected as it should be.

To be exact, the Test pin (pin 26 on the FT232RL chip) needs to be grounded to fix the original problem you were having with communications with the Nano.

The description there fits your description.  The Nano can't talk to the PC if the Nano is connected to the PC at power on.  The same thing happens with the circuit referenced in that Arduino forum thread, but they are using another embedded system instead of a PC.

If you fix that, then you won't need to use an external 5V supply.

To back up the conclusion from the Arduino forum, here's an excerpt from page 8 (pin descriptions) of the FT232RL datasheet:

  26 TEST   Input  Puts the device into IC test mode. Must be tied to GND
  for normal operation, otherwise the device will appear to fail

You need to connect pins 25 (ground) and pin 26 (Test.)

Excerpt from the Nano schematic:

Pins 25 (ground) and 26 (Test) are right next to one another, so easy to fix.

You need to put a blob of solder on the red marked spot in this picture:


RFID/NFC Tag get data from wordpress MySQL I have a local workshop for students to teach them 3D printing/woodworking
I want to know if its possible to create RFID/NFC tags using wordpress data from MySQL or HTTP/HTTPS.
Web Scenario :
I have a wordpress website where I setup a gamefication plugin.
Each time a student takes a quiz/posts on forum he gets a "x" number of points that are accumulated on his profile.
I want to know if I can get a RFID/NFC tag to get that number of points.
Each member has a RFID/NFC tag card and with that card he can get access to different things around the workshop .
Workshop Scenario :
For each tool there will be a lock , RFID/NFC reader and a LCD display screen.
When a student want to access that tool he needs a number of points on the wordpress gamefication script that are transfered to the RFID/NFC card.
If he has the needed points a text on the LCD screen will appear with something like " You have access to this tool" and the tool will be unlocked .
Else if the user doesn't meet the needed points the LCD screen will show "You don't have the needed points for this tool, please visit [URL] to get more info" and the tool will stay locked.

I need only info if this is possible, not the way to do it.
[ In case you are kind to hand me some guides on where to start to will be great! ]

Thanks and waiting to see if this is possible!

From what I can tell it's absolutely possible but will take some considerable development time and around $30-$70 of hardware per NFC terminal. Please note I would strongly not recommend this as a first project as it has a lot of individual components that all have to work together flawlessly and each is different. Properly done this will be complex software and hardware wise although more so from the hardware side of things.

Hardware wise you need/terminal:

LCD display (I would recommend segmented for simplicity and cost)
Wifi or ethernet shield/breakout and ethernet cable if the board is not wifi compatible
Arduino (MKR1000 has wifi built in), Feather (Adafruit's boards that are frequently Arduino software compatible and have many shields available and guides written on how to use them), or cheap Arduino knock off (preferably not this option as giving money to arduino.cc, Adafruit, or other designers is important if we want new boards regularly)
NFC breakout or shield (Google/DuckDuckGo/Bing RFID-RC52 for an economical option, they're ~$4 on Ebay)
Power supply corresponding to the requirements of the chosen board + shields + breakouts
NFC tags
Lock able to be unlocked by a servo. If you expect security in absence of supervising shop manager (aka just to be safe, assume dishonesty in people using the shop) from this system, the locks need to be better than a Masterlock as those are insecure to even simple soda can shims. The rotary masterlocks can also be reduced to 100 possible combinations and then the combo can be brute forced easily from there so if you get a rotary based lock system make sure the assembly covering the dial is not easily removed.
Servo or stepper powerful enough to actuate locks
Servo or stepper driver breakout board

Then you'd just want to have the public key (note I don't mean a "public key" in the general cryptography sense but on that subject, you do want the key encrypted) to the user stored on the NFC tag and then use the arduinos+electronics to read the tags and see point values. User data from wordpress could be downloaded periodically to the boards so the individual checks don't use network resources and the system works offline.


How to continuously calibrate sensor I have a problem in calibration an LDR sensor. I want to let the sensor goes all day long and I'm using the LDR sensor as a presence sensor. The calibration values (min and max) changes all the day, and I need to detect only the peaks, or continuously change the min and the max values. Are there some defined pattern or algorithms to use?

In this situation, it may be useful to look at the differential of the signal.

One way to do this is to store the value, wait some time and read another value. You can then do:

dv = current_value - last_value

Or if you have some time metric (Perhaps clock ticks, or a rtc):

dv = (current_value - last_value) / (current_time - last_time)

You would then want to only count significantly large changes in dv. As the day progresses the light value will only change at a small rate but if someone were to block the light then there will be a large difference between current_value and last_value, causing dv to be largely negative (Indicating a loss of a lot of light) and when they no longer block the light you will get the opposite, indicating there is no longer an obstruction. (Or rather, less of an obstruction.)


Arduino ADC Reference Voltage if it is Battery Powered I am looking to possibly monitor battery power to the Arduino using its ADC.  This is fairly straight forward and simple (especially if using the Arduino API); however, if the battery is powering the Arduino and is unregulated externally, won't the ADC reference voltage constantly be dropping with the battery?  In other words, wouldn't the ADC value would constantly read the same value (the max value) even though the battery would actually be decreasing in voltage?

If this is the case, it would be both inefficient and pointless to measure the battery voltage.

... won't the ADC reference voltage constantly be dropping with the battery?

Yes, which is why you either use or measure an internal bandgap reference instead.

Use the analogReference() function to select a reference appropriate for the board in use. Note that you will need to use a voltage divider to reduce the battery voltage to a value below that of the selected reference if you wish to measure it.

To measure the bandgap voltage instead (using AVCC as a reference and working "backwards") you will need to set MUX[3:0] in ADMUX to 0b1110 and then perform an ADC reading directly (set ADSC in ADCSRA and wait until it resets, then read from ADC[H:L]).

As always, see the MCU datasheet for details.


Condition in a while loop not updated on my mkr1010 I am using a server-client system where i send data from the server to the client to turn on a led (the onboard led). Led must be turned off using digital input (labeled 7 on the connector).
I use therefore a while loop that checks the value of the input (button press). As long as value is not equal to LOW the led remains on (i use also a second led on pin 13 as doublecheck). I assume that the while loop will be left once i press the button, unfortunately this doesn't happen. The result of the condition seems not updated (remains HIGH).
I measured the voltage on the input when pressing the button and it goes from 3.3V to 0.0V so hardware seems to be OK.
From my undestanding the while loop is always (before each loop) checking the condition ? why doesn't this happen here ? did i do something wrong ?
I must use a while because i never know in advance when the button will be pressed.

this my code :

#include <SPI.h>
#include <WiFiNINA.h>
#include <utility/wifi_drv.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)

//int keyIndex = 0;            // your network key Index number (needed only for WEP)

const int buttonPin = 7;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
int buttonState;         // variable for reading the pushbutton status

int status = WL_IDLE_STATUS;
IPAddress ServerIP(192,168,0,157);
WiFiClient client;

int i;
String response;

void setup() {

  WiFiDrv::pinMode(25, OUTPUT); //GREEN
  WiFiDrv::pinMode(26, OUTPUT); //RED
  WiFiDrv::pinMode(27, OUTPUT); //BLUE

 pinMode(buttonPin, INPUT);
 pinMode(ledPin, OUTPUT);

  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
   ; // wait for serial port to connect. Needed for native USB port only
  }
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
  Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection:
    delay(10000);
  }

    // you're connected now, so print out the status:
  printWifiStatus();
}

void loop() {

if (client.connect(ServerIP, 23)) {
  client.print("90");
  String response = client.readStringUntil('\n');

  Serial.println(response);

if (response == "9") {
  buttonState = digitalRead(buttonPin);
 // Serial.println(buttonState);
  while (buttonState != LOW){
    // turn LED on:
    digitalWrite(ledPin, HIGH);
     WiFiDrv::digitalWrite(25, 255); // for full brightness
     Serial.println(buttonState);
  }
  digitalWrite(ledPin, LOW);
  WiFiDrv::digitalWrite(25, LOW); // for full brightness
        }
  }

  client.stop();
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
 Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

thanks a lot for helping me out !

while (buttonState != LOW){
    // turn LED on:
    digitalWrite(ledPin, HIGH);
     WiFiDrv::digitalWrite(25, 255); // for full brightness
     Serial.println(buttonState);
  }

You never update the value of buttonState in this while loop.  If buttonState is not LOW to get into the while loop, nothing inside the while loop will ever change it so every time it gets checked it will still not be LOW.  It's not going to surmise that you meant to read a pin just because you used that variable to read a pin once before.

But do you really need this while loop?  Couldn't you just write the led pin low when you first get a press and then write it high when it first gets released?  See the "State Change Example".  Let the loop function be the loop.  It will lead to better code.  You don't see this now because you are a novice, but you are about to paint yourself into a corner with this approach and you'll soon be rewriting the whole thing.  It's a trap that gets most new coders.  Better to get it right now.


How to interpret analog values sent to Arduino from line scanner? So I have a line scan camera attached to my Arduino Mega and I'm trying to send it a digital clock impulse and get an analog output back. The line scan camera is supposed to return 128 pixels.

So far I've been able to send the impulses and get analog values back which I am printing out. However, the values are different every time, which doesn't make sense because the camera didn't move so I assume that it should give back similar numbers.

Also, is there a way to determine what these numbers mean? Is there some way of turning analog signals into color pixels? My ultimate goals is to be able to determine if something has moved through the vision of the line scanner

Here is the datasheet for the line scanner: http://www.farnell.com/datasheets/315815.pdf

Here is my code:

void loop() {

  int delayTime = 20;
  digitalWrite(syncPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(syncPin, LOW);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int i = 0; i < 128; i++)
  {
    digitalWrite(clockPin, HIGH);
    pixelValue[i] = analogRead(dataPin);
    delayMicroseconds(delayTime);
    digitalWrite(clockPin, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int j = 0; j < 128; j++)
  {
    Serial.print("I received: ");
    Serial.println(pixelValue[j]);
  }

}

First, a preliminary note: according to the datasheet, the only time you
need a delay in your program is after reading the whole array and before
sending the next sync pulse. All the other timing requirements are
shorter than a single CPU cycle of your Mega, so no need to add extra
delays.

  the camera didn't move so I assume that it should give back similar
  numbers.

Similar: yes. Identical: no. You expect noise to make every reading
slightly different, and you also will have variations due to uneven
timing of your program (e.g. the timer interrupt kicking in from time to
time).

  is there a way to determine what these numbers mean?

They are proportional to the amount of light collected by each pixel.
That's about all you know about their meaning.

  Is there some way of turning analog signals into color pixels?

No. This is a B&W camera.


What is the minimal possible latency between arduino and PC Case specifications:

PC OS: Debian 9, x64 arch
Starting time point: i have a 1kb buffer on arduino that i want to send to host PC
Ending time point: i have recieved the buffer in a custom written C\C++ app running on a host PC
I want to send such a buffer once a second

What is the minimal possible latency - time passed between starting and ending points? and with what communication type? (serial?)

There is more to low-latency communication than just squirting data as fast as you can (though that is an important part of it).

One thing people often forget is that the Arduino can only (easily) do one thing at a time. While you're sending your buffer to the PC it can't be sampling and filling your buffer.  If you have a buffer which fills up over the period of 1 second and you want to send that buffer to the PC when full, what happens during the subsequent second while you're sending the buffer? The buffer can't be being filled while it's being sent.

Using a normal UART to USB connection as most of the normal Arduino boards (Uno, Mega, etc) use the fastest you can reasonably expect is around 1MBaud. That's about 100kB/s.  Less if you use a cheap Chinese clone with a CH340G.  Even at 100kB/s your 1kB buffer, if sent completely raw and in binary, would take around 10ms to transfer. But getting the computer to make any sense of that raw data would be hard. So you'd need to wrap it in some form of protocol (up to you to design that...) so you may get half that speed (or worse depending on your protocol design).

And during that time not much else can happen.

For smooth low-latency communication of data it is much more preferable to use "ping-pong" buffers and interrupt- or DMA-driven sampling of your data. That means that one buffer is receiving your data from whatever source, and the other is being sent to the PC. Once the first buffer is filled up they reverse roles. However, the little 8-bit Arduinos aren't really suited for that kind of thing:

They don't have much RAM to waste on two buffers
They don't have interrupts with priorities to allow samples to occur while sending
They don't have DMA to do background transfers of data to/from peripherals

If latency is really that critical you would be better using one of the ARM-based Arduinos, such as the Due, where you can also then take advantage of a high-speed native USB interface which can give much higher throughput than a UART connection. Your choice of USB endpoint can also influence the latency of your design:

Isochronous - Lowest latency, small packets, not guaranteed to be delivered
Interrupt - Medium latency, small packets, delivery guaranteed
Bulk - High latency, large packets, delivery guaranteed

Isochronous is used mainly for audio where you would notice the slightest delay in sound, but wouldn't necessarily notice or worry about a slight glitch in the quality. Interrupt is used for things like HID where you need it to respond to you pressing the keys on your keyboard nice and fast, but you're never sending much data (64 byte packet limit on interrupt transfers).  Bulk is used for things like CDC/ACM (Serial over USB) where you may want to tranfer lots of data but wouldn't notice if it's pausing for a few ms every now and then (HS USB has a 512 byte packet limit on bulk transfers, FS USB has a 64 byte limit).

One of the great things with a direct USB connection is that underneath it is all packet-based, so you can use that as your transfer protocol if you know what you're doing. Don't just rely on the CDC/ACM "pipe", but instead make use of the underlying USB protocol to send individual packets which the receiving program can then understand and break apart into the right data without adding any extra protocol overheads.

For more advanced USB programming the Teensy and chipKIT cores have far more sophisticated USB support than the Arduino core, so you may fancy taking a look at their offerings in the way of boards that may suit your needs better.


Is it possible to extend the reach of a PN532 NFC/RFID shield? I am working off an Arduino Uno with an AdaFruit PN532 NFC/RFID shield. The goal is to have a shoe box, with a false bottom. Under that false bottom would be my prototype, which I hope will be able to detect any MIFARE tag that is in the box, above the false bottom.

The range obviously for these devices is practically touching, but I was was wondering if there is anyway to extend the reach of the NFC/RFID shield, so that the entire false bottom of the box could act as that antenna.

I suspect not. NFC is designed for short range for privacy reasons. Some RFID systems have longer ranges (a few meters). They work by using an electromagnet to create a switching magnetic field. The RFID/NFC chip takes power from the magnetic field and then modulates a signal onto it, which the sensor detects. In order for it to work the chip needs to be close enough to get as strong enough field to power itself, and to modulate that field.


Multiple Push buttons to one input So I am trying to use one input to control an LCD display. The goal being that once one of the buttons is pressed it delivers a message. I have watched quite a few tutorials and can get the program to work sometimes. Yet, it is still pretty buggy and I am wondering why that is. To get this make this project work somewhat used this code.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonPin = A0;     //Button and LED pin numbers
    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!");
  Serial.begin(9600);           //Serial monitor used to determine limit values

 }

void loop()
{
  int temp = analogRead(buttonPin);   //Read the analogue input
  Serial.println(temp);               //Display the read value in the Serial monitor
  if (temp = 340)                     //Lower limit for first button - if below this limit then no button is pushed and LEDs are turned off
  {
  lcd.print("No Button Pushed \n");
  }
  else if (temp = 867)                //First button limit - if below this limit but above previous limit then the first button is pressed
  {
    lcd.print("Button 1 Pushed");
  }
  else if (temp = 156 )                //Second button limit
  {
    lcd.print("Button 2 Pushed");
  }

  else                                //If none of the previous buttons are pressed, then the third button must be pressed
  {
    lcd.print("Button 3 Pushed");
  }
  delay(100);                         //Delay for stability
}

The output sometimes is correct other times it is off. I think it has something to do with the circuit. Yet, I am scratching my head to find out what.

Michel Keijzers pointed out the issues you have in your code. But then
there is also an issue with your circuit: if you press any of the push
buttons, the analog input pin gets connected to one of the nodes of the
resistor ladder, and you get a well defined voltage reading. Good.
However, if none of the buttons is pressed, the input is not connected
to anything: it is floating. In this case the reading you get is
unpredictable, as it depends on parasitic influences of stray
capacitances, environmental noise, etc. You should modify your circuit
to make sure that the input voltage is well defined even when no button
is pressed.
Then, regarding the program, I recommend you remove everything after
Serial.println(temp);. Just make it work like this, and take note of
the readings you get in each case. Make sure they are consistent. Once
you know the values you expect, you can decide on the threshold to
apply, which should be about halfway between the typical readings. E.g.
if the two lowest values you get are 0 and 240, you would set a
threshold at 120.


Is this function subject to memory fragmentation? I'm trying to understand if the following bit of code is subject to memory fragmentation.

Let's say I incrementally build a string within a function and I don't know how large the string should be.

String f() {
    String s = String("");
    s += "a"; // ...
    s += "bc"; // ...
    return s;
}

The String object does dynamic memory allocation internally, but s is on the stack, so once the function returns, the s object presumably deallocates and dynamically allocated memory is freed.

Before this happens, the String object to be returned must be copied from s. Since String objects hold internal data in dynamically allocated buffers, this means that the s internal buffer is allocated, then the return object internal buffer is allocated, then the s internal buffer is deallocated.

The return object internal buffer allocation is sandwiched between the s object alloc and dealloc.

To me, this implies that this will cause memory fragmentation. Am I reading this properly, or is this not the case? If so, does this also imply that functions like Serial.readString are also subject to memory fragmentation?

Pretty much every use of the String object can lead to memory fragmentation. Especially concatenating and copying objects.

I cover it here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

You are much better off never using the String class and instead sticking to basic C strings (char arrays).


What does the following code in Morse Code Arduino mean? struct node *root, *currentNode;
  root = (struct node*)malloc(sizeof(struct node));
  root->value = '\0';
  root->next = 0;
  currentNode = root;

What does the following code in Morse Code Arduino mean?

Step by step:

  struct node *root, *currentNode;

Pointer variables root and currentNode. Pointers to struct node.

  root = (struct node*)malloc(sizeof(struct node));

Allocate memory for a struct node and assign root pointer.

  root->value = '\0';
  root->next = 0;

Assign struct node members using the root pointer. Assign value member to character 0. Assign next to zero, NULL, i.e. often marks end of list.

  currentNode = root;

Last assign currentNode to point to the save value as root, i.e. the allocated struct node.

Next question?


How to send numbers to Arduino UNO via Python 3 and the module serial I am new to Arduino (and computer programming in general), so I apologize if this question  looks silly.

Once I set up a basic arduino-LED connection, I have problems sending INTEGERS to arduino through the serial port. I can easily send characters such as 'm', 'o' and so on.. However if I send a number it looks like it simply does not get it.

Here is the Arduino code, ideally it should get a value from the usb port through python or the serial monitor and then adjust the brightness of the LED according to the value. (value must be in range [0,255]).

NOTE: I am using ARDUINO UNO and PYTHON 3

//--------------------------

int LED = 10;
int number;

void setup(){

pinMode(LED,OUTPUT);
Serial.begin(9600);
}

void loop(){

number = Serial.read();
Serial.print(number);
Serial.print('\n');
if(number == -1){
number = 0;
}

else if(number > 255){

number = 255;

}

else if(number < 0){

number = 0;
}

analogWrite(LED,number);
delay(1000);
}

However, when I input a value into the Serial port or through Python, for instance 0, it gives me 48 as answer (which, interestingly, is the ASCII code for 0!) and lights up the LED which is not what should happen since at 0 the LED should be off!!
I am missing something but I cannot find what... Could you please tell me what is wrong?

Here is the code I use in Python:

import serial
import time
try:
    arduino = serial.Serial(port,speed)
    time.sleep(2)
    print("Connection to " + port + " established succesfully!\n")
except Exception as e:
    print(e)

#Note: for characters such as 'a' I set data = b'a' to convert the data in bytes
#However the same thing does not work with numbers...
data = 0
data = arduino.write(valueToWrite)
time.sleep(2)
arduino.close()

what am I doing wrong or misunderstanding? Thank you.

Parsing on the Arduino can be slow and time-consuming (which is bad if you use clock prescaling or have time-critical tasks), so let's do it in Python.

The problem is that you're sending the numbers as ASCII whereas you need to be sending them as raw binary. This is where struct comes in.

3>> import struct
3>> print(struct.pack('>B', 0))
b'\x00'
3>> print(struct.pack('>B', 255))
b'\xff'
3>> print(struct.pack('>2B', 255, 0))
b'\xff\x00'
3>> print(struct.pack('>H', 9000))
b'#('

So what you really want is:

data = arduino.write(struct.pack('>B', valueToWrite))

or something to that effect.


Arduino library redeclaration error This is my first time here and I hope someone can be of help!
I'll try to keep it as concise as possible.

So I have two sensors/modules, 1 is an LCD screen from elecrow and another is the DS1307. Both are connected through analog 4 and 5. I tried hooking them up with the help of my breadboard but I've stumbled upon the following issue with the libraries (I don't even know if what I'm trying to achieve is possible but I'm trying nevertheless(and failing horribly while at it))

In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:31: error: redeclaration of 'OFF'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                   ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:457:5: note: previous declaration 'LCD_SwitchState OFF'
         OFF=0x00,

         ^
    In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:42: error: redeclaration of 'ON'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                              ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:458:5: note: previous declaration 'LCD_SwitchState ON'

         ON=0x01

         ^

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

What I make out of this, is that the libraries are conflicting with each other on the following:

OFF = 0x00
ON = 0x80
ON= 0x01

Is there anyway to fix this? I know that I have to edit the .h libraries but I don't know what to change and to what it should be changed, here's the library code on the module itself:

// RTC based on the DS1307 chip connected via I2C and the Wire library
enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

class RTC_DS1307 {
public:
   boolean begin(void);
   static void adjust(const DateTime& dt);
   uint8_t isrunning(void);
   static DateTime now();
   static Ds1307SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(Ds1307SqwPinMode mode);
   uint8_t readnvram(uint8_t address);
   void readnvram(uint8_t* buf, uint8_t size, uint8_t address);
   void writenvram(uint8_t address, uint8_t data);
   void writenvram(uint8_t address, uint8_t* buf, uint8_t size);
};

Thank you for your help!

C.C

EDIT:
I think that I might have come a bit closer. I tried implementing one of the answers and that made me get the following error:

    C:\Users\c\Documents\Arduino\libraries\RTClib\RTClib.cpp:284:1: error: 'Ds1307SqwPinMode' does not name a type

 Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() {

 ^

exit status 1
Error compiling for board Arduino/Genuino Uno.

That's a whole lot less than before. I will keep this updated!

EDIT 2:

Meanwhile, I tried something entirely else like changing the name of OFF and ON Throughout the RTClib concerning only the DS1307 module. That however gives me an entirely new line of errors such as:

error: 'enum Ds1307SqwPinMode' is not a class or a namespace

  RTC_DS1307 Ds1307SqwPinMode::readSqwPinMode() {

                                              ^

and:

error: could not convert '(Ds1307SqwPinMode)mode' from 'Ds1307SqwPinMode' to 'RTC_DS1307'

   return static_cast<Ds1307SqwPinMode>(mode);

                                            ^

These errors in particular only take place in the .cpp library
This is where I am stuck now at the moment

A general rule is to keep definitions such as enum's within the context of the class (library). Below is a possible refactoring:

class RTC_DS1307 {
public:
   enum SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

   ...
   static SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(SqwPinMode mode);
   ...
};

Cheers!


error: 'analogRead' was not declared in this scope I am using Codeblocks with arduino IDE to simulate the control of a stepper motor, and the errors "'analogRead' was not declared in this scope" and "'A0' was not declared in this scope" keep popping. The code follows:

#include <Stepper.h>

const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;  // number of steps the motor has taken

void setup() {
}

void loop()
{
    int sensorReading = analogRead(A0); //ERROR

    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);

    if (motorSpeed > 0)
    {
        myStepper.setSpeed(motorSpeed);
        myStepper.step(stepsPerRevolution / 100);
    }
}

EDIT: Sorry I forgot to mention it clear, but I do not own a board, that's why I'm trying to simulate it on PC.

// yours code looks Ok, but i think problem is with Arduio IDE setting. Go to the "Tool > Boards...." in arduino IDE and make it sure that you have selected the right option of Arduino module. Mean it is same as you are using in hardware?


Use object of other class within class I am writing a class for a project which will take care of handling any LCD updates for my project. The way I want to handle this is to initialize the LCD object in my main file, and then pass the LCD object on to my own class when initializing it.
The LCD object should be declared a private object in my class so several member functions can access it.

The problem is I can't find how to initialize the object correctly in the .h file.
Below is what I currently have, but when I try to build it, I get:

LCDController.h:_Clcd1' should be initialized
LCDController.h:_Clcd2' should be initialized

main .ino file:

void setup()
{
  //LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
  LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
  LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

  LCDController.init(lcd, lcd2);
}

LCDController.h file:

// LCDController.h

#ifndef _LCDCONTROLLER_h
#define _LCDCONTROLLER_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif
#include <LiquidCrystal.h>
class LCDControllerClass
{
 protected:

 public:
    void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2);
private:
   void _UpdateLCD(int iLine, int iPosition, String cText);
   LiquidCrystal& _Clcd1;
   LiquidCrystal& _Clcd2;
};

extern LCDControllerClass LCDController;

#endif

LCDController.cpp file:

#include "LCDController.h"
#include <LiquidCrystal.h>

void LCDControllerClass::init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1.begin(40, 2);
   _Clcd1.clear();

   _Clcd2 = Clcd2;
   _Clcd2.begin(40, 2);
   _Clcd2.clear();

}

In C++, a class that holds reference members (in your sample, LiquidCrystal& _Clcd1; and LiquidCrystal& _Clcd2;) must ensure these references are initialized at construction time, not later.

This means your void init(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2); method is not the right way to initialize _Clcd1 and _Clcd2 because it will be called after construction time.

You have 2 ways to solve this issue,t hat I will detail further below.

HOWEVER, before we discuss the solutions, you must be aware that your sample code has a huge defect in setup() method code!

void setup()
{
    //LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
    LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
    LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

    LCDController.init(lcd, lcd2);
}

Here, you create lcd and lcd2 in your setup method, but their life ends at the end of setup(), because they have been allocated on the stack. Using these outside setup() will most likely cause your program to crash as soon as your loop() tries to access lcd or lcd2, indirectly through LCDController method calls.

To remove this defect, you must declare these variables outside setup:

//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(lcd, lcd2);
}

Now you can use them anywhere in your program, you are sure they are present and "alive".

Now we can go to the solutions of the original compilation problem.

1. Initialize references at construction by adding a constructor

class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2) {}
    ...
};

You can still keep an void init() method to complete the initialization if you don't want it to occur right at construction time, or you can fully integrate the current init() content into the constructor and re,voe init() altogether:

class LCDControllerClass
{
    public:
    LCDControllerClass(LiquidCrystal& Clcd1, LiquidCrystal& Clcd2)
    : _Clcd1(Clcd1), _Clcd2(Clcd2)
    {
        _Clcd1.begin(40, 2);
        _Clcd1.clear();

        _Clcd2.begin(40, 2);
        _Clcd2.clear();
    }
    ...
};

In anycase, you will have to change the way you instantiate your LCDControllerClass LCDController which you did not show in your sample code, that would be something like this:

LiquidCrystal lcd(...);
LiquidCrystal lcd2(...);
LCDControllerClass LCDController(lcd, lcd2);

That obviously requires that you can instantitate lcd and lcd2 before creating LCDController. If that is not possible for you, then  you'll have to use the second way.

2. Replace references with pointers

As mentioned before, in a class reference members MUST be initialized at construction time (moreover, they cannot be changed afterwards, to point somewhere else). This is not the case for pointers however:

class LCDControllerClass
{
    public:
    void init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2);

    private:
    void _UpdateLCD(int iLine, int iPosition, String cText);
    LiquidCrystal* _Clcd1;
    LiquidCrystal* _Clcd2;
};

void LCDControllerClass::init(LiquidCrystal* Clcd1, LiquidCrystal* Clcd2)
{
   _Clcd1 = Clcd1;
   _Clcd1->begin(40, 2);
   _Clcd1->clear();

   _Clcd2 = Clcd2;
   _Clcd2->begin(40, 2);
   _Clcd2->clear();
}

Note that now, you need to use the arrow notation -> to access _Clcd1 and _Clcd2 members (dot notation cannot work for pointers).

The rest of the code should be slightly modified to reflect this change:

//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);  //declare two LCD's
LiquidCrystal lcd2(12, 10, 7, 6, 5, 4); // Ths is the second

void setup()
{
    LCDController.init(&lcd, &lcd2);
}

Note that we now have to pass the address of lcd and lcd2 to init(), by using & before their names.


Function pointer call results in InstrFetchProhibited (ESP32) I have the following issue which I'm unable to resolve by myself. Perhaps one of you could point me to issues in my code which I don't see.

There is a class called communicator which handles an MQTT connection. I use PubSubClient as a MQTT client. The constructor of communicator looks like the following. Besides connection arguments, it also receives an array of structs SubscriptionHandler. These structs define which topics should be subscribed to and also point to a callback method. When a communicator receives a MQTT message, it compares the topic to the known ones and calls the appropriate callback.

Communicator(char * mqttBrokerIP, uint16_t mqttBrokerPort, char *mqttUsername, char * mqttPassword, char * mqttClientHostname, SubscriptionHandler subscriptionHandlers[], int lenHandlers);

SubscriptionHandler. is defined like this:

typedef void (*callback)();

struct SubscriptionHandler
{
    char *Topic;
    callback Callback;
};

I tried the following: In the main file, I defined two methods for demonstration purposes:

void enableHandler()
{
  Serial.println("enable handler");
}

void disableHandler()
{
  Serial.println("disable handler");
}

The communicator is created in the setup()-Method:

SubscriptionHandler handlers[] = {{&strEnable, enableHandler},
                                    {&strDisable, disableHandler}};

callback (in communicator.h) typedef void (callback)();

strings : String strEnable = ("test/" + hostname + "/command/enable"); and the same for disable. Those are also defined in main.cpp –

As soon as the communicator receives a MQTT message, the ESP32 crashes with the following message:

Guru Meditation Error: Core  1 panic'ed (InstrFetchProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x3ffc9306  PS      : 0x00060c30  A0      : 0x8017e97c  A1      : 0x3ffb1ed0
A2      : 0x3ffc9306  A3      : 0x3ffc9306  A4      : 0x3ffc9306  A5      : 0x3ffc1318
A6      : 0x3ffb1f44  A7      : 0x00000000  A8      : 0x800d4df0  A9      : 0x3ffb1eb0
A10     : 0x0000000d  A11     : 0x0000000b  A12     : 0x3ffc24a4  A13     : 0xa98b32f8
A14     : 0x3ffc1318  A15     : 0xff000000  SAR     : 0x00000004  EXCCAUSE: 0x00000014
EXCVADDR: 0x3ffc9304  LBEG    : 0x400014fd  LEND    : 0x4000150d  LCOUNT  : 0xffffffff

Backtrace: 0x3ffc9306:0x3ffb1ed0 0x4017e979:0x3ffb1f00 0x400e280e:0x3ffb1f20 0x400d4f3e:0x3ffb1f70 0x400d5cff:0x3ffb1f90 0x400e4c45:0x3ffb1fb0 0x400889dd:0x3ffb1fd0

Therefore, something is wrong with how I use the function pointer (or somewhere which I don't even think about). Could anyone give me a hint where I could start?

I found the issue. After moving SubscriptionHandler handlers[] = ... out of the setup()-method, the function calls work. Perhaps handlers gets overwritten after leaving the setupfunction scope. Could anyone validate my suspected reason?