Accessing 2 dimensional array in PROGMEM inside loop I am unable to access elements of a 2D PROGMEM array from inside a loop. Please see the following example:

const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

  Serial.println(pgm_read_byte(&(arr[0][0])));
  Serial.println(pgm_read_byte(&(arr[1][0])));
  Serial.println(pgm_read_byte(&(arr[2][0])));
  Serial.println(pgm_read_byte(&(arr[3][0])));
  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(":");
    Serial.println(pgm_read_byte(&(arr[i][0])));
  }
  int j = 0;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 1;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 2;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 3;
  Serial.println(pgm_read_byte(&(arr[j][0])));
}

void loop() {

}

The output is:

97
101
106
114
0:12
1:174
2:12
3:148
97
101
106
114

I verified and re-verified the syntax so many times. could not find anyone facing similar issue. I am at my wits end why it would not print correct values inside the loop. Any ideas?

EDIT: expected output is:

97
101
106
114
0:97
1:101
2:106
3:114
97
101
106
114

After going through link given by Juraj above again, I could make it work as follows:

const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

void setup() {
  Serial.begin(74880);

  Serial.println(pgm_read_byte(&(arr[0][0])));
  Serial.println(pgm_read_byte(&(arr[1][0])));
  Serial.println(pgm_read_byte(&(arr[2][0])));
  Serial.println(pgm_read_byte(&(arr[3][0])));
  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(":");
    Serial.println(pgm_read_byte_near(pgm_read_word(&(arr[i])) + 0));
  }
  int j = 0;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 1;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 2;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 3;
  Serial.println(pgm_read_byte(&(arr[j][0])));
}

void loop() {

}

Now it shows the expected output and access from inside loop using variable index is possible. Thanks.


Control Speed of DC FAN Using Arduino PID Library I want to make a circuit that control speed of DC fan Using Arduino PID Library to get thing at specific temperature.

The circuit looks like this but can be changed, The dc fan motor connected to PWM 3 and thermistor connected with pin A0.

The thermistor check the temperature of a device that heated by nearby heater so fan cools the device to get the specific temperature.

Case 1

When Heater not running, the thermistor value in Serial monitor 0-1023, When fan not running it gives 1023 and when fan runs at full speed it gives about 0.

Case 2

But when heater is running the values of thermistor has been changed and when fan not running it gives 1023 and when fan runs at full speed it gives about 500.

I want to set a point 650 from thermistor value(INPUT Value), and fan speed have to adjust using pid so temperature adjusted and the thermistor gives 650 value.

Sample PID code

 #include <PID_v1.h>
//Define Variables we'll be connecting to double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);
void setup()
{
  Serial.begin(115200);
  //initialize the variables we're linked to
  Input = map(analogRead(0), 0, 1023, 255, 0);
  Setpoint = 650;
  myPID.SetOutputLimits(0, 255);
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}
void loop()
{
  int sensorValue = analogRead(0);
  Input = map(analogRead(0), 0, 1023, 255, 0);
    double gap = abs(Setpoint-Input); //distance away from setpoint
  if(gap<10)
  {  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
     //we're far from setpoint, use aggressive tuning parameters
     myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  analogWrite(3,Output);
  Serial.println(sensorValue);
}

What changes have to done in code so we can set point from input values?
And
Please help me so this code works for me.

Two thing that may be helpful.
First make sure you have a common ground. For instance for you transistor you are using separate power from the arduino and 12 volt source. Connecting the two ground of the arduino and the power supply may resolve this for you.
The other thing is it is often times helpful to put a capacitor across the DC motor to help with voltage fluctuations.


ESP8266 (Huzzah Feather) I2C scanner finds nothing I am trying to address an I2C device on my Huzzah Feather (Adafruit) ESP8266, but the I2C scanner tool does not detect anything.  All is sufficiently powered and quadruple checked the wiring.

Is there something I am missing for this board in regards to I2C connections?

I've had no issue on an Arduino, which uses the 2 pins on the Analog rail for I2C...

The Huzzah has no Analogue But the one pin, regardless, Huzzah Feather has different (still pin 4 & 5 tho) I2C,  and not via A0 A1 like on the Uno.

Do I need to dig deep and change some pin configurations for the Huzzah?

Thought I would ask before wasting more time on trial and error experiments.

Update Note:

I failed to mention there is a Feather Neopixel board (4x32) hard soldered to the board. Which I suspect is not the culprit as this issue also persists on same board without the neopixel shield attached.

Update

The soldering job was good, but discovered a faulty wire.  This allowed the I2C scanner to detect the i2C controller (LCD2004) at the address of 0x3F...

I checked with a I2c LCD library example, and I don't get any characters to come up... This is the same with both Huzzah Feather boards, one with Neopixel shield and the other is bare.

This particular issue was due to a faulty wire on the I2C bus. I replaced the wire and I was able to scan and get an address to the I2C LCD controller.

I still cannot get text to the LCD.  I will start a new question for that.

EDIT:

Upon scrapping my I2C_LCD_DISPLAY library, I downloaded one that was linked in a ESP32/8266 tutorial for the LCD, and finally got it working.


Cannot upload program to Arduino Duemilanove w/ Atmega328 This is the error I receive while trying to upload to the Arduino.
I have installed FTDI drivers for mac. (http://www.ftdichip.com/Drivers/VCP/MacOSX/FTDIUSBSerialDriver_v2_2_18.dmg)

The board is part of a quadcopter: https://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=50460

The processor is an Atmel 328P. Do I have the correct drivers?

What else could be the issue?

You may have wrong port:  /dev/tty.usbserial-A9007LXq works with Duemilanove on my Mac.


What are the units of output of soil moisture sensor? I want to use a soil moisture sensor using arduino uno R3. I am using the analog output. The values are in the range of 100 to 1300 as in the readings mention in this question.

May I know what exactly these numbers mean? I read in a website that:

  Most soil moisture sensors are designed to estimate soil volumetric water content based on the dielectric constant (soil bulk permittivity) of the soil.

So what are the units? Basically I want to base an estimate for the normal amount of soil moisture for typical loamy soil and I don't understand how to base this threshold based on the readings given by the sensor. It would be greater help if someone actually knows what an appropriate soil moisture threshold is for loamy soil.

I searched on the internet but the closest i could come to answers was this table and this particular entry:

  Table 1.1. Typical field capacity and wilting point values (m^3
   m^(–3)) for different soil textures

  Soil texture| Field capacity| Wilting point| Available water

  Loam    |0.27| 0.12| 0.15|

I am so sorry if I seem confused but I am very new to the whole of sensors and electronics
This is the sensor that I am making use of

Those sensors have no units. If you can find a schematic you could possibly relate the value to the resistance of the soil, but you'd need to know the resistance that the soil is paired with to form the resistive divider.

All you can say from the numbers is "This is wet" or "This is dry". Normally you would use trial and error to determine what the values roughly relate to, and say that "Anything under X should trigger watering. Anything over Y should stop watering."


Assigning an element of a multidimensional array to a second array I have two arrays. The first array is a multidimensional array holding color values.

The 2nd array stores an active color from the 1st array.
How can I assign an element from the multidimensional colors array to the 2nd EXCLUSIVE_COLOR array?

int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 }
};
int EXCLUSIVE_COLOR[3] = {0};

I tried the following but neither seemed to work:

    EXCLUSIVE_COLOR = {
      colors[0][0],
      colors[0][1],
      colors[0][2]
    };
    // error: assigning to an array from an initializer list

    EXCLUSIVE_COLOR = colors[0];
    // error: invalid array assignment

You can copy the array:

EXCLUSIVE_COLOR[0] = colors[0][0];
EXCLUSIVE_COLOR[1] = colors[0][1];
EXCLUSIVE_COLOR[2] = colors[0][2];

but this doesn't work in an initialization.

Alternatively, you can declare EXCLUSIVE_COLOR as a pointer to an
array of 3 integers:

int (*EXCLUSIVE_COLOR)[3]; // pointer to array 3 of int

Then you can have this point to a row of the 2D array, either by
assigning the pointer or in the initialization:

int (*EXCLUSIVE_COLOR)[3] = &colors[0];  // initialization

// Later in the program:
EXCLUSIVE_COLOR = &colors[1];

Note that when using this pointer, you will have to explicitly
dereference it:

for (int i = 0; i < 3; i++)
    Serial.println((*EXCLUSIVE_COLOR)[i]);

Edit: As pointed out by Juraj in a comment, you can instead make
EXCLUSIVE_COLOR a pointer to int. In this case you will make it point
to the first element in the row you want:

int* EXCLUSIVE_COLOR = &colors[0][0];

One nice thing of this approach is that you can use the “decay to
pointer” feature of the language to simplify the syntax:

int* EXCLUSIVE_COLOR = colors[0];

// Later
Serial.println(EXCLUSIVE_COLOR[i]);


Micro is not recognised as HID device Being a completely noob with Arduino (but not with coding though) I'm trying to create a simple buttonbox with a Micro unit.

For now, I can not figure out what should I do to make my Windows 10 recognize the Arduino as a HID device (joystick actually). What did I miss?

Joystick (github.com/MHeironimus/ArduinoJoystickLibrary) lib did the job. @chrisl, thx for the patience.


Suggestions for latest ESP8266 WiFi module I am having problems with the ESP8266-01 I bought. It works at only 115200 baud rate and it gives many problems when programming with Arduino Uno. I got it flashed to 9600 baud rate, but still many times it becomes unreliable.

I have seen many videos online that has the ESP8266 that works at 9600 by default.

Could someone please tell me where I can buy the latest ESP8266 that runs at 9600 baud rate by default?

No, I'm afraid we can't, since we're not ESP8266 salesmen.

However, I would seriously recommend not using an Arduino to communicate with the ESP8266 but instead to program the ESP8266 directly so you don't have any communication worries.  If you want to add an Arduino into the mix at a later date for its enhanced IO capabilities, then feel free to do so - where you can then implement your own serial protocol at whatever baud rate you like (or other protocol even - SPI? I2C?).

All you need is:

The Arduino core for the ESP8266: https://github.com/esp8266/Arduino
Some form of USB serial adapter (eg FT232 breakout board).

The controller chip on the ESP8266 is considerably more powerful than the Arduino's chip, and the fact that many people insist on using the ESP8266 as a slave device to the lower powered Arduino always seems completely backward to me.

If you want an easier board to program that messing with breakout boards you can do a lot worse than investing in a NodeMCU board. Make sure you go for the version 1 not the version 0.9 since the version 1 has a slightly more enhanced chip on it with more IO facilities than the version 0.9.


problem uploading arduino sketch on esp8266-12e i have a new mac os sierra installed.
i just installed arduino IDE and the serial drivers for mac os x to make the serial usb port available for esp8266 device

when i try to flash the device through the IDE i have these errors:

Arduino:1.8.3 (Mac OS X), Scheda:"NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

Archiving built core (caching) in: /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_cache_169716/core/core_esp8266_esp8266_nodemcuv2_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_244c37a477ed4ef8a63952f7a6e6a50b.a
Lo sketch usa 222149 byte (21%) dello spazio disponibile per i programmi. Il massimo è 1044464 byte.
Le variabili globali usano 31524 byte (38%) di memoria dinamica, lasciando altri 50396 byte liberi per le variabili locali. Il massimo è 81920 byte.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: unslip sequence wrong
warning: espcomm_send_command: can't receive command response header
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

what can i do?

I installed another version of the driver from silabs' website and now it's working.


HC-05 to low cost AB shutter 3 I'm trying to connect a HC-05 to AB Shutter3 module. However, when I try to search AB Shutter3 address via AT commands (AT+INQ) I could not find AB Shutter3.

I want to integrate both, so that I can send commands from an AB Shutter button click to HC-05.

I also want to know whether the HC-05 needs to be in master or in slave mode.

I rather suspect the AB Shutter 3 is a Bluetooth HID device (like a keyboard or a mouse). The HC-05 can only communicate with Bluetooth Serial devices, such as the HC-06 or systems that can emulate a serial device (such as a computer or a smartphone).

You won't get them to communicate no matter how hard you hit them.


From Strings to int problem I create applications for a computer that is to be used to control the robot arm. I wanted to make the first attempt to run the application not on the motor, but on the diode and check if it will change its brightness depending on the position of the slider. I wrote an application in Qt that sends thongs to Arduino, and Arduino I read and converts to int. The problem is that although the slider is set to 0, the Arduino does not show it, often the figures do not agree too often (often too small), also when I suddenly move the number slider all the time count towards the front instead of back.

Arduino code:

String br;

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

void loop()
{
   while (Serial.available()>0)
 {
    br = Serial.readString();
    analogWrite(9, br.toInt());
    Serial.println(br.toInt());
 }
}

Qt code:

void MainWindow::on_horizontalSliderGrip_sliderMoved(int position)
{
   this->sendMessageToDevice(QString::number(position) + "n");
   qDebug() << "Grip: " << QString::number(position);
}

void MainWindow::sendMessageToDevice(QString message)
{
   if(this->device->isOpen() && this->device->isWritable())
   {
       //this->addToLogs("Sending information to the device " + message);
       this->device->write(message.toStdString().c_str());
   }
   else
   {
       this->addToLogs("I can not send a message. The port is not open!");
   }
}

As Majenko wrote in his comment, your problem lies with Serial.readString(). It is generally not a good way to handle Serial data. It reads data from the Serial interface, until the timeout (default 1s) occurs. So it will try to read until 1 second after your last change of the slider and return the whole data as one string. String.toInt() will then start to read the string from the first character and convert them to an integer, until it reads a non-digit character (meaning the n, that you send). It stops there and returns the already converted value.

This means, that out of all the data, that was send to the Arduino, only the first value will be used. The rest get's thrown away.

Better you should use a non-blocking code, that handles the messages (numbers in your case) correctly. This is done by reading the incoming serial data byte by byte, adding them into a buffer, until a special delimiter character get's received. Then the message get's processed as a whole. After that, the next message can be read and processed. This way you don't miss any of the send values.

The special delimiter character is arbitrary; you can use any character, that does not occur in the valid data. So using the character n is ok here. But mostly the newline character \n is used, so that you can also send messages with alphanumeric characters. Most likely you already meant to use \n.

As an example of this serial code, you can take the readline() function from Majenko's blog post:

char buf[80];

int readline(int readch, char *buffer, int len) {
    static int pos = 0;
    int rpos;

    if (readch > 0) {
        switch (readch) {
            case '\r': // Ignore CR
                break;
            case '\n': // Return on new-line
                rpos = pos;
                pos = 0;  // Reset position index ready for next time
                return rpos;
            default:
                if (pos < len-1) {
                    buffer[pos++] = readch;
                    buffer[pos] = 0;
                }
        }
    }
    return 0;
}

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

void loop() {
    if (readline(Serial.read(), buf, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buf);
        Serial.println("<");
    }
}

You can convert the character buffer to an int with atoi() in the if statement in void loop() and use it for ´analogWrite()`.


How to filter a blank line received over serial - ESP8266 How can I filter a garbage completely blank line over my serial data? It comes from the wifi module ESP8266

How I read data:

  while (Serial1.available()){
       String inData = Serial1.readStringUntil('\n');

       Serial.println("Got: " + inData);

  }

Here is my common output:

Got: AT+CIPSEND=6
Got:
Got: OK
Got: >
Got: Recv 6 bytes
Got:
Got: SEND OK
Got:
Got: +IPD,21:Volume From: 99 To 89AT+CIPCLOSE
Got: CLOSED
Got:
Got: OK

inData.trim();
if( inData.length() > 0 ){
   Serial.println("Got: " + inData + "\n");

::trim() removes all leading and trailing whitespace characters including newlines. A line of [zero or more whitespace] + [newline] will get trimmed to the null string. If the result isn't null, then append the stripped off newline and print it. Note that this will flatten any indentation or vertical spacing that was supplied in the incoming text.


Basic C++ programming, how to pass constructor argument into class? I'm having some programming problems.

So here's what's happening:

In my .ino file, I have a tft variable which holds the connection to a LCD. I want to make a class which can either automatically access that tft class contained in the .ino, or pass it into the constructor when it's created; so basically:

// assuming this is the .ino:

TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

MenuClass *menu = MenuClass();
menu->init("Example", tft); // this should work and "menu" should now have access to the "tft" variable

Here's my Menu.cpp:

// Menu class

#include "Menu.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <TFT_ILI9163C.h>

String menName = "Unnamed";

void MenuClass::init(const String name)
{
    menName = name;
}

String MenuClass::getName() {
    return menName;
}

void MenuClass::draw() {
    tft.setCursor(2, 2);
    tft.print(menName);
}

MenuClass Menu;

Assuming you want to require every instance of MenuClass should be associated with a TFT_ILI9163C display object, you could use something like this:

// MenuClass.h

class TFT_ILI9163C; // declare a class name which is defined in TFT_ILI9163C.h

class MenuClass
{
  private:
    // read-only private member initialized by constructor
    // (the m_ prefix is commonly used to denote class member values)
    TFT_ILI9163C* m_tft;

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft) : m_tft(pTft) {};

  private:
    // private storage for the Name property
    String m_Name;
  public:
    // read the Name property
    String getName() {
      return m_Name;
    };
  public:
    // write the Name property
    void setName(String value) {
      m_Name = value;
    };

  public:
    void draw() {
      // the m_tft member is a reference to the display class
      m_tft->setCursor(2, 2);
      m_tft->print(m_Name);
    };
}
MenuClass Menu;

Note that there is only one constructor, and it requires a pointer to the TFT_ILI9163C display. The body of the constructor : m_tft(pTft) {}; initializes the private member m_tft with the constructor argument pTft, so  MenuClass member functions invoke TFT functions as m_tft->fn(args);  Since there is no "void constructor" MenuClass(void), m_tft is effectively guaranteed to point to a valid TFT_ILI9163C instance.

Since it looks like you were using menName kind of like a class property, I rewrote that in the more commonly used m_propertyname style. Your MenuClass::init() was behaving like a name property setter; I'm not sure whether menu initialization requires anything else. This simple example has class MenuClass defined entirely inside the header file.

Usage is pretty similar to your example code, except now the MenuClass constructor requires a pointer to a previously constructed TFT_ILI9163C display instance:

// Main application
#include <TFT_ILI9163C.h>
#include "MenuClass.h"
// ... etc ...

// the TFT_ILI9163C display instance
TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

// an example menu that draws on the display
MenuClass *menuFoo = new MenuClass(&tft); // use new to get pointer to new class instance
// MenuClass *menuFoo = MenuClass(&tft); // cannot convert 'MenuClass' to 'MenuClass*' in initialization

void setup() {
  // an example menu that draws on the display
  menuFoo->setName("Example");
  menuFoo->draw();
}

If you wanted to pass the constructor an initial Name property value as well as the tft display pointer, you could define the constructor as

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name) : m_tft(pTft), m_Name(name) {};

You could even go a step further, and give the name argument a default value:

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name = "Unnamed") : m_tft(pTft), m_Name(name) {};

So with this modification, the expression MenuClass(&myTFT) is the same as the expression MenuClass(&myTFT, "Unnamed"), but you can still override the default value like MenuClass(&myTFT, "DoSomething").

It is also perfectly legal to put statements inside the { } block of the constructor, but in this example all of the work is accomplished by the :memberName(value) constructor syntax.

Edit: MenuClass *menuFoo = new MenuClass(&tft); thanks @BrettAM


I want to send the last 10 minute data via bluetooth This was for photocell data logging for 30 sec intervals, now I want to write a code which commands from the cellphone and sends back the last 10 minute data.

At first I thought if I make an array of 20 buckets and put it in a loop, then send the loop function to android would make it right. But it just sends me continues data. I only want the last 10 minute data of the program.

float sensorvalue[20];

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);

    for (int i = 0; i < 20; i++) {
        pinMode(sensorvalue, OUTPUT);
    }
}

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

    if(Serial.available()) {
        c=Serial.read();
        if (c=='t')
            sendvalues();
    }
}

void sendvalues()
{
    for (int i=0 ; i<20 ; i++) {

        Serial.println(sensorvalue);
        sensorvalue   = analogRead(A0);
        delay(30000); //every 30 seconds read data

        if (i>=20) {
            i=0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
        }
    }
    Serial.println("***********************************");
}

What you want for this project is called a ring buffer. Before
reading the rest of this answer, I suggest you stop and take the time to
carefully read the Wikipedia page I am linking to.

Did you read it? Good! Now, yours is a somewhat special case in that you
don't need to continuously keep track of both a read pointer and a write
pointer: you only need the write pointer, as the read happens all in one
big batch.

Once your ring buffer is full, you will start overwriting the oldest
readings, those that are more than 10 minutes old. When the program
is instructed to dump the data, it will send out the whole buffer,
starting with the cell pointed to by the write pointer (the cell that
holds the oldest data point and was about to be overwritten).

There is one special case to take care of. What if the program gets the
command to dump the data while it has less than 20 readings stored?
You could decide that this is a user error, and it's OK for the program
to give garbage. I suggest, however, that the program should be able to
detect this situation, and then only send the valid data. For this, it
needs to store a boolean variable in order to remember whether the
buffer has been filled or not.

Here is an implementation I propose for such a ring buffer, together
with the functions for adding an item and for dumping all the data
through the serial port:

const uint32_t READING_PERIOD = 30000;  // one reading every 30 s
const int MAX_READINGS = 20;           // 20 readings = 10 min

int readings[MAX_READINGS];  // ring buffer
uint8_t reding_index = 0;    // next available slot
bool readings_full = false;  // did we fill the ring buffer?

static void register_reading(int value) {
    readings[reding_index] = value;
    if (++reding_index >= MAX_READINGS) {
        readings_full = true;
        reding_index = 0;
    }
}

static void dump_readings() {
    // If the buffer is full, then the next avaiable slot is the oldest
    // reading in the buffer.
    if (readings_full) {
        for (int i = reding_index; i < MAX_READINGS; i++)
            Serial.println(readings[i]);
    }
    for (int i = 0; i < reding_index; i++)
        Serial.println(readings[i]);
}

Now the main program is quite simple. You time the data taken using the
technique shown in the Blink without delay tutorial. You don't want
to use delay() because, when the program is delaying, it cannot
respond to your commands. There is one last question remaining: when it
dumps the data, should it forget it? In other words, if you ask it twice
to dump the data, with less that 10 minutes in between, should it
give repeated data the second time, or should it only provide the fresh
data? In the code below I assume the later option, and thus reset the
buffer, but in the end it is your choice:

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

void loop() {
    // Periodically take a reading.
    static uint32_t last_reading_time;
    if (millis() - last_reading_time >= READING_PERIOD) {
        last_reading_time += READING_PERIOD;
        register_reading(analogRead(A0));
    }

    // Dump the data on command.
    if (Serial.read() == 't') {
        dump_readings();
        reding_index = 0;       // reset the buffer
        readings_full = false;  // ditto
    }
}


How to get average of 16bit ADC readings? I have an Adafruit ADS1115 analog-to-digital converter, configured in single ended mode. I want to average over 3 sensor readings to increase the reading stability.

  //initialize variables
  int16_t rawData, ambient;
  int i=0;

  // start loop
  while(i<3) {
      rawData = ads.readADC_SingleEnded(0); //read from ADC
      // divide sensor reading by three
      // (doing so after summation will lead to an overflow)
      rawData=rawData/3;
      Serial.println(rawData); // print data to serial for debugging (OK)
      ambient+=rawData;
      i+=1;
      delay(100);
      Serial.println("I LIVVVVEEE"); // print text to serial for debugging (OK)
  }

  // Print signal (NOT OK)
  Serial.print("Ambient is ");
  Serial.println(ambient);

The "rawData" is printed correctly on the serial monitor. However, the value for "ambient" can be crazy: the resulting output is over an order of magnitude higher. Somehow, the summation doesn't seem to be performed correctly.

You forgot to initialize ambient to zero, so it got whatever happened to be in that place of memory when it got instantiated. Some unpredictable, seemingly random data.


ESP8266 Returns 'invalid' - Cause 4 I have tried to get the Ai-Thinker ESP8266 working at all. If you hook it up to an Uno you have garbage returned no matter what the baud rate is. Tried softwareSerial on D3 and D4 (switching pins doesn't help) and over D0 and D1 with no sketch (to send AT commands directly to the device because softwareSerial wasn't working).

I'm using a logic converter from 5v to 3.3v to handle the voltage correctly.

I also know for a fact you can do that. I've done it a bunch with Bluetooth. HC-05.

NOTE: Pins in the wrong order won't return anything, in order to get garbage it needs to be wired correctly.

I also have a FTDI module that functions as another passthrough unit for this. It has a jumper for 3.3v to 5v and will stay on 3.3v as these units are unable to handle 5v.

I used PuTTY in order to view the boot information of this chip. On boot it returns this information.

So here's my issue.

ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x40100000, len 816, room 16
tail 0
chksum 0x8d
load 0x3ffe8000, len 788, room 8
tail 12
chksum 0xcf
ho 0 tail 12 room 4
load 0x3ffe8314, len 288, room 12
tail 4
chksum 0xcf
csum 0xcf

2nd boot version : 1.2
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd▒C▒
Ai-Thinker Technology Co. Ltd.

invalid

At the end of the day this invalid line means that the wifi information (from what I understand) is corrupted. It also refreshes this information over and over and WILL NOT accept AT commands so I can't seem to chase it down.

I am afraid that by attempting to update it if this kind of issue happens it will be bricked.

Both of these modules are opened today and I have tested another 8266 with similar results.

Any help would be appreciated.

Alright so I figured it out. Thanks to user Butters for pointing me in the right direction.

The Arduino Uno DOES NOT have enough power to handle the ESP8266 itself. It needs a power source using a 5v to 3v stepdown chip. The 3v3 rail doesn't handle it by itself.


How do I print the reading serial data sending from Arduino I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert  the data to read.

You can see the receive data has some no printer character.

Workflow of sending and receiving data between QtSerialPort and Arduino

Sending Data with QtSerialPort

void MainWindow::sendData(){

    QString m_allData = m_sendEdit->toPlainText();
    int i = 0;
    int size = m_allData.size();

    QString line = "";
    int c = 0;
    while(i < size){
        line.append(m_allData[i]);
        if(c == 24){
            int sended = m_serialPort->write(line.toUtf8(), 24);
            m_serialPort->flush();
            line.clear();
            c = 0;
        }
        i++;
        c++;
    }
    if(c > 0){
        m_serialPort->write(line.toUtf8(), c);
    }
    m_serialPort->flush();
}

I want to send the data with a buffer size of 24 bytes.

Reading and Sending Data with Arduino

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

 void loop() {

    delay(1000);

    if (Serial.available() > 0){
        short i = 0;
        int size = Serial.available();
        String data = Serial.readString();
        Serial.print(data);
    }
 }

The Arduino code is simple.

Receiving Data with QtSerialPort

void MainWindow::readData(){
    int c = 0;
    char * dataBuffer;
    int size = m_serialPort->bytesAvailable();
    dataBuffer = new char[size];
    c = m_serialPort->read(dataBuffer, size);
    m_receiveEdit->setText(m_receiveEdit->toPlainText() + QString::fromUtf8(dataBuffer));
        delete dataBuffer;
}

I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?

You have no warranty that Qt will receive the whole message in a single
chunk. It may receive "no se" as the first chunk, and then "q pasa" as
the second chunk. Since dataBuffer is dynamically allocated, it
initially contains garbage, and you are printing the part of this
garbage that you did not overwrite.

An easy fix would be to simply NULL-terminate the buffer:

dataBuffer = new char[size + 1];            // + 1 byte for '\0'
c = m_serialPort->read(dataBuffer, size);
dataBuffer[c] = '\0';                       // terminate the string


Deploying an Arduino Uno R3 standalone I have an Uno R3 with a sensor board and a temperature sensor. I'm running a simple temperature check and would like to store that data outside the Ardunio for keeping records, graphs, etc.

I powered it from my PC during development, but obviously I want something more compact when deployed. It's still inside the house, but I want the PC shut down, not running 24/7.

I do have wireless access, and a Raspbery Pi 3 model B. Can any of those help? Or should I buy an ethernet/WiFi shield and try to get acces with those?

So you would rather use your Raspberry Pi than your PC? Easy, as it
turns out that a Raspberry Pi is not that different from a PC running
Debian or a Debian-like OS (e.g. Ubuntu).

Just connect the Uno to the Raspberry Pi through the USB link. Log the
data on your Raspberry exactly like you would do on the PC. You don't
need any Ethernet or WiFi shield. You just need to make sure that
whatever logging program you use on the PC can run on the Raspberry Pi.
This is most often trivial if the PC is itself running a Linux distro.


Trying to understand Arduino products Background:

I am new to Arduino world, and I like to buy a board. I am a bit confused how Arduino products are being sold. Coming from Raspberry world, it seems that I don't know what actually Arduino is.

Question:

I am trying to understand what is it that this product offers:

.

Why it says "For Arduino UNO R3"? 2. Isn't it actually an "Arduino UNO R3"? So why it says "For"?
What are MEGA328P and CH340? Does "Arduino UNO R3" comes with other chipsets?

It sounds to me like an Arduino Uno clone.

  Why it says "For Arduino UNO R3"?

I would read that as "For Arduino UNO R3 projects" (ie. Uno-compatible).

  Isn't it actually an "Arduino UNO R3

No, it's a clone. Or not really a clone (see below) because they used different hardware. It is compatible with the Uno in most respects.

  What are MEGA328P?

That is the main chip on the board (actually an Atmega328P).

  and CH340?

They have saved money by using a CH340 USB-to-serial chip instead of the Atmega16U2 used on genuine Uno boards. You may need to install a different driver to make that work. I disagree with the other answer(s) that this is a separate board or chip. It is clear from the photo of the chip near the USB socket that it is a CH340 chip there. See, for example https://hackaday.com/tag/ch340/ from which I quote:

  The cheapest USB to serial chip on the market appears to be the CH340G, available for 20-40 cents apiece from the usual retailers. There is, however, almost no English documentation, and the datasheet for the CH340 family doesn’t include this chip

They used it because it is cheap.

  Does "Arduino UNO R3" comes with other chipsets?

Yes the genuine one comes with an Atmega328P (main processor) and Atmega16U2 (USB interface).

Having said all that, the Uno is a good all-rounder starting board to get going with Arduinos.

Note that they are using the SMD (surface mounted) main processor chip. If you fry it you need to replace the whole board, not just the chip. However the entire board is quite cheap. :)


analogWrite mosfet problem i have a custom atmega328p board which have connected to pin 9 the gate of a MOSFET.
If i run a simple sketch like:

void setup() {

}
void loop() {
  analogWrite(9,70);
}

The motor connected to the mosfet works just fine, from 70pwm to 255pwm.

On the other sketch i'm receiving serial data from an android app via bluetooth. Ive 2 Servo motors and a DC motor connected to the mosfet.
The 2 servos works like expected, the DC motor doesn't spin unless i use a 255pwm.

void loop() {
  if(Serial.available() > 0){
      state = Serial.read();
  }
  if (state == 'S') {
      servoONE.write(90);
      servoTWO.write(90);
      analogWrite(MOSFET,MOSFET_LOW);
  }
  else if (state == 'F') {
      analogWrite(9,70);
      servoONE.write(90);
      servoTWO.write(90);
  }
  else if (state == 'L') {
      servoONE.write(MAX_SERVO);
      servoTWO.write(MIN_SERVO);
  }
  else if (state == 'R') {
      servoONE.write(MIN_SERVO);
      servoTWO.write(MAX_SERVO);
  }
  else if (state == 'Q') {
      analogWrite(MOSFET,MOSFET_HIGH);
      servoONE.write(MAX_SERVO);
      servoTWO.write(MIN_SERVO);
  }
  else if (state == 'E') {
      analogWrite(MOSFET,MOSFET_HIGH);
      servoONE.write(MIN_SERVO);
      servoTWO.write(MAX_SERVO);
  }
}

Do you know why the same motor works on the first sketch with any pwm above 70 and on the second sketch it only works at 255?

You have a timer conflict.

Pin 9 is OC1A which is the Output Compare Channel A pin of Timer 1. However the Servo.h library also uses timer 1.

So you can't use servos and still use pins 9 (OC1A) and 10 (OC1B) as PWM.

However, you can still use pins 3, 5, 6 and 11 as PWM since they are on other timers.


Stack isn't popping off correct data? So, I was working on a project where I needed to get a random object from a stack, so to make sure my design was correct, I made a dummy program that does nothing but fill a stack with data, then print it out.

why in the world is nothing coming out of the stack but -1s??

Here's the stack.h file.

http://pastebin.com/vjhNLpNu

You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.

class Stack
{
private:
    int *p;
    int top,length;

public:
    Stack(int = 0);  <<== CONSTRUCTOR - DEFAULT SIZE IS 0
    ~Stack();

    void push(int);
    int pop();
    void display();
};

When you make your Stack object you must give it a size for the number of entries in the stack:

Stack stack(4);


Issues on Arduino, LiPO battery and two mottors setup My main objective with this project was to control these two DC motors with an Arduino Nano (it is not a UNO), powered by a 3-Cell 750mAh LiPO battery (both the motors as the Arduino itself). So, I came up with something like this (it is a simplified version):

If the load on the two mottors rise, could the Arduino be damaged by this current increase? Is the voltage too high for the Arduino handle? Is there any more issues that this setup can have?

When searching, I found that it would be wise to get a fuse between the power supply and the arduino (before reaching Vin). Is that necessary?

If the load on the two motors rise, could the Arduino be damaged by this current increase?

No, the motor current doesn't pass through the Arduino. It is completely separate.

  Is the voltage too high for the Arduino handle?

Borderline. The regulator (a lowly 7805) may well get very hot at that voltage (depending on the Arduino's current draw) and go into thermal shutdown.

  Is there any more issues that this setup can have?

Maybe add a small buck regulator to the 5V pin instead of using the on-board linear regulator. That will not overheat and will be far more efficient making your batteries last longer. Often marketed as "UBEC" (Universal Battery Elimination Circuit) and used throughout the model vehicle industry these are very easy to get hold of and are ideal for powering things like Arduinos from batteries like this.


Scope of RtcDateTime object when declared outside of a function I'm trying to merge 2 Arduino samples, in order to be able to use DS3231 RTC module with ESP8266 WiFi simple web server.

My RTC library is this:
https://github.com/Makuna/Rtc/wiki

Generally, to code runs ok (I have the Web server responses to my browser calls, and I think the DS3231 RTC code also works). But when I'm trying to use a variable from within the RTC object into the Web server function - I get nothing.

I thought declaring the 'now' object outside any function (Setup() nor Loop()) will make it global, and when I'll update it in the Loop() function using

now = Rtc.GetDateTime();

It will be available to other functions as well, but all I get is "0" when I try to print it.

My code is here:
Definitions part:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

/* This block is for I2C protocol for DS3231 module (for normal hardware wire use below) */
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>
RtcDS3231<TwoWire> Rtc(Wire);
/* The above block is for I2C protocol and DS3231 module  (for normal hardware wire use above) */

ESP8266WebServer server(80);
RtcDateTime now;

My Loop():

void loop(void) {
  now = Rtc.GetDateTime();
  Serial.println(now.Minute());
  server.handleClient();
  delay(500);

}

And all I get is "0" printed.

Any help would be appreciated!

As was suggested by more 'native' friends here - I'm 'Answering my question' to make things clear.

After a check and debug - I've found a mysterious behavior that happened to my DS3231 module. Probably a mistaken initializing set of calls - made it stop working - not getting time updates and not counting the time at all. (Freeze at 1/1/2000, 00:00:00).

Disconnecting it from power source, and taking out the battery - returned it to normal behavior, able to get time updates, and answering the calls from the library.

When that part solved - everything else went as easy as it should.

The code sample I posted in my question (declaring the 'now' object outside of setup() and loop() functions) made that object global, so another function (WebServer) can read its current value and use it internally.

Thanks everyone who looked at my problem and helped,
It was a great lesson about how not to take anything as 'known' without double-checking.


How do I correctly use enum within a class? I am trying to set the status of an object from a private enum and I'm not sure how to get the private member to the public version in the constructor, and I'm pretty sure I should not be using byte in the constructor when it's an enum.

Also, I'm not sure if I should even have the values of the enum inside the header at all. Here is my code:

.h

class CandleRack
{
  public:

    CandleRack(byte candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    byte _pushButtonPin;
    enum _candleRackStatus
    {
      inactive = 0,
      candlesOn = 1,
      rewardAnimation = 2,
      tweetArrived = 3,
      partyMode = 4,
    };
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

.cpp

CandleRack::CandleRack(byte candleRackStatus)
{
  _candleRackStatus = candleRackStatus;
  _debouncePushButton = NULL;
}

in the sketch

CandleRack MyCandleRack(0);

error:

error: expected unqualified-id before '=' token
_candleRackStatus = candleRackStatus;

Thanks!

I see two separate issues here.

First of all your enum isn't available as a variable.
By declaring it as a private type within your class the enum can't be used outside of that class.

This forces a user of that class to handle unintended calls like (attention, bug):

CandleRack(255);

which can make code harder to read (and debugging more difficult, since it wouldn't be detected by the compiler).

Second of all you try to directly assign a byte value to an enum type. This will be rejected by the compiler and/or cause runtime errors later (depending on compiler settings).

I recommend that you declare the enum type so that it is accessible directly via the header file:

.h

enum CandleRackStatus {
    inactive = 0,
    candlesOn = 1,
    rewardAnimation = 2,
    tweetArrived = 3,
    partyMode = 4,
};

class CandleRack
{
  public:

    CandleRack(CandleRackStatus candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    CandleRackStatus _candleRackStatus;
    byte _pushButtonPin;
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

Now you can instantiate your class while using the correct enum type as the parameter.

.ino

CandleRack MyCandleRack(CandleRackStatus::inactive);

Within your implementation you can now directly store the constructor parameter in the private variable, the compiler will make sure it's always of the correct enum type:

.cpp

CandleRack::CandleRack(CandleRackStatus candleRackStatus) {
    _candleRackStatus = candleRackStatus;
    // rest of your initialisiation goes here
}

As an added bonus, there's the possibility to use a couple of C++ language features that will make your implementation easier:

a default parameter value
an initializer (list)

.h

class
{
  public:
    CandleRack(CandleRackStatus candleRackStatus = CandleRackStatus::inactive);
    // [...]
}

.cpp

CandleRack::CandleRack(CandleRackStatus candleRackStatus) : _candleRackStatus(candleRackStatus) {
    // rest of your initializiation goes here
}


Sensor TSL2591 with Arduino Mega I have three light sensors  TSL2591, of signal I2C, that I need to connect (together) to an Arduino Mega. However, I'm not very sure of how share the SDA and SCL pins of the three sensors and I don't know how to change their address for the Arduino to read and show the data of each sensor.

I have already read sensor's datasheet but there is not much information about this.

Looking at the datasheet, the TSL2591 does not appear to have a comfigurable address mechanism, therefore you are most likely obliged to use an I2C Multiplexer.

One example of such a device is the TCA9545A, Low Voltage 4-channel I2C and SMbus Switch With Interrupt Logic and Reset Functions, that can split one I2C line into 4 buses.

They are very easy to use and the pinout (and datasheet) are self explanatory.

Don't forget that you will need 3k3 Ω resistors on the INT, RESET, SDA and SCL lines from the Arduino and on each of the INTx, SDx, and SCx lines from the TCA9545A:


Correct Capacitors to use with L7805 Voltage Regulator I am making my own arduino.  I am in the process of hooking up power to the Atmega328.

In both these articles they use the L7805 voltage regulator with two 10uF capacitors.

https://www.arduino.cc/en/Main/Standalone

http://www.instructables.com/id/How-to-Build-an-Arduino-Uno-on-a-BreadBoard/?ALLSTEPS

I am looking at the datasheet for the regulator at http://pdf.datasheetcatalog.com/datasheet_pdf/sgs-thomson-microelectronics/L7805CD2T_to_L7885CV.pdf

The data sheet provides a number of figures for how to correctly hook up the L7805 in different situations (pages 4, 16-23).  I think Figure 13 represents our situation (Fixed Output Regulator).  In the figure they use 0.33uF and 0.1uF
capacitors.  Could someone explain why the examples use 10uF and the data sheet specifies 0.33uF and 0.1uF?

The answers are in the notes:

  Although no output capacitor is need for stability, it does improve transient response.
  Required if regulator is locate an appreciable distance from power supply filter.

So  the values aren't critical to the operation, but you should have them there. Bigger capacitors give more energy to the regulator and more energy to your circuit (input and output capacitors respectively) but at the cost of lower frequency response. The actual values you select depend on your circuit, not the regulator. 10µF is a good "ballpark" figure to use in most circumstances.

The input capacitor reduces the impedance of the power source by providing a local source of power. The output capacitor is like the "reservoir" capacitor you should have at the power entry to all boards anyway, and reduces the impedance to the rest of your circuit.

For the higher frequency responses you should have smaller value decoupling capacitors by all your active components anyway.

You can also add more smaller capacitors to the output of the regulator to improve high frequency responsiveness if needed - you're not just limited to the one capacitor.


Is this a USBasp I can use with Arduino? I bought the following USBasp off of Aliexpress.

The Arduino UDE doesn't recognize it. When I try to run avrdude with it, it says:

avrdude -cusbasp -Pusb -patmega328p
avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

Looking at the USB enumeration, it says:

USBHID:

  Product ID:   0xc8b4
  Vendor ID:    0x03eb  (Atmel Corporation)
  Version:  1.00
  Speed:    Up to 1.5 Mb/sec
  Manufacturer: zhifengsoft
  Location ID:  0x14200000 / 8
  Current Available (mA):   1000
  Current Required (mA):    100
  Extra Operating Current (mA): 0

Looking online, I see one blog post (http://www.sciencetronics.com/greenphotons/?p=938) about a device with the same VID/PID, and it says it can be reprogrammed but is not clear how to do it.

In particular, I know there is a jumper that I need to set to put it in self-programming mode but I can't figure out where to put this jumper. Once the jumper is in, I understand I just match the SPI pins and program it using the firmware.

Can someone help?

That's not a USBasp, that's some other programmer that has co-opted Atmel's vendor ID invalidly. If you want to use it then you will need to find and use some program called "ProgISP" that is only available for Windows.

That particular device does not show the jumper required for reprogramming, so I wouldn't attempt it (and in fact I would find the nearest bin to toss it in and get a couple from Baite and/or LC Tech instead).


If (serial.available()) conditional statement I am very new to Arduino and I have a question I would like to clarify on Serial.Available()

According to Arduino documentation, Available() returns the number of bytes that are stored in the buffer, ready to be read. Why then, both If function below works, when there are data in the buffer? For Scenario A, it appears to me that there is no conditional statement, how then, would the IF function evaluates to TRUE?

Scenario A: IF(Serial.Available())

compare with

Scenario B: IF(Serial.Available()>0)

Thanks in advance!

In C, 0 is false and anything else is true. So if Serial.available() returns 0 it is considered false. If it returns 7, 23, 44, etc it is considered true.


Getting error while uploading a sketch through Ardunio IDE I recently used the Ardunio board and powered with the AVR pocket programmer along with the AVR ISP cable and it worked just fine and no issues were experienced. However now that i switch back to the default method of powering Ardunio board with USB, getting this error while trying to upload the sketch.

There are forums available on Arduino platform but no definitive resolution.

The board is recognized by the IDE.

Reinstall the bootloader using your ISP programmer.

Installing a sketch using ISP first wipes the chip clean, and that includes the bootloader. Without the bootloader the USB interface won't be able to communicate with the main MCU.


Problem with a function having a parameter with a default value I've got a problem using a default value for a function parameter.
This code gives "'blink' was not declared in this scope":
void loop(void) {
  blink(12, 2, 1000);
}

void blink(const uint8_t led, int num, const uint16_t l = 12) {
  Serial.println(led);
  Serial.println(num);
  Serial.println(l);
}

but it works if I don't assign a default value to the "l" arg:
void blink(const uint8_t led, int num, const uint16_t l) {

or if I put the blink function before the loop:
void blink(const uint8_t led, int num, const uint16_t l = 12) {
  Serial.println(led);
  Serial.println(num);
  Serial.println(l);
}

void loop(void) {
  blink(12, 2, 1000);
}

It's just a failing of the Arduino build process to generate prototypes (function declarations) for functions that have default argument values.  There's otherwise nothing wrong with what you're doing.  Not in my opinion anyway.  The build process sometimes chokes on function or class templates as well.  The answer to these sorts of problems is probably that these features are not considered part of the Arduino "language".
Just a reminder: In C++ a function declaration needs to have been seen in order to generate a call to it.  A definition will serve as a declaration.  In either case, one must have been seen before the call site.  Generating declarations where needed is, perhaps, the greater part of what the Arduino build process does that can be said to make the Arduino "language" different from plain C++.
The following were generated by working out of /tmp/default-param with the "input" being default-param.ino, running:
arduino-cli -b arduino:avr:uno build --build-path /tmp/build

and inspecting /tmp/build/sketch/default-param.ino.cpp which I'm calling "output".  You can use the same process if you want to see exactly what the build process is doing to your code.
Non-default argument
This input:
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

generates:
#include <Arduino.h>
#line 1 "/tmp/default-param/default-param.ino"
#line 1 "/tmp/default-param/default-param.ino"
void setup();
#line 4 "/tmp/default-param/default-param.ino"
void loop();
#line 5 "/tmp/default-param/default-param.ino"
void func(int xyzzy);
#line 1 "/tmp/default-param/default-param.ino"
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

The build process has inserted a valid C++ function declaration prior to the call site, so the compiler is happy.
With default argument
But this input:
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy = 7) {}

generates:
#include <Arduino.h>
#line 1 "/tmp/default-param/default-param.ino"
#line 1 "/tmp/default-param/default-param.ino"
void setup();
#line 4 "/tmp/default-param/default-param.ino"
void loop();
#line 1 "/tmp/default-param/default-param.ino"
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy = 7) {}

No declaration prior to the call site this time, so the compiler is not happy with this generated code.
Build process
The build process is a rather ugly... process... that scrapes the output of the compiler and generated ctags to build include paths and to try to generate forward references for things.  Sometimes, it just gets it wrong.  I'm not sure what the exact error is in the build process, but it is probably just a failure to match the error caused by calling an undeclared function with its matching entry in the ctags.  You can try reading through the build process documentation to make sense of this.  Ultimately though, you may have to read the source to arduino-cli/arduino-builder to get to exact cause.
Non-.ino (and non-.pde) files more or less go through the build process unscathed.  So, if you really want default arguments, you can make use of and .h file for your function prototype/declaration and a .cpp file for its body and follow the normal rules of C++.
Using your own declaration
You can just make your own declaration for it.  Doing so makes it not detect an error on that line.
void func(int xyzzy = 7);

void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

Output:
#include <Arduino.h>
#line 1 "/tmp/default-param/default-param.ino"
void func(int xyzzy = 7);

#line 3 "/tmp/default-param/default-param.ino"
void setup();
#line 6 "/tmp/default-param/default-param.ino"
void loop();
#line 7 "/tmp/default-param/default-param.ino"
void func(int xyzzy);
#line 3 "/tmp/default-param/default-param.ino"
void setup() {
    func(11);
}
void loop() {}
void func(int xyzzy) {}

As you can see it generates a proto type for whatever reason.  But not one that conflicts with your own.

It is probably better if you want to make use of default arguments to just use headers and .cpp file for those functions that have them so that you're not subject to changes in the ability of arudino-cli/arduino-builder to handle them.


How to compile and upload the specific (.cpp + .h) code? I have a specific arduino code (no .ino files) https://github.com/justintconroy/MdbBillValidator , which can't be opened by arduino IDE. How can I make & upload this code? I have an arduino 2560 mega.

I've created an empty MdbBillValidator.ino file and added these lines:

#include "MdbBillValidator.h"

void setup() {

}

void loop() {

}

Here is the error message

MdbSerial.cpp: In function ‘void __vector_37()’:
MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_52()’:
MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_55()’:
MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: At global scope:
MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
MdbSerial.cpp:554:189: note: candidates are:
MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
MdbSerial.cpp:352:1: note:   candidate expects 20 arguments, 19 provided
In file included from MdbSerial.cpp:38:0:
MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
MdbSerial.h:52:7: note:   candidate expects 1 argument, 19 provided

The problem is that I need to import this code just a simple usual library.


Change arduino.local server address I have a Yun and I'm trying to change the URL I type in to access the Web UI.

I've successfully changed its hostname in /etc/config/system, which now lets me SSH in using the new name. However:

Going to newname.local doesn't work (no response at all).
Going to arduino.local pulls up the green page 'Wait a moment or click here...', after which no page is rendered.

How can I access my Yun by typing in newname.local in my browser?

That should be working fine.

I just logged into my Yún and changed its name by editing that file.  I then restarted avahi-daemon since that is what broadcasts its name (faster to restart the daemon that reboot the whole Yún).

Browsing to the new name worked fine.

matt@dell:~$ ssh root@arduino.local
root@Arduino:~# vi /etc/config/system
(edit the config file)
root@Arduino:~# hostname skybridge
(manually changing the hostname so I don't have to reboot)
root@skybridge:~# /etc/init.d/avahi-daemon restart
(restart the avahi daemon)

Browsing to skybridge.local now shows me the Arduino login as it should.

As a further test I have just rebooted my Yún so it runs everything from scratch and it still works fine.

There are a number of caches involved in the system, any of which may be getting in the way.  It could be that the browser has cached incorrect or out of date information about the FQDN (fully qualified domain name) for the name you have given your Yún, in which case just closing and re-opening your browser may help.  It may be that the mDNS lookup system on your computer (you haven't mentioned which operating system you are using, which is a big factor) has cached old or out-dated information for the FQDN, in which case flushing that cache may help (how you do that depends on your OS), or just rebooting your computer.

Incidentally, if you are on Linux (Windows lacks these basic networking facilities along with many other basic tools), you can query the network for your Arduino Yún with the avahi-browse and avahi-resolve commands.  OS X has similar tools, but I don't know off hand what the commands are:

matt@dell:~$ avahi-browse _arduino._tcp
+  wlan0 IPv4 skybridge                                     _arduino._tcp        local
^CGot SIGINT, quitting.
matt@dell:~$ avahi-resolve -n skybridge.local
skybridge.local 192.168.0.252


32u4 using internal clock on custom PCB - loading sketch I have a custom PCB with a 32u4 running fine with an 8MHz external oscillator.  I burned the bootloader and loaded my sketch with an UNO using Arduino as ISP.

I have no USB on my PCB nor do I need precise timing, so I wanted to see if I could simplify things by removing the external oscillator and caps.

Reading the 32u4 datasheet it states "The device is shipped with Low Power Crystal Oscillator (8.0 - 16MHz) enabled and with the fuse CKDIV8 programmed".

With that, can I simply hook my PCB (assuming a factory fresh 32u4) via ISP to the UNO as before and in IDE just use Sketch > Upload Using Programmer?    Basically not burning any bootloader at all.

Also, in IDE I have been choosing the Sparkfun ProMicro 3.3v, 8MHz board.  Can I still use that selection?

Yes you can reprogram your 32U4 chips via the ISP, they do not have to be fresh chip. If you set your Fuses to -U lfuse:w:0xE2:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m using AVRDUDE you will have an 8mhz internal RC oscillator set and you do not have to have the external crystal.

You can play with these settings at http://www.engbedded.com/fusecalc/.

I recommend learning the command line AVRDUDE commands this way you have more control over what you are doing to your chip.

I use this all the time, and if you need to do more than one quickly I typically make a batch file that does the Fuse Burn and hex at the same time.

this is for a attiny167 but you get the idea:
.\avrdude\avrdude -C".\avrdude\avrdude.conf" -v -pattiny167 -cstk500v2 -PCOM3 -Ulfuse:w:0xE2:m -Uhfuse:w:0xDF:m -Uefuse:w:0xFF:m  -Uflash:w:1060X01-001.hex:i


How to map 6 bytes of raw data to long long type? I'm trying to solve some problems for a contest, and I have a problem with it. I have to implement a function that has 3 arguments like this:

void foo(unsigned char* A, unsigned char* B, unsigned char* C);

And what comes in, is 6 bytes of data. I have to convert these 6 bytes of data to integer data (maybe long long). The problem is, I don't know how to map the bytes in the right order.

I'm using an Arduino Uno board.

Please help me with it.

The trick is to use a union data type and get full control of the mapping. The issue of data representation and endian is now under your control:

uint64_t foo(uint8_t* A, uint8_t* B, uint8_t* C)
{
  union {
    uint64_t X;
    struct {
      uint8_t A[2];
      uint8_t B[2];
      uint8_t C[2];
      uint8_t D[2];
    };
  } map;
#if defined(MSB_ORDER)
  for (int i = 0, j = 1; i < 2; i++, j--) {
    map.A[i] = 0;
    map.B[i] = C[j];
    map.C[i] = B[j];
    map.D[i] = A[j];
  }
#else
  for (int i = 0; i < 2; i++) {
    map.A[i] = A[i];
    map.B[i] = B[i];
    map.C[i] = C[i];
    map.D[i] = 0;
  }
#endif
  return map.X;
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  uint8_t a[] = { 0x12, 0x34 };
  uint8_t b[] = { 0x56, 0x78 };
  uint8_t c[] = { 0x9a, 0xbc };
  uint64_t res = foo(a, b, c);
  Serial.print((uint32_t) (res >> 32), HEX);
  Serial.print((uint32_t) res, HEX);
}

void loop()
{
}

Cheers!


Replacement for #include  on particle photon I've run into this a couple of times when trying to use libraries written for Arduino on a particle photon. Many have the line:

 #include <pins_arduino.h>

which returns the error on the photon compiler:

 fatal error: pins_arduino.h: No such file or directory

I had similar trouble with:

 #include <WProgram.h>

and found an easy fix was to replace that with

 #include "application.h"

I'm wondering if there's a similar easy fix for pins_arduino?

There are some Arduino libraries, that just implements functionalities that do not depend on hardware. Example of these are almost all those libraries that deal with data structures/types (strings, arrays, trees, lists, etc), or particular algorithms.
If such libraries do not depend on other Arduino-specific libraries, you can use them almost certainly.

Other libraries, instead, heavily depend on the hardware currently used on the Arduino boards. In those cases, the library must access the hardware, therefore they will include verious headers, such as pins_arduino.h (in particular, pin_arduino.h .

These won't work without heavy modification of such libraries and/or the creation of a wrapper header to "emulate" the required functionalities and define the required macros/constants, according to your hardware.


Arduino Hardlid Unlocker I am trying to build a unlocker on my hardlid for my ute. I have replaced the manual unlocking mechanism with 2 of these https://www.jaycar.com.au/slave-door-lock-actuator/p/LR8813.

Now my code below works sometimes and I cannot work out why. The way the code should work is

Press Unlock Button (Count increments)
Press Unlock Button again
When count = 2 turn relay on for 4 seconds then turn off
reset count to 0
If time between presses is longer than 10 seconds reset count to 0

Basic diagram below. Please note the push button is actually wired to a relay which is triggered by the car unlock remote and the LED is the actuators.

This is my code

int switchPin = 2; // choose the input pin (for a pushbutton)
int relayPin = 4; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;
bool lockOn = false;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

unsigned long LockcurrentMillis = 0;
unsigned long LockpreviousMillis = 0;

const long interval = 10000;
const long Lockinterval = 4000;

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

  pinMode(switchPin, INPUT); // declare pushbutton as input
  pinMode(relayPin, OUTPUT); // declare pushbutton as input

  Serial.println("Ready");
  Serial.print("IP address: ");

}

void loop() {

  currentMillis = millis();
  LockcurrentMillis = millis();
/*
  Serial.print("Current ");
  Serial.print(currentMillis);
  Serial.print(" | Previous ");
  Serial.println(previousMillis);
    //Serial.println(lockOn);

  Serial.print("Lock Current ");
  Serial.print(LockcurrentMillis);
  Serial.print(" | Lock Previous ");
  Serial.println(LockpreviousMillis);
  */
  if (lockOn == true){

    if (LockcurrentMillis - LockpreviousMillis >= Lockinterval) {
      // save the last time you blinked the LED
      LockpreviousMillis = LockcurrentMillis;
      digitalWrite(relayPin, LOW); // turn relayPin off
      lockOn = false;
      Serial.println("relay off");
    }
  }

  val = digitalRead(switchPin); // read input value
  if (val == HIGH) { // check if the input is HIGH (button released)
    currentState = 1;
  }
  else {
    currentState = 0;
  }
  if (currentState != previousState) {
    if (currentState == 1) {
      counter = counter + 1;
      previousMillis = currentMillis;   //reset timer
      Serial.println(counter);
    }
  }
  if (counter == 2) {
    counter = 0;
    digitalWrite(relayPin, HIGH); // turn relayPin on
    //delay(4000);
    //digitalWrite(relayPin, LOW); // turn relayPin off
    lockOn = true;
          LockpreviousMillis = LockcurrentMillis;

    Serial.println("relay on");
  }

  previousState = currentState;
  //delay(250);
  if (currentMillis - previousMillis >= interval) {
    // save the last time you presse the button
    previousMillis = currentMillis;
    //LockpreviousMillis = LockcurrentMillis;
    //if (counter >= 1) {
    Serial.println("Took too long reset count");
    counter = 0;
    lockOn = false;
    //}
  }
}

Any Help would be highly appreciated

Thanks

Your circuit drawing seems very wrong, but it is not helpful since, as
you say, it doesn't represent the real circuit. Please, add a proper
diagram of the actual circuit.

As for your reliability problem, I did not dig into the logic of the
code you posted, but I suspect it may be caused by the lack of
debouncing. You could add you own debouncing code but, for the sake
of simplicity, I suggest you instead use a ready-made library, like
Bounce2.

For the kind of program you are trying to write, I find that the logic
becomes way easier to grasp if you think think of it as a finite state
machine. This is program construct based on the idea that the
system can be in any of a predefined set of possible states, and that
its behavior and the possible state transitions depend on what
particular state it is in. In this specific case, I would use three
states:

In the LOCKED state, the lid is locked and you need to press the
button twice in order to unlock it. Once you press the button once,
it transitions to the WAITING state.
In the WAITING state, the lid is still locked, but the first
button press has already been registered. If you press the button
again, the system transitions to the UNLOCKED state. If not,
after a timeout it transitions back to LOCKED.
In the UNLOCKED state the lid is unlocked. After another timeout it
transitions back to the LOCKED state.

Once you have this logic written down, it can be translated into code in
a very straightforward way:

#include <Bounce2.h>

const uint8_t  switch_pin = 2;
const uint8_t  relay_pin  = 4;
const uint32_t wait_interval = 10000;  // 10 s
const uint32_t lock_interval =  4000;  //  4 s

Bounce button;

void setup() {
    button.attach(switch_pin, INPUT_PULLUP);
    pinMode(relay_pin, OUTPUT);
    Serial.begin(9600);
    Serial.println("Ready.");
}

void loop() {
    static enum { LOCKED, WAITING, UNLOCKED } state = LOCKED;
    static uint32_t last_change;  // not used in the LOCKED state

    button.update();
    uint32_t now = millis();
    switch (state) {
    case LOCKED:
        if (button.fell()) {
            Serial.println(F("Waiting for second button press."));
            state = WAITING;
            last_change = now;
        }
        break;
    case WAITING:
        if (button.fell()) {
            Serial.println(F("Unlocking."));
            digitalWrite(relay_pin, HIGH);
            state = UNLOCKED;
            last_change = now;
        } else if (now - last_change >= wait_interval) {
            Serial.println(F("Wait time out."));
            state = LOCKED;
        }
        break;
    case UNLOCKED:
        if (now - last_change >= lock_interval) {
            Serial.println(F("Locking."));
            digitalWrite(relay_pin, LOW);
            state = LOCKED;
        }
        break;
    }
}


Error compiling for board Arduino Nano I have multiple Arduino Nano boards.
I am able to compile or upload code only once. If I try to compile/upload again I get an error: "Error compiling for board Arduino Nano". However there is a workaround: to be able to upload again I change something in tools menu for example board or processor.
I tried all of the nanos and all of the ports.

The error message is below (verbose is enabled).

The problem appeared from nowhere.
Thank you in advance!

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
Error compiling for board Arduino Nano.

I resolved this issue by installing older arduino ide version.


Need to cycle through LED brightness So this is pretty much explanatory.  I am new to arduino, and i am learning the best i can.  I need to sketch a code in which will cycle through 5 different brightness settings of an led.  One push will cycle through the five, another push of the button will turn the led off, and another push will restart the cycle.

const int led =11;
const int BUTTON = 7;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

void setup()
{
  pinMode(led,OUTPUT);
  pinMode(BUTTON,INPUT);
}
boolean debounce(boolean last)
{
  boolean current = digitalRead(BUTTON);
  if (last != current)
{
  delay(5);
  current = digitalRead(BUTTON);
}
return current;
}

void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledLevel = ledLevel + 51;
  }
  lastButton = currentButton;
  if (ledLevel > 255) ledLevel = 0;
  analogWrite(led, ledLevel);
  analogWrite(led, ledLevel + 51);
  delay(200);
  analogWrite(led, ledLevel + 102);
  delay(200);
  analogWrite(led, ledLevel + 153);
  delay(200);
  analogWrite(led, ledLevel + 204);
  delay(200);
  analogWrite(led, ledLevel + 255);
}

The code above turns the led on and cycles brightness, like it should it however for some reason it does disable the button.  Take the analogWrites out except for the first one, and the button will cycle the led. any suggestions on what i could do?  Im very new at this.

Something like this, with variable declarations & setup() left to you.  All time elements are of type unsigned long.

pwmValue {} = [51, 102, 153, 204, 255];

void loop(){
  if (digitalRead(startButton) == LOW && pwmCycling == 0){
    // start button pressed, and not already running
    startTime = millis(); // capture the time of the button press
    pwmCycling = 1; // keep track of the running state. 0 for off, 1 for on.
    }
  if (pwmCycling == 1){ // cycling is running
    // this is where the blink without delay is:
    currentTime = millis(); // capture the time now
    elapsedTime = currentTime - startTime; // see how much time went by
    if (elapsedTime >= eventDuration){  // enough?  start next brightness
      currentTime = startTime; // set up for next event time
      brightNumber = brightNumber +1; // keep track of brightness level
      if (brightNumber >= 5){ brightNumber = 0; } // reset after the last level
      analogWrite (ledPin, pwmValue[brightNumber]); // write the LED pin
      }
    }
  if (digitalRead(startButton) == LOW && pwmCycling == 1){
    // start button pressed while LEDs are cycling, stop them
    pwmCycling = 0;
    analogWrite (ledPin, 0);
    brightNumner = 4; //reset the brightness level to the end
    delay (100); // little bit of dumb debounce delay
    }
}


Sketch skipping the OPEN Arduino inputs Folks,
I am a beginner to Arduino. I have a sketch that tests a set of INPUTS for HIGH or LOW by using a 'for' loop. When the for loop reaches an INPUT which is kept OPEN (no wires connected to it), the for loop apparently 'skips' that INPUT and move on to the next. However, if I have +5V connected to any INPUTS within the range of the for loop, it works correctly. Any thoughts what's is happening here?

You should always connect something to an input to pull it high or low when no signal is present.  The simplest thing is to activate the built-in pullup resistor, which will result in the input returning HIGH when there is nothing connected.  If that's not compatible with your particular use, add a resistor from the input to ground (10k-100k is fine) so that it will return LOW when nothing else is connected.  If the input is just floating, it is susceptible to noise causing random state changes. The input impedance is very high (100 Meg) so it can pick up static and other mischief.


Unexpected Delay Between For Loops I made some arduino code for leds that blink down a row and then back again, but when the program is run, there is an approximately 2 second delay in between the first for loop and the second. This is my code in the loop function:

int leds[] = {13, 12, 11};
int i;

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

  for (int i = 0; i < sizeof(leds); i ++) {
     pinMode(leds[i], OUTPUT);
  }
}

void loop() {
    for (i = 0; i < sizeof(leds); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i; i > 0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

It really makes the program look weird when the LEDs are blinking on a breadboard. Keep in mind that this only happens after the first for loop, the second is continuous back to the first. Any idea why this might be and how to fix it?

The claim “The cause it that your 3rd led (2nd element in the array) is reapeted twice” is wrong.

Apparently that sentence is supposed to mean that the long delay is due to i being one too large, coming out of the first loop and entering the second one.  Indeed, i is too large, but that's because each element of the array is a 2-byte int, so that instead of for (int i = 0; i < sizeof(leds); i ++) being equivalent to for (int i = 0; i < 3; i ++), it is equivalent to for (int i = 0; i < 6; i ++).

Thus, one second goes by with an extra 4 occurrences of delay(250); in the first loop, and another one second with 4 extra occurrences of delay(250); in the other loop.

To correct the problem, write sizeof leds/sizeof leds[0] instead of sizeof(leds), and write for (--i; i > 0; i--) instead of for (i; i > 0; i --).


Fading red to white to blue continuous loop on ws2812 LED strip I'm a big noob when it comes to writing a sketch and have set myself a task for an upcoming 4th July project, which has come to a halt.

I'm trying to set a strip of 30 LEDs to fade from red to white to blue through FastLED on a Wemos D1 mini. I also wanted it to flash each colour after the 3 colours have faded and continuously loop these.

I have searched many different forums and managed to get the fade to go from red to blue, but can't for love nor money add the white in-between.

Can someone point me in the right direction?

#include "FastLED.h"
#define NUM_LEDS 30
#define DATA_PIN D4
#define COLOUR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {

    FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

    //start from red
    for( int colorStep=0; colorStep <= 255; colorStep++ ) {

        int r = 255;
        int g = 0;
        int b = colorStep;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }

    //into blue
    for( int colorStep=255; colorStep >= 0; colorStep-- ) {

        int r = colorStep;
        int g = 0;
        int b = 255;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }
}

Think of a color as a point in 3d as defined by its r g b attributes

Think of two points here, one is your starting color in that 3d space, and another your ending color.

Figure out the path you want to take from the starting color to the ending cokor.

Chop it up in a few steps and use your code to walk the path.

Done


What is the datatype of the pinMode function? I just tried it, but the Arduino IDE crashed, I hope its not related.
I want to declare a datatype like this:

int a = pinMode(pin, OUTPUT);

or something like that, but I'm not sure what datatype the pinMode function uses. I looked on the pinMode documentation page, of the Arduino website, and I see basic usage, but not a more clear definition of the source code for that function.

pinMode(pin, Mode); is a void. It doesn't return anything. It simply sets a pin as an OUTPUT or an INPUT.
It says it in the link you posted.

Returns
None

That means that the function doesn't return any value.


LCD lights up but shows no text I've connected an LCD display to an Arduino Uno following the instructions from the Adafruit LCD lesson.

I've used the code sample described in the Adafruit lesson.

What happens after I connect the Uno to the USB cable is that the LCD lights up, but no text is displayed.

I've checked all connections and they look good. I am not 100%sure I have connected the potentiometer correctly, as this is the symptom I usually found online.

Could this also be a bad solder job? It's my first attempt and I guess it did not go that great.

Here are some more images, maybe someone with more experience can spot the error.

Update: here's what the board looks like once connected

and after removing the ethernet shield I get some weird flashes from time to time, only when I switch the potentiometer to maximum on one side, see video at https://i.imgur.com/ZclD2xz.mp4 .

Update 2: I realised that this is a 20-pin LCD screen and re-reading the datasheet and some online tutorials I switched digital wire connections to pins to the LCD 7-10 (DB0-DB3) - same result and then 11-14 (DB4-DB7) - garbled output, shown below. Still no idea what is wrong.

From provided picture it is visible that your display is not alphanumeric display (with most popular HD44780 driver). It is a graphical display (most popular: KS0107 or KS0108 or ST7920). You can count horizontal pixels and vertical ones in the picture to confirm its resolution.
Without too many problems you can drive it with your Arduino. Try to use some of 128x64 Arduino libraries. Also, check the rear of the display for any part number to confirm the driver (search in google).
 Good luck!


Arduino, Receiving Instant Time When Event Occurs i am trying to figure out situation that i have mentioned about in the topic.

I am trying to get an event's time when it occurs. For example, i am trying to receive Diagnostic Port's data by Arduino CanBus shield and i want to print instant time on screen. For example whenever i receive RPM value from car at a time(time in terms of milisecond) i want to display that time on serial monitor. May be i will run the code for 2 hours. I know that i can use RTC for some time process, but i want to solve this situation without RTC.

Here is my code,

//Canbus.ecu_req(state[check % 3].pid, state[check % 3].buffer);
strcpy(state[check % 3].buffer, "HELLO !");
state[check % 3].time = millis();
state[check % 3].f1 = SD.open(state[check % 3].sdName, FILE_WRITE);     //  Open vehicles' variables sd file
state[check % 3].f2 = SD.open(state[check % 3].sdTimeName, FILE_WRITE);     // Open vehicles' variables time file
if (state[check % 3].f1 && state[check % 3].f2) {
    state[check % 3].f1.println(state[check % 3].buffer);   // Write pid values
    state[check % 3].f2.println(state[check % 3].time);     // Write time values
    Serial.println(state[check % 3].buffer);
}

As you can easily see from my code, i assigned millis() to value of my variable's time when it receives OBD value from car.

It's not very clear what you expect to see.

You are currently using millis() which returns the number of milliseconds since the program started running.  This can run for 50 days without wrapping.  It has no relevance to the real time unless you recorded the time the program started.  You could write something to add millis to the start time if you wanted (look at http://playground.arduino.cc/Code/time)

Alternatively you could use a real time clock (DS1307 or DS3221) which a usually just a few pence/cents.  These ICs keep the current real time and return it when queried.  If you are trying to log data from sensor (or cars) then this will give you the real time the data was received by the Arduino, and it will make a lot more sense.

Your current code will display

45678

An RTC could let you display

Wednesday 22nd February 2017 13:05:42.32


Combine bits from two ports into a single byte I'm attempting to read the values of 8 pins at a time into a byte.

The obvious answer to this seems to be the Port registers, however with the way the Arduino is wired, I'd have to split my read across two registers.

In this case, I need a way to combine the lower 5 bits of PORTB with the upper 3 bits of PORTD into a single byte.

For example, this is the physical layout with the data lines I'm attempt to read/write to and their corresponding port assignments.

             SCSI
DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
|   |   |   |   |   |   |   |
PB4 PB3 PB2 PB1 PB0 PD7 PD6 PD5
            AVR

From what I can gather I need to use some shift operators to achieve this,
perhaps something like:

hi = PORTB & 3;
lo = PORTD >> 3;

But I'm unsure if that's correct and then how I would combine them.

Is it possible to write a macro to make getting and setting this byte easier?

Is there a good learning resource on bit manipulation like this?

Assuming PORTB and PORTD are correctly giving unsigned char values:

result = (PORTB << 3) | (PORTD>>5)

would do it.

As a macro:

#define SCSIBITS ((PORTB << 3) | (PORTD>>5))

Then use like this:

result = SCSIBITS

To make it clearer which specific bits are being used, write:

#define SCSIBITS (((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

It should be easier to see that the lower 5 bits of PORTB, and the upper 3 bits of PORTD are being used.

In the general case, where the values being manipulated are not unsigned char (should not be a problem in this specific case, but may be helpful to know), you might write:

#define SCSIBITS ((unsigned char)((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

or:

#define SCSIBITS ((((unsigned char)PORTB & B00011111) << 3) | (((unsigned char)PORTD & B11100000) >> 5)))

Here are a few links to bit-manipulation tutorials:
https://www.hackerearth.com/notes/bit-manipulation/
http://www.cprogramming.com/tutorial/bitwise_operators.html
http://www.tutorialspoint.com/ansi_c/c_bits_manipulation.htm


Teensy: SPI and Pressure Sensor I'm first time working with a Teensy 3.1. I have to connect this (MS5803-01BA: http://www.amsys.de/products/ms5803.htm) pressure sensor via SPI to my Teensy.

My problem is, that I don't have any reliable knowledge on SPI. I read the Wikipedia for it and also the Teensy-Manual.

For the pressure sensor I already got a C-Code but it is only working with the ATMEL ATmega644p microcontroller. I tried to get the code to work with my Teensy, but it seems like I don't get either any input nor any output.

I hope that one of you can help me with the following code and tell me what I'm missing out on. Thank you.

Code:

http://pastebin.com/xaWXfRUR

Datasheet of the pressure sensor:

http://www.amsys.de/sheets/amsys.de.ms5803_01b.pdf

C-Code for the pressure sensor for the ATMEL ATmega644p microcontroller:
http://www.amsys.de/sheets/amsys.de.an520_e.pdf

PS: Please excuse my not perfect English for it's not my native language.

Details about SPI at SPI - Serial Peripheral Interface - for Arduino

This isn't right:

  SPI.transfer(CMD_ADC_READ); // send ADC read command
  SPDR = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  ret = SPDR;
  temp = 65536 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 2nd byte
  ret = SPDR;
  temp = temp + 256 * ret;
  SPDR = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

The SPI library handles SPDR for you. Writing to it yourself will corrupt its behaviour.

It should be more like:

  SPI.transfer(CMD_ADC_READ); // send ADC read command
  ret = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
  temp = 65536 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 2nd byte
  temp = temp + 256 * ret;
  ret = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)

Ditto for elsewhere.


Controlling 16x2 LCD backlight (I2C module) I've installed an I2C module on my 16x2 LCD so i don't have access to all those LCD pins to control the backlight LED.

BUT there is a 100 ohm smd resistor in series with anode of the backlight LED, i want to remove the resistor and use Arduino PWM to control the backlight or i can just replace that resistor with a 330 ohm or a 1K resistor.

Red box showing the resistor and blue box showing the Jumper.

Also I2C module itself have a jumper for LED backlight which also goes to that resistor...

Just wanted to ask here and make sure it is going to work before doing any modification to the LCD.

which way is better? is it going to work?

UPDATE: i used Arduino PWM and a 2n2222 transistor and was able to successfully control the backlight brightness via jumper pins of I2C module.

It's hard to tell from the limited information, but chances are the "backlight jumper" mentioned in passing in the datasheet can be simply removed.  This will then give you two pins.  One will connect to pin 3 of the IO expander, and the other will connect to the back light anode itself.

Which is which you will have to discover for yourself.  One of them will have the 100Ω resistor in line with it as well.

If you can't see the tracks (some black boards are hard to make them out) then you should get a digital multimeter and set it to continuity mode and probe the pins to see where they lead.

Once you have identified which pin is which you can connect the one that goes to the back light to your Arduino and drive it with PWM.


`servo.attach()` paralyzing (one) motor on L298N I have 2 DC motors (well, 4; but each pair is controlled by the same "signals") connected via a L298N, which is connected to the Arduino. In addition, I have a servo motor connected to the Arduino.

When I run the following program (in reality, it's a bigger program; however, I've managed to chiseled it down to the following):

#include <Servo.h>

const int servoPin = 3;
Servo servo;

const int LMotorsSpeedPin = 5;
const int RMotorsSpeedPin = 10;
const int LMotorDirectionBit1Pin = 7;
const int LMotorDirectionBit2Pin = 6;
const int RMotorDirectionBit1Pin = 8;
const int RMotorDirectionBit2Pin = 9;
const int MotorSpeed = 150;

void setup()
{
  // 1
  pinMode(servoPin, OUTPUT);
  servo.attach(servoPin);

  // 2
  pinMode(LMotorsSpeedPin, OUTPUT);
  pinMode(RMotorsSpeedPin, OUTPUT);
  pinMode(LMotorDirectionBit1Pin, OUTPUT);
  pinMode(LMotorDirectionBit2Pin, OUTPUT);
  pinMode(RMotorDirectionBit1Pin, OUTPUT);
  pinMode(RMotorDirectionBit2Pin, OUTPUT);

  // 3
  digitalWrite(LMotorDirectionBit1Pin, LOW);
  digitalWrite(LMotorDirectionBit1Pin, HIGH);
  analogWrite(LMotorsSpeedPin, MotorSpeed);

  // 4
  digitalWrite(RMotorDirectionBit1Pin, LOW);
  digitalWrite(RMotorDirectionBit1Pin, HIGH);
  analogWrite(RMotorsSpeedPin, MotorSpeed);

  // 5
  delay(10000);
}

void loop() {}

1 Sets up servo.
2 Sets up L298N pins.
3 Sets up left motor data.
4 Sets up right motor data.
5 Tests the code above for 10 [s].

I assume that you'll need some experience with the L298N; however, here's the gist.

*MotorsSpeedPin sends each motor what speed (MotorSpeed 0-255) they must go (via PWM).
Data into a pair of *MotorDirectionBit*Pin tell each motor what direction to go (i.e. back 01, stop 00 11, right 10).

When I run the program above, only the left motor runs. However, if I comment out 1 (which essentially renders the servo useless), both left and right motors start to work.

I find this problem quite odd. What does the servo code have to do with the motor code (and only one at that!)?

The Servo library uses Timer 1 to create the servo control signal. That means it can run the servo on any pin or combination of pins, and at the 50Hz speed that a servo likes best.

However, pins 9 and 10 also use Timer 1 to create the PWM signal.

It can't do both.

As soon as you start using the Servo library you lose PWM on pins 9 and 10.

So what can you do about it? Simply move your pins around to different pins. You can't use 9 and 10 for PWM, but you can use them for the servo. So put your servo on pin 10 and your right motor speed control on pin 3 and all should be happy.


Electret microphone amplification I've got an electret microphone and I understand that I need quite some amplification to get it to be read by an Arduino (0-5V input). So I seeked the web, but answers are as different as people on the street. Some use Op-Amps, some only a transistor cicruit or the like. This guy is using 2 amps before and after his filters Video, LM386 and this guy claims, that exactly this amp isn't good for the job: recommends NOT using LM386.

I really only want to have a threshold switch, so I need no filters whatsoever and not a super duper amplification. What is the simplest solution, with which I can read a voltage with the arduino? With a transistor alone (seems easiest to me so far) - how can I know how much it amplifies (or as I understand it modifies the "other voltage" to look the same)?

I found many different schematics using various op-amps, but regarding them I don't really need another tutorial, but rather a rule of thumb for a "readable" amplification. Is 100 times enough? I found circuits with 1000 times amplification, so I'm really wondering which one works fine.

However the really simple thing would be this: video at 17sec. At second 17 and 50 or so, they show an extremly basic circuit, which would be exactly what would work best for me... However the question is, if this is enough amplification for the ADC in an arduino.

If I can't get a satisfying answer I think I'll build both and see how they compare/work for me.

For the most basic circuit you must bias your microphone since it is electret with a 10k pull up resitor. If you do not want to build a complex circuit you could use a breakout board such as this one.  To build your own see here. It is used as a VU meter which is basically the same idea.  Also, make sure you observe polarity(pin with traces touching metal packaging is negative).


How can I give power to Arduino Uno using a 12V 7.5 Ah Lead-Acid battery? I am trying to give power to my Arduino Board using a 12V 7.3 Ah Lead-Acid Battery but I am unable to do it.

I connected the battery to Arduino Uno (via DC Pin) and it worked for a couple of minutes but then, it automatically stopped working. I checked the voltage of the battery using a Multimeter from the same DC Pin which was connected with battery and board. The voltage was 12.62 volts.
Then I thought my board might have been fried. So, I checked the board by connecting it with a 12V 2 Amp DC adapter and I found that my board was not fried and it was working fine with the Adaptor. The Adaptor was giving 12.48 volts voltage. Then, I again checked the board using battery but still it didn't work. I tried charging the battery via a charger but it still didn't work. I tried these steps multiple times but the results were always same.

I checked with my 12V DC Fan & some other devices also and it works perfectly, but it doesn't work with my Arduino Board.
This indicates that my battery is in a good condition but not working with Arduino Board only. While Arduino is also in a good condition, working with 12V DC Adaptors but not with the Battery.

Please Help!

The input voltage on the DC pin is specified as 7 to 12V. Your battery may well be supplying more than that, causing the voltage regulator to overheat and shut down.

  The voltage was 12.62 volts.

That is out of spec for the Arduino Uno. When you operate out of specified voltages anything can happen, and that anything may not be very good.

You could get a buck converter to lower the voltage.

Certainly a Uno should be able to run for a long time on a 7 Ah battery (provided you are supplying voltages in range for it, preferably using a buck converter or similar to make sure that a fully-charged battery does not supply too high a voltage).