Trouble reading from multiple analog ports So I'm trying to read 4 different analog values and store each one to a variable.  I imagine doing this by first initializing the ADC registers and each time it enters the ADC ISR checking which port it read from and saving it to the corresponding variable.  Then setting the ADMUX to the next ADC port and repeating the whole process.  Unfortunately something goes wonky and I just can't figure out what it is.  If I get rid of the switch case and just read from one port it all works fine, but if I put the switch case back in and try to cycle through them it stops working.  Please ignore the rest of code as this is not complete.  I just included everything I could.  Eventually this will take in 4 values.  Then use them for error checking and a PID loop.

Thanks for any help!

/*
 * Throttle_by_Wire.c
 *
 * Basic throttle by wire controller
 * for the 2015 Formula Hybrid car
 *
 *  Created on: Nov 24, 2014
 *  Author: Austin R. Bartz
 *
 *  Pin Connections:
 *      PB2 - Motor Speed (Enable pin) (PWM)
 *      PB4 - Direction control (Counter-Clockwise)
 *      PB5 - Direction control (Clockwise)
 *      PC0 - Throttle Pedal Sensor A (TPA) (Shallower Slope)
 *      PC1 - Throttle Pedal Sensor B (TPB) (Steeper Slope)
 *      PC2 - Throttle Valve Sensor A (TPSA) (Negative Slope)
 *      PC3 - Throttle Valve Sensor B (TPSB) (Positive Slope)
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <inttypes.h>
#include <stdlib.h>

uint16_t TPA = 0;
uint16_t TPB = 0;
uint16_t TPSA = 0;
uint16_t TPSB = 0;
uint16_t analogpin = 0;

long map(long x, long in_min, long in_max, long out_min, long out_max);

int main(void)
{
    //Configure ADC for single shot conversion
    ADMUX |= (1<<REFS0);
    ADCSRA = (1<<ADEN)|(1<<ADSC)|(1<<ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
    DIDR0 = (1<<ADC4D)|(1<<ADC3D)|(1<<ADC2D)|(1<<ADC1D)|(1<<ADC0D);
    //Configure timer/counter1 for FastPWM
    TCCR1A = (1<<COM1B1)|(1<<WGM11)|(1<<WGM10);
    TCCR1B = (1<<WGM13)|(1<<WGM12)|(1<<CS10);
    OCR1A = 800;    //20kHz
    //Set motor control pins as outputs
    DDRB = (1<<PB2)|(1<<PB4)|(1<<PB5);
    PORTB |= (1<<PB5);
    //Enable global variables and interrupts
    sei();

    while(1)
    {
        //Control PWM % to motor
        OCR1B = map(TPA, 0, 1023, 0, OCR1A);
    }
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

ISR(ADC_vect)
{
    //Save current conversion's ADC value
    analogpin = ADMUX & 0b00001111;
    switch (analogpin)
    {
    case 0:
        TPA = ADCW;
        //Increment ADC port to ADC1
        ADMUX |= (1<<MUX0);
        break;
    case 1:
        TPB = ADCW;
        //Increment ADC port ADC2
        ADMUX &= ~0b00001111;
        ADMUX |= (1<<MUX1);
        break;
    case 2:
        TPSA = ADCW;
        //Increment ADC port to ADC3
        ADMUX &= 0b00001111;
        ADMUX = (1<<MUX0)|(1<<MUX1);
        break;
    case 3:
        TPSB = ADCW;
        //Reset ADC Port to ADC0
        ADMUX &= ~0b00001111;
        break;
    }
    //Start next conversion
    ADCSRA |= (1<<ADSC);
}

Case 2 is missing the ~ and does not clear off the low 4 bits

  ADMUX &= 0b00001111;

should be this to clear off the MUX selection bits:

ADMUX &= ~0b00001111;

Also, you have no default case.  I would agree that by design the bits can only contain the values 0-3, but what happens if it ends up 4?

The bit manipulation is hard to follow.  I would implement like this:

ISR(ADC_vect) {
  uint8_t nextMux;

  //Save current conversion's ADC value
  analogpin = ADMUX & 0b00001111;
  switch (analogpin) {
    case 0:
      TPA = ADCW;
      nextMux = (1<<MUX0);
      break;
    case 1:
      TPB = ADCW;
      nextMux = (1<<MUX1);
      break;
    case 2:
      TPSA = ADCW;
      nextMux = (1<<MUX0)|(1<<MUX1);
      break;
    case 3:
      TPSB = ADCW;
    default:
      nextMux = 0;
  }
  // set mux for next conversion
  ADMUX &= 0b11110000;
  ADMUX |= nextMux;

  //Start next conversion
  ADCSRA |= (1<<ADSC);

  return;
}

I like the consistent pattern of this because it makes errors easy to see.  With respect to code space, a few bytes should be saved.  Execution time wise, it adds one |= to the case 3.


ATTiny to drive LEDs I'm installing some daylight running lights in my car and I have purchased 2 LED bars, each with 8 white LEDs. They use 12V and I need to make some effect when they turn on. Like in some modern cars, when I turn on the key, LEDs should blink(shake like when old fluorescent tubes turns on) and then turn on slowly(brightness from 0-100).

I can do this with Arduino-Uno and I need to put this in a smaller chip. What would be the best suitable ATTiny chip for this project? Because using an ATmega328 is not worth for a small project like this.

The ATtiny85 is an 8-pin AVR device with 3 PWM channels available in DIL and SO packages. The Arduino core can be downloaded from arduino-tiny. It can be programmed via ISP using either ArduinoISP or a dedicated programmer.


How to display extended ASCII characters, e.g., the standard degree symbol, DEC 167, on the Serial Monitor [not LCD]? I spent an afternoon researching this, and read a lot of material, but with no successful results.  [I really thought this would be a trivial task.]

Is this problem Windows, or WIN10, specific, as the extended characters all seem non-displayable? Regardless, is there a solution?

The Arduino serial monitor uses UTF-8, per the discussion at http://forum.arduino.cc/index.php?topic=172814.0 --

For the U+00B0 degree symbol, you'd send the bytes UTF8 0xC2 0xB0 like this:

Serial.print("°");


Sketch stops printing after writing a few times I am trying to build a random horoscope printer. I have a series of strings in an array which I am storing in program memory. I then pick a random number and print that index concatenated with a title. But it often (but not always) only runs 4 or 5 times.

#include <avr/pgmspace.h>

const char string_0[] PROGMEM = "You have a great need for other people to like and admire you. ";
const char string_1[] PROGMEM = "You have a tendency to be critical of yourself. ";
const char string_2[] PROGMEM = "You have a great deal of unused capacity which you have not turned to your advantage. ";
const char string_3[] PROGMEM = "While you have some personality weaknesses, you are generally able to compensate for them. ";
const char string_4[] PROGMEM = "Your sexual adjustment has presented problems for you. ";
const char string_5[] PROGMEM = "Disciplined and self-controlled outside, you tend to be worrisome and insecure inside. ";
const char string_6[] PROGMEM = "At times you have serious doubts as to whether you have made the right decision or done the right thing. ";
const char string_7[] PROGMEM = "You prefer a certain amount of change and variety and become dissatisfied when hemmed in by restrictions and limitations. ";
const char string_8[] PROGMEM =  "You pride yourself as an independent thinker and do not accept others' statements without satisfactory proof. ";
const char string_9[] PROGMEM = "You have found it unwise to be too frank in revealing yourself to others. ";
const char string_10[] PROGMEM = "At times you are extroverted, affable, sociable, while at other times you are introverted, wary, reserved. ";
const char string_11[] PROGMEM = "Some of your aspirations tend to be pretty unrealistic. ";
const char string_12[] PROGMEM = "Security is one of your major goals in life. ";

const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5, string_6, string_7, string_8, string_9, string_10, string_11, string_12};

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(2));
}

void loop() {
    Serial.println("WE GOING TO LOOP NOW");
    char buffer[50];
    int rand = random(0,12);
    Serial.println(rand);
    strcpy_P(buffer, (char*)pgm_read_word(&(string_table[rand]))); // Necessary casts and dereferencing, just copy.
    char text[15] = "Your horoscope";
    String output;
    output = strcat(text, buffer);
    Serial.println(output);
    delay(1000);
}

I also sometimes don't seem to get very clean results, but I'm not sure why. I.e. printing WWWW... and missing the first part of the string in the serial monitor.

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GOING TO LOOP NOW
1
Your horoscopeYou have a tendency to be critical of yourself.
WE GOING TO LOOP NOW
3
or them. While you have some personality weaknesses, you are generally able to compensate for them.
WE GOING TO LOOP NOW
4
Your horoscopeYour sexual adjustment has presented problems for you.
WE GOING TO LOOP NOW
2
ge. You have a great deal of unused capacity which you have not turned to your advantage.

What you see is undefined behavior. You define your buffer to have a length of 50 bytes:

  char buffer[50];

This is too short for most of the strings you want copy into it and you will thus overwrite other variables.

The simplest solution is to increase the buffer size so that the longest string fits (e.g. 150). You will see that it then works as you expect. Take a look at http://linux.dd.com.au/wiki/Arduino_Static_Strings for hints how to avoid wasting RAM for the buffer.


Accesing the USART registers by Arduino I'm having a hard time understanding how the Arduino libraries are defining the address for accessing the registers of the USART modules.

I cant find definition for udr(pointer) as used in the delegated constructor for Hardware Serial. So how does the class gets the underlying address? And what type of declaration is this?

HardwareSerial::HardwareSerial(
  volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
  volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
  volatile uint8_t *ucsrc, volatile uint8_t *udr) :
    _ubrrh(ubrrh), _ubrrl(ubrrl),
    _ucsra(ucsra), _ucsrb(ucsrb), _ucsrc(ucsrc),
    _udr(udr),
    _rx_buffer_head(0), _rx_buffer_tail(0),
    _tx_buffer_head(0), _tx_buffer_tail(0)
{
}

It is handed the addresses when the object is constrcted:

 HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);

&UDR is passed as *udr. That is then assigned to _udr in the initialiser list.


Where is the Aref pin for Attitny88 I would like to use the external analog refence voltage in an Attiny88 project I am working on that will be powered with batteries.

However, the datasheet for this processor does not show an Aref pin like other versions of the attiny, like attiny85 and attiny84, where it is usually the pin PA0 or PB0. Does anyone know where is the pin for the external voltage reference in attiny88 (e.i. Aref pin)? Does this chip has the functionality for an external analog reference voltage?

As shown in the detailed information for the ADMUX register in the ADC section of the datasheet, the ATtiny88 has no external voltage reference. Consider using a ATmega8 or ATmega88PB instead.


Dimming this ~30V led with PWM, what do I need? I have a street lamp with a led and simple driver in it, I don't know the exact led voltage but the driver (image attached) says 27-36V DC output, MODEL: 50W.
Is there a part I could place between this driver and the led, so I can control dimming by Arduino via PWM ?
The led driver specs (large image below) says: INPUT; AC 85-285V and OUTPUT: DC 27-36V 1500mA, MODEL: 50W
I thought it would work to put this "PWM power module" between the driver output and the led, but (I tested months ago) I remember it started to blink, I think only when decreasing power but not on full power (controlled by PWM with arduino).

Should it work with this module or I am trying something very wrong ?
Are there any other parts that should work for sure in this situation ?

The specs on the PWM module are these:
Voltage: 5 V - 36 V DC;
Power: 400 W;
Current: 30 A;
PWM Voltage: 3.3-20V;
PWM frequency: 0-20kHz ;

It will not be possible for you to PWM dim your LED with that LED driver (power supply).
That is a constant current driver with under/over-voltage protection. It delivers a specific amount of current (1.5A) and varies the voltage to allow that to happen.
If the voltage rises too high or falls too low then there must be a fault, so it shuts the power off. This is usually because there is either a short (LEDs tend to "fail short") or an open circuit. The former causes the voltage to drop too low and the latter for it to be too high.
When you insert PWM control you alternate between driving the LEDs and an open circuit. If that open circuit persists too long (low duty cycles) the driver will shut off.
You will need to replace the LED driver (the power supply) with one which includes PWM control internally to it.


Is std::array (from the C++ STL) safe to use on arduino? Does it use dynamic memory allocation? I'd like to use std::array on a project that will need to be very stable, and have all memory pre-allocated to avoid heap fragmentation.

I am reading in characters from the serial port, following a known protocol. Each received byte will be written to a char array of ample size to hold the longest possible string I will receive. I will then perform some minor on the fly operations, (i.e. skipping certain characters, replacing one with another, etc.) and write those out another serial port.

This device needs to function indefinitely. I will not be calling malloc or new anywhere in my code. All of my control objects are singletons, (audible gasp from the high-level crowd!) created during setup, and never being destroyed.

Is the STL array template safe to use in this context?

After reading this post, and this post, the only potential issues I can see are exception handling. As far as I'm concerned, an exception is as fatal as an access violation. I would not expect to ever attempt recovery from an exception, so I don't care that Arduinos don't support them.

But what will happen if the program tries to throw one? Will the arduino compiler even allow the use std::array if it supports exceptions? Is there an Arduino-friendly array template that uses fixed size arrays and supports iterators?

Thanks!

std::array does not use dynamic memory allocations to store its elements. If you use static or stack-allocated std::arrays, you don't have to worry about memory fragmentation (contrary to std::vector or String, for example).
Of course, if you allocate arrays on the stack, you can have a stack overflow if you call too many functions, either by design, or because of a bug.

That brings us to the problem of exceptions. If you look in the standard, you'll see that most of the member functions of std::array are marked noexcept, with the notable exception of the element accessors. Obviously, the at() accessor can throw, but you'd expect that operator[] doesn't.
In practice, operator[] is marked noexcept in the version of the STL (GCC9) that I have on my computer, so if you check it in the STL implementation you're using, you can be pretty confident that it won't throw. Just keep in mind that this is not mandated by the standard.

/usr/include/c++/9/array

      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

The debug version is also marked noexcept, but it can throw/abort if the index is out of bounds:

/usr/include/c++/9/debug/array

      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      {
    __glibcxx_check_subscript(__n);
    return _AT_Type::_S_ref(_M_elems, __n);
      }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      {
    return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n)
     : (_GLIBCXX_THROW_OR_ABORT(_Array_check_subscript<_Nm>(__n)),
        _AT_Type::_S_ref(_M_elems, 0));
      }

The STL implementations for Arduino I found online don't seem to have the <array> header.

Luckily, you can easily create your own array container, for example:

template <class T, size_t N>
struct Array {
    // Storage
    T data[N];

    static size_t length() { return N; }
    using type = T;

    // Item access
    T &operator[](size_t index) { return data[index]; }
    const T &operator[](size_t index) const { return data[index]; }

    // Iterators
    T *begin() { return &data[0]; }
    const T *begin() const { return &data[0]; }
    T *end() { return &data[N]; }
    const T *end() const { return &data[N]; }

    // Comparisons
    bool operator==(const Array<T, N> &rhs) const {
        if (this == &rhs)
            return true;
        for (size_t i = 0; i < N; i++)
            if ((*this)[i] != rhs[i])
                return false;
        return true;
    }
    bool operator!=(const Array<T, N> &rhs) const {
        return !(*this == rhs);
    }
};

void setup() {
  Serial.begin(115200);
  while (!Serial);

  // Create an array
  Array<int, 5> myArray = {1, 2, 3, 4, 5};
  // On older compilers, use double braces:
  //    Array<int, 5> myArray = {{1, 2, 3, 4, 5}};

  // Iterate over the array
  for (int element : myArray)
    Serial.println(element);

  // Access elements of the array
  myArray[2] = 30;
  Serial.println(myArray[2]);
}

void loop() {}


A1 was not declared in the scope I'm trying to put all my settings in a config.h file and then #include it in the Arduino sketch.

Here's what my config.h looks like:

RobotConfig.h

#ifdef BOT
    //hardware pins
    int motor1Pin = 9; //s0
    int motor2Pin = 10; //s1

    //pins for light
    int light2 = A4;
    int light3 = A2; //right
    int light1 = A1; //left

And here's what .ino sketch looks like:

#define BOT
#include "RobotConfig.h"

void setup() {
  //Light INIT
  pinMode(light1, OUTPUT); //left light with motor1/s1 in front
  pinMode(light2, OUTPUT); //middle light with motor1/s1 in front
  pinMode(light3, OUTPUT); //right light with motor1/s1 in front
  ...
}

This compiles fine on my Mac but I'm trying to compile this on Raspberry Pi (Pi3 with new Jessie install with sudo apt-get install arduino) and get an error while doing so. The error says:

  A1 was not declared in the scope etc.

What am I missing?

RobotConfig.h needs to include Arduino.h in order to have those constants.


Can't get actual output when, both input logic is high I want
When,

light=0, ir=0 then output will pin 8 high & pin 12 low.
light=0, ir=1 then output will pin 8 high & pin 12 high.
light=1, ir=0 then output will pin 8 low & pin 12 low.
light=1, ir=1 then output will pin 8 low & pin 12 low (This statement
does not work).

Please find the code & suggest me, if any modification is needed.

void setup() {

    pinMode(8,OUTPUT); //logic output.
    pinMode(12,OUTPUT); //logic output.
    pinMode(2, INPUT); //value input.
    pinMode(4, INPUT); //value input.

    Serial.begin(9600);
}

void loop() {

    int light = digitalRead(2); //value input.
    int ir = digitalRead(4); //value input.

    if (light == LOW && ir == LOW)
    {

      digitalWrite(8, HIGH);
      digitalWrite(12, LOW);
      delay(2000);

    }

    if (light == LOW && ir == HIGH)
    {

      digitalWrite(8, HIGH);
      digitalWrite(12, HIGH);
      delay(2000);

    }

    if (light == HIGH && ir == LOW)
    {

      digitalWrite(8, LOW);
      digitalWrite(12, LOW);
      delay(2000);

    }

    if (light == HIGH && ir == HIGH) //This condition does not work.
    {

      digitalWrite(8, LOW);
      digitalWrite(12, LOW);
      delay(2000);

    }

    digitalWrite(8, LOW);
    digitalWrite(12, LOW);
    delay(2000);

}

You can simplify your requirements somewhat by splitting your inputs up.

  light=0, ir=0 then output will pin 8 high & pin 12 low.

  light=0, ir=1 then output will pin 8 high & pin 12 high.

If light is 0 then pin 8 is high. AND ir is echoed to pin 12.

  light=1, ir=0 then output will pin 8 low & pin 12 low.

  light=1, ir=1 then output will pin 8 low & pin 12 low

If light is 1 then both pins 8 and 12 are low, and you don't care what ir does, since it doesn't have any effect on the outputs.

So your structure could look more like:

if (light == 0) {
    digitalWrite(8, HIGH); // 8 will always be high with light == 0
    digitalWrite(12, ir); // echo the ir value to pin 12
} else {
    digitalWrite(8, LOW); // if light is 1 then everything
    digitalWrite(12, LOW);// is low regardless of ir.
}


Firebase.failed() returns 0 after Firebase.begin(), but returns 1 while reading or writing from/to firebase from ESP8266 The program was running fine, a few days ago, but now it just wouldn't read/write to the database. I'm running on ArduinoJson 5.13.5 and using FirebaseArduino library. I have set all the rules to true, would love to know how to debug this error. Also Firebase.error() does not give any output at all!

Apparently the Firebase's fingerprint has changed recently and has caused the above issue!

from here get the latest finger print and change it in the ...\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient.h

In the file mentioned above: update the value of static const char kFirebaseFingerprint[] to the new one mentioned above.

P.S. One issue going forward for me(planing on implementing it on a long term basis) is how to be ahead of this issue in the future, so that I can get the data uninterrupted!


SKETCH quits working after unplugging from computer Arduino Sketch program runs fine as long as it stays plugged in usb to computer. If I plug in a different power source the sketch quits working. I have plug back in usb and re-download ??? It stops working if I unplug from computer than plug right back in. I have to re down load every time.

I have ran into this problem personally. I believe that you are drawing too much power from your computer's USB port. A USB port can give 500 mA output max provides 5 Volts x 0.5 Amo = 2.5 Watts. With real world efficency losses (nominally 80~90% efficent), you can provide a Higher Voltage with Less Current, or a Lower Voltage with More Current, but you can't create powerout of nowhere.

See this post on a similar issue:
http://forum.arduino.cc/index.php?topic=289005.0

I hope this helps.


Passing a method pointer I created a small library, which takes a callback function:
MyClass::add_callback(bool (*callback_function)(), byte behaviour) {
  // ...
  bool result = callback_function();
  // ...
}

So far, I'm using it for periodic polling (for which I don't want to use ISR interrupts). However, I like to use it for other periodic calls that require a state. A simple example is a blinking light, which has an on-off state, as well as knowledge when the next state change needs to occur.
I like to change this method or add another method that takes a method, instead of a function. How should I do this? I'm struggling with the C basics, but answers on StackOverflow seem foccused to more modern C variants. For example, this great answer on Stackoverflow recommends to use boost::bind, but I rather not include such a large dependency.
What I'm looking for is something akin to:
MyClass::add_callback(void *obj, bool (*callback_method)(), byte behaviour) {
  // ...
  bool result = Object::callback_method(&obj);
  // ...
}

where Object::callback_method(&obj); should be equivalent to Object obj; bool result = obj.callback_method();.
For bonus points, is it possible to make this independent on the Object class?
I'm happy for pointers to other sites (like StackOverflow), provided it is applicable to a bare Arduino program.

The easiest method I know to do this would be to use a "C"-style wrapper for the member function call. This is in fact done to interface C callbacks with C++ objects.
You could do it like this:
struct Blinky {
  //state etc.
  bool isOn() { return /* something useful */ true; }
};

// The "C" wrapper for the callback
bool Blinky_callback(void *vblinky)
{
  return static_cast<Blinky*>(vblinky)->isOn();
}

struct MyClass {
  void add_callback(void *obj, bool (*callback_method)(void *), byte behaviour) {
    // ...
    bool result = callback_method(obj);
    // ...
  }
};

// Globals
MyClass c;
Blinky b;

void setup() {
  c.add_callback(&b, Blinky_callback, 0);
}

A slightly tidier way with a static member (functionally identical):
struct Blinky {
  //state etc.
  bool isOn() { return /* something useful */ true; }

  static bool callback(void *vblinky) {
    return static_cast<Blinky*>(vblinky)->isOn();
  }
};

// ...
c.add_callback(&b, Blinky::callback, 0);

Other variants would be using inheritance and virtual functions.
// Abstract base class
struct Sensor {
  virtual bool do_check() = 0;
};

struct Blinky : public Sensor {
  bool do_check() override { return true; }
}

Then you can have your add_callback look like:
void MyClass::add_sensor(Sensor *sensor) {
  // ...
  bool result = sensor->do_check();
  // ...
}

This is relatively nice to code with, and the compiler has a fighting chance at keeping your code typesafe, if all the "things" you want to control can conform to the same interface. The virtual dispatch won't cost much more (if anything) than the static wrapper in the previous example. You "pay" a few bytes per class and one pointer per instance for the virtual table though.
More modern techniques would involve templates and/or lambdas, or perhaps std::function, but all that seems overkill if your need is as described (and might generate a lot more code than you're expecting, or do dynamic allocations for std::function which is best avoided in context).

Remark: if you want to do it with (non-static) member function pointers, it is possible but the syntax is hairy:
void add_callback(Blinky *obj, bool (Blinky::*callback_method)(), byte behaviour) {
  // ...
  bool result = (obj->*callback_method)();
  // ...
}

And you're tied to that class. Unless you make add_callback a template, but beware extra codegen.


variable name standards, e.g best method to send motion_detect=true I am working with some sensors and sending data to a public web server via http, I was thinking this server can be possibly used by more people to send their data and server displays a chart.
I was wondering if there is a IOT industry standard when sending certain type of data, so that in future I don't need to rename this or change documentation to be more compatible or more intuitive.
For example when sending a "motion detected" ping, do I go with pir=true, pir=1, motion_detect=true ?
Then for example when sending temperature, it would be much better temp_celsius=30 then just temp=30.
It should also make developers job much easier if there is a certain standard. Is there one ?

Yes, there are systems designed to continuously receive such data and the data exchange is standardized, even some Units are standardized.
OPC DA
An example is OPC Data Access for real time values. It seems you want to build a graph, so OPC Historical Data Access is more what you're looking for.
One would set up the data points on the server side once, i.e. configure the type and unit that you're gonna receive on that "channel" or "port" or whatever you call it.
Unfortunately, OPC DA and OPC HDA use XML and building XML is not trivial. It's not very suitable for IoT devices.
Lessons learned: configure the unit on server side and let the client send data only. Do not use XML for data transfer.
OPC UA
Then there is OPC Unified Architecture. They also learned their lesson and removed XML and added security. They now use a binary protocol. The specification is more than 1000 pages, so understanding it will be difficult and is in fact so difficult that even OPC UA implementations of different companies do not work together well.
OPC UA defines 25 data types and ways of defining other data types.
The address space in OPC UA is hierarchical - and probably a device can exist in multiple hierarchies, e.g. physical topology like floors and rooms or logical topology that fits into the structure of the machine.
Lessons learned: make the protocol simple and think about security, i.e. if you want to do URL encoding (GET), then use HTTPS at least. AFAIK, devices ESP32 support encryption, so it's no longer a problem for tiny devices. People will use very strange data types, like 18 bit integers. Also, do not only provide a flat list of devices, but let them arrange stuff as needed.
MQTT and NodeRed
Now these were quite heavy protocols and models driven by companies. Of course there are also protocols better suited for IoT, like MQTT. MQTT is widely known and uses the also well known Node Red software for handling it. You can define workflows how the data should be handled, converted, stored and whether alarms shall be triggered above or below thresholds.
They already think of connection loss, reconnect and how to send all the data that was already recorded but could not be sent.
Lessons learned: People want more than just data storage and a graphics.
Units
openHAB tries to come up with a List of units. I am a radio amateur. I am measuring electromagnetic fields. I am still missing

SWR (standing wave ratio)
dBu (dB µW)
dBc (dB relative to the strongest signal)
dBV, dBmV (dB for Volts instead of Watts)

Personal experience
I was working for a company that made software for industry. There are devices that send a measurement value every 100 ms. Let's say this is a simple temperature value of just 1 byte, that's still 315'000'000 records per year.
How do you display such data? On a Full HD screen you would still need to combine 150'000 measurement values on a single column of pixels.
Lessons learned: you need sophisticated data crunching skills to generate the graphics. The users probably want some control over the time span they are viewing. They want zooming and panning.
Conclusion

I was thinking this server can be possibly used by more people to send their data and server displays a chart.

IMHO, sorry, it's hardly needed. People do not want to send their data to a random HTTP server. Some want to set it up at home only, so that no data ever reaches the Internet. Some people want to do more than just displaying a grpahics (especially alarms). MQTT and Node Red runs locally, on a Raspberry, on a server and even in the cloud, whatever you want.
You do not only need pir=true, pir=1, motion_detect=true, you also need

an ID for the device,
a timestamp when the data was recorded
potentially a way to send bulk data after the server was offline for an hour of maintenance
a system for units
encryption

That's quite an effort. Node Red has > 4000 commits.


Specifying port in Ciao.write As far as I know, Ciao uses port 80 as the default and I haven't found a way of changing the port it attempts to connect to.

I tried using "192.168.0.23:8080" but the Ciao.write() seems to timeout after a while. Is there a way to specify the port to use?

P.S I'm using an Arduino Uno WiFi DevEd

You can't. The factory firmware of Uno Wifi is discontinued.

Uno WiFi and WiFi Link doc


How can I get my (Arduino) Pro Micro schematic to allow me to program it through GPIO instead of USB I'm trying this project so far I've got the schematic of a Pro Micro, which is powered through GPIO from a Raspberry Pi Zero, and want to remove the micro usb connection and able to flash it using an avr programer and a few pins.

How do I get to Achieve that? also the Pro Micro is getting D+/D- from the the raspberry's D+/D- pads as well. Schematic below for reference.

Welcome to arduino.stackexchange.
You can program your ATmega32U4 on at least two ways:
1. Use Arduino's bootloader and D+/D- pins. This way you won't need an external programmer. Try search for phase "programming ATmega32U4 with bootloader".
2. Use ISP (In-System-Programming) method. In this case you can use your avr programmer. To do so you also need access to PINs named Reset, MISO, MOSI, SCLK. See this link or this one

As always, the important read is ATMega32U4 datasheet.


HC-06 module versus 1sheeld Why would someone buy a 1sheeld?

Why not connect an Arduino to their smartphone using HC-06 bluetooth module and find an appropriate Android app, like for example RoboRemo. What is the advantage of using a 1sheeld?

Why would you buy a car when you can cobble something together from some old pram wheels, a lawnmower engine, some old scaffolding, gaffer tape and chewing gum?

Because buying a car is considerably easier and more reliable.  Plus your "friends" don't laugh at you when they see you trying to drive it to work.

Yes, you could cobble something together that might work using random components and other bits of software, but the work involved would be considerably more than plugging in a shield and downloading an app that is guaranteed to work perfectly with that shield.


Arduino Pro Mini interrupts timer not working i am trying to make an arduino pro mini sd card serial logger.The arduino should log the data that comes over the uart and write it to an sd card and if it is no data on the serial for 25 seconds to save automatically the data into the file.Each file are named diffrent every time they are saved(for example datalog0.txt, datalog1.txt and so on).I am creating also at the start of the sketch an config(config.txt) file where the number of the file present of the sd are stored and if the file already exist than a new one will be created, this option works good.Now, after the 25 seconds past and it is no more  data over the serial the arduino dont close the datalog.txt file , so the next data will be saved in the same file, this is the problem i have, even in the config file the file number will be increased.I will attach the sketch and expect patient from you, ai am still newbie.I forgot to mention that it was working good for some time but not anymore, the only thing i did was to upload the bootloader from ide and since than is not working anymore.

Regards.

//#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <SoftwareSerial.h>

            int i;
            int incomingByte = 0;
//int data[512];
            File myFile;
            unsigned char bytes,flag_again;
            unsigned int fileNo,timer_count;
            String s_fileNo,filename,filename_master;
            char comanda;

            void Timer1_InIt()
        {
            TCCR1A = 0;
            TCCR1B = 0;
            TCNT1  = 0;
            OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
            TCCR1B |= (1 << WGM12);
                TCCR1B |= (1 << CS12) | (1 << CS10);
                //TIMSK1 |= (1 << OCIE1A);
            }

ISR(TIMER1_COMPA_vect)
{
    timer_count++;
    if(timer_count > 25)
    {
        timer_count = 0;
        TIMSK1 &= ~(1 << OCIE1A);
        myFile.close();
        fileNo++;
        myFile = SD.open("config.txt",FILE_WRITE);
        myFile.seek(0);
        myFile.print(fileNo);
        myFile.close();
        //software_Reset() ;    //reset the sketch
    }
}
SoftwareSerial mySerial(4, 5); // RX, TX

void setup()
{
    cli();
    Timer1_InIt();
    sei();

    mySerial.begin(9600);
    Serial.begin(10752,SERIAL_8E2);
    //mySerial.print("Initializing SD card...");

    if (!SD.begin(10))
    {
        //mySerial.println("initialization failed!");
        return;
    }
    Serial.println("initialization done.");

    myFile = SD.open("config.txt",FILE_READ);
// mySerial.println("Config file created");
    if(!myFile.available())
        bytes = 0;
    else
    {
        bytes = myFile.available();
        for(i = 0; i< bytes ; i++)
            s_fileNo += (char)myFile.read();
    }
    myFile.close();
    fileNo = s_fileNo.toInt();
// mySerial.print("file no:");
    //mySerial.println(fileNo);

    filename = "datalog";
    filename += fileNo;
    filename += ".txt";

    myFile = SD.open(filename,FILE_WRITE);
    if (myFile)
    {
        //mySerial.print(filename);
        //mySerial.println(" File Open...");
    }
}

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        /*if(incomingByte == 0 || incomingByte < 15 )
        {
          Serial.print('0');
          myFile.print(0,HEX);
        }*/
        //mySerial.println(incomingByte,HEX);
        myFile.println(incomingByte,HEX);
        // myFile.println(incomingByte);
        timer_count = 0;
        flag_again = 1;
    }
    if(!Serial.available() && flag_again)
    {
        TIMSK1 |= (1 << OCIE1A);
        flag_again = 0;
    }

}

In untested (pseudo-)code

unsigned long lastSerialInput = millis();

void loop()
{

    if(!myFile)
        myFile = SD.open(filename, FILE_WRITE);

    while(Serial.available())
    {
        incomingByte = Serial.read();
        myFile.println(incomingByte,HEX);

        lastSerialInput = millis();
    }

    // check for 25 seconds of inactivity
    if( myFile && (millis()-lastSerialInput > 25000 )
    {
        myFile.close();
        fileNo++;
        filename = "datalog";
        filename += fileNo;
        filename += ".txt";

        //save new fileNo to config.txt (though I'd personally find the file with the largest number in setup instead of relying on a config.txt file)
    }

}


How to use components that don't have a shield? I recently started messing around with an Arduino and I have made a few "gadgets" using shields. I then wondered how I would go about using things I can't find shields for.

One specific thing I want to do is to be able to use the larger e-paper displays from Pervasive Displays (7'' and 10'') but a brief consultation with Google found no Arduino kits or shields. I then looked through the documentation of the timing controller for the 7'' display and found the information required to be able to use it (initiation, sending data to be drawn, opcodes, etc.). I then decided to check the Github repo for the examples for the 2'' displays and they seem to just do what the documentation says to do.

Is my observation naive here? Is it really as straightforward as following the documentation? No magic sauce?

Note: I don't have a clue how complex using the 7'' display actually is, I just used it as an example because I had just looked it up...

Your observation is correct. Everything breaks down to some number of physical connections and some protocol for communicating with the device. Shields and libraries associated with them do most of the work for you, but not everything comes in a shield.

There are some common protocols for interfacing with devices, including SPI and I2C. From a quick peek at the driver interface sheet, it looks like they're using SPI. Well, your Arduino already supports that so you can hit the ground running with this display. You just need to know what commands to send to it, which you can find from the display's datasheet.

Note: It looks like the 2" screen requires 3.3V while the 7" one supports up to 7V.


Unexpected accident of my board, CH341 issue for Linux or Dead ESP? I have early midnight accident of my Lolin/Wemos boards. I tried uploads my sketch with a assembly VIN to GND as my reset button, when i uploads my sketch at more one hundred times, i get my boards cannot be online again or my port cannot readable to my Ubuntu as /dev/ttyXXX. usually when i plugged the Usb3.0 cable, the blink led should be turn on at my boards but i didn't get it. How  i can re-flash my boards to be online again?

Thanks in advance.

Shorting VIN to GND will over-stress the diode that is in-line with the power coming in from the USB.

The result

The diode will blow and you will not get power from the USB to power the board.
The PC may detect "over-current" and shut down the USB port
The USB port on the computer may be damaged

How do you fix it?

Replace the diode if blown.
Use a different USB port.

How do you work around it?

Provide an external 5V power source to VIN & GND if the diode is blown

How do you avoid it happening in future?

NEVER short VIN to GND, even for a short time.  There is a reset pin RST provided for the purpose of resetting the board.


Figuring out some numbers for a mini pump I'm just now getting into electronics (I don't know why I waited so long) and I'm just figuring out some stuff.  I picked up an Arduino kit from Vilros.com and a few other parts for my project.

I'm currently trying to work on a project that is basically a humidor keeper.  Living in So.California, it's extremely dry here and I would like a perfectly controlled environment for my humidor.  I purchased a few things like some humidity sensors (as an input obviously), a humidifier (basically a water canister with a sponge and tubes) some tube splitters and twist valves and most importantly, a small air pump.

The small air pump is what I'm having problems with at the moment.  This is the pump. Obviously it's a 3v pump.  I will be using the supplied 9v battery cable when the project is ready, so I understand I'll have to use resistors to bring the voltage down so I don't burn out the pump.  As I said, I'm new to this, so I'm trying to figure out ohms law to find out what kind of resistor(s) I will need.  The problem is, I don't know the amperage.  Where would I find this?

I looked at the details for the pump and what looks like amps (or milliamps) is really just the product number.  Can anyone help me out?

Right now, I have my equation as r=6v / ?i  But where do I find the current?

There are two serious problems with your approach, which you will need to change in order to end up with a sound solution.

If by "9v battery cable" you mean that you intend to use a 9v battery, this is highly unsuitable for motor applications given its low power storage capacity and high internal impedance - without extreme care to use sleep modes, it probably can't even run the Arduino alone for a week.  It would be much more appropriate to use a larger capacity lower voltage source - 4 or 5 C or D cells for example.  A power supply could be another option, though given the water involved, be very careful to pick an isolated one and use a ground fault protected outlet.
Resistors are a poor way of reducing the supply voltage to a motor, as they are not only wasteful, but the applied power will depend too much on the load.  A professional solution would use pulse with modulation to apply the supply voltage at a reduced duty cycle - something you can try with one the various motor shield, but you will need to be careful not to overheat the motor by using too high a duty cycle.

Probably your best bet would be to buy a pump with a 6 or 7v motor (as is showing up in the associated products at the bottom of that page), or even replace the standard-form-factor motor in that pump with a higher voltage one.  A 7v or so supply voltage can then be a compromise solution for running both the motor and the arduino.


Sending over a number from Arduino to Attiny85 I recently started my first arduino project, displaying a number on a 4x 7 segment display. I want to keep this code and use the display in other projects to display 4 digit numbers (creating a library and using segmentdisplay.write(number) maybe?).

Just displaying the number went really well, but I wanted to drive it with less I/O pins. Then I discovered shift registers, which reduced the number of necessary I/O pins to 3. But, the code needs to execute constantly to keep the 4 digits on the display via multiplexing. My solution to this was to run the sketch on attiny85, on which I programmed the code below. The only thing left to do is to change the value of 'getal' to a value that I read or calculate on the arduino. But I have no idea on how to achieve this, can I shift out data from the arduino to attiny85, which then updates 'getal's value? Any help is appreciated!

const int dataPin = 0;
const int latchPin = 1;
const int clockPin = 2;

const int Db = B00001111;
const int D1 = B00000111;
const int D2 = B00001011;
const int D3 = B00001101;
const int D4 = B00001110;
const int num0 = B11111100;
const int num1 = B01100000;
const int num2 = B11011010;
const int num3 = B11110010;
const int num4 = B01100110;
const int num5 = B10110110;
const int num6 = B10111110;
const int num7 = B11100000;
const int num8 = B11111110;
const int num9 = B11110110;

int D_4[4] = {D1, D2, D3, D4};
int D_3[4] = {Db, D2, D3, D4};
int D_2[4] = {Db, Db, D3, D4};
int D_1[4] = {Db, Db, Db, D4};
const int num[10] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};

const int tallen[4] = {1000, 100, 10, 1};

int getal = 185;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  int lengte = findn(getal);
  switch (lengte) {
    case 1:
      displaynum(D_1);
      break;
    case 2:
      displaynum(D_2);
      break;
    case 3:
      displaynum(D_3);
      break;
    case 4:
      displaynum(D_4);
      break;
  }
}

int findn(int num) {
  int n = 0;
  while (num) {
    num /= 10;
    n++;
  }
  return n;
}

void displaynum(int *D_x) {
  for (int i = 0; i <= 3; i++) {

    digitalWrite(clockPin, LOW);
    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, LSBFIRST, D_x[i]);
    shiftOut(dataPin, clockPin, LSBFIRST, num[(getal / tallen[i]) % 10]);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
}

As Look Alterno stated it would be easier to directly use an LCD display. But if you really want to use the 7 segment display and the ATTiny85 you can use I2C to send the number to the ATTiny. There are libraries, that can use the USI hardware ot emulate a (nearly) full I2C bus. For example my TinyWire library, that I composed from the previous TinyWireM and TinyWireS libraries. I2C needs only 2 pins (pin 0 as SDA and pin 2 as SCL I think), so you still have your 3 pins left for the display.

Then you would make the Arduino master and the ATTiny slave. Use the examples, that come with the library to learn it's usage. Note, that currently you can use the write() function only with one byte, so if you need bigger datatypes you need to split them to byte-level on your own.


What are the distances between Arduino Mega connectors? I am trying to build an Arduino Mega shield. For that, I need to know the exact distances between the different connectors.

The pin layout and dimensions of the Mega are as follows:

Dimensions are in thousandths of an inch. Source


Why does reading an analog pin give a different results when interfacing with Processing? I am interested in measuring the voltage over an analog pin (A6). When I use the Arduino IDE to print the results through the serial I get values around 300.

Here's the code

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

void loop(){
   Serial.println(analogRead(A6));
   delay(50);
}

When I try to run a equivalent program using Processing and interfacing it through Firmata and the corresponding library, I get values around 900.

Here's the Processing code:

import cc.arduino.*;
import processing.serial.*;

Arduino arduino;

void setup(){
   arduino = new Arduino(this,Arduino.list()[0], 57600);
   delay(2000);
}

void draw(){
  System.out.println(arduino.analogRead(6));
  delay(50);
}

Does anybody know what could be the issue? I should probably rather trust the values given directly by the Arduino without interfacing, right?

The pin is connected to a circuit with supply voltage.
I also tried reading the values directly using Serial in Processing (so without using the cc.arduino.* - library) and that showed me the values around 300. So I guess the difference is caused by the arduino.analogRead() method. I am puzzled as to whether that's a bug in the library or something else.

The problem seems to be me not properly initialising the pins. But calling

arduino.pinMode(6,Arduino.ANALOG);

in the setup method does nothing, as does Arduino.PWM, SERVO and any combination I tried. I thought, maybe Processing tried to assign D6 as analog instead of A6, but changing the value to 20 (as it's the pin number according to this) simply caused an OutOfBoundsException.

You have not provided a schematic of how the Arduino is wired up.

However, if nothing is connected to the pin, i.e. it is not connected to ground or a supply voltage, then the input will float. That means that just by placing your hand near the Arduino, then analogRead() will produce a different value than when your hand in not near it.

I would hazard a guess that if you ran both sets of code multiple times then you will get different answers each time, if you start waving your hand around the Arduino.

Try that first, and then tie the input to either HIGH or LOW and then repeat the previous experiment.

In the second case the results should be consistent, and equal in the Arduino and Processing alike.

However, according to your comment, that is not your issue, as your inputs are not floating.

I think that issue is actually this:

  Even with Firmata installed, the Processing application needs to define the pin mode for ALL the pins being referenced, telling the Arduino instance that xPin, yPin, and zPin are ANALOG pins.

Source: Re: Firmata problem with analogRead in Processing Library

Looking at your Processing code the pins are not defined. You need to do so.

With the Arduino code, there is no need to define the analogue pins.


trying to delay between sequences I am trying to build a set of four stars using an Arduino, potentiometer and a four channel relay to control how fast it speeds across the stars. My question is how can I delay the process, say for 20 or 30 seconds before it starts again?

Use Delay(  ).
Or this code

long previousMillis;

void setup(){
  previousMillis = millis();//in void setup
  bool lS=LOW;//in void setup
}

void loop(){
  long currentMillis= millis();//in void loop

  if(currentMillis-previousMillis>=20000){
     if (lS==LOW){
       digitalWrite(pinNo,HIGH);
       lS=HIGH;
     }
     else
     {
       digitalWrite(pinNo,LOW);
       lS=LOW;
     }
     previousMillis= millis();
  }
  delay(1);
}

While this does not serve your purpose, it shows you an how to switch on and off and LED after every 20 sec without keeping the Arduino idle for 20 sec.You could improve on it and make your own code.


Can I run a Mega 2560 on 14v? I have a Mega 2560 with a ramps 1.4 shield. I noticed when I turn on the 14v power supply the mega would also power up and run.

Am I damaging it running it at 14v? If not is there a solder or jumper somewhere that I can set it to only run the mega/logic on the usb power? The 14v is just for the stepper motors.

You can, but you shouldn't, because the the board will heat excessively, as you're out of the recommended range for the input voltage on vin (7-12V).

Unless you have a switching regulator (the one on the board is linear), then you shouldn't' have too much of a difference between the operating voltage and vin as an operating principle because of efficiency (and thus heat) issues.


How to use LCD Screen and IR Remote to broadcast a countdown I am trying to use an IR Remote to input date's and time's for a countdown, so then the LCD will display a countdown, like this:
LCD: Enter Year
Remote-Input: 2021
LCD: Enter Month
Remote-Input: 08
LCD: Enter Day
Remote-Input: 20
LCD: Enter Hour
Remote-Input: 08
LCD: Enter Minute
Remote-Input: 00
LCD: Enter Second:
Remote-Input: 00
LCD: You have __ Years, __ Months, __ Days, __ Hours, __ Minutes, __ Seconds.

How do I do this?

How do I do this?

I have no clue how you do that but I do know I would do that.

I know how to ask a question.

Apparently not, your question is far from perfect (and my answer above is technically the only correct answer to that specific question). It doesn't tell us what you've tried, it doesn't tell us what you haven't tried. It not specific nor practical. Doesn't state your experience with Arduino, doesn't state which hardware you (would) be using. (Though I must say your example output thing is quite nice)

I was just in a rush.

Isn't everyone nowadays? And why would we invest time in an answer on a question which has no effort put into it?

You're basically asking "How to do an Arduino project" (or any project), there's many ways but let's dive into it.
0. Split up your project into smaller projects.
Since it sounds as if you have no clue on how to get started or if you feel this project is daunting, it may help to make the 'problem' easier to get started. You can always add more complexity.
Make one Arduino program, which shows "Hello World" on the LCD.
Make one Arduino program, which receives IR codes and depending on which button pressed, shows "Hello" or "World" in your terminal.
1. Research
Search the internet, maybe there's projects like this. Try to google for "Arduino Countdown Timer". Check what design choices they made, what hardware they use and how they work in general.
2. Design
Make a design, not only about the aesthetic part, but also functionally. What happens if the timer depletes? Should it also have a buzzer? Does it need an enclosure?
And technically, how will it be powered?
3. Acquire hardware
As a starter; it can help to buy hardware from stores that also include example code.
Use the example code to test and verify your hardware and connections.
4. Software
If you're asking "How to write software", you're better off starting out with some example projects/tutorials which include the code and explain it.
But basically you should use the example code to drive the hardware, use examples on the internet combined with your own experience to create a program that matches your required behavior.

If, along this path, you have a practical question. We will be much more able to, and happy to, help.


Is it possible to run emulator from IC? and how? I have an Emulator and Roms I would like to create a portable device to allow me to connect via RCA to a TV and play. Only I have no prior knowledge of how Integrated Circuits function or what they are capable of. If a IC would work, how does one go about programming one to load up the emulator? What other components aside from RCA and USB would I need? Any direction with this would be great and sorry in case I am not asking the proper questions.

I figured arduino is similar to what I am building in regards to circuitry/ electronics. Thanks in advance.

This is the only bit of information I have found online in 4 days thats not store bought.   CLICK HERE

Not a chance, I am afraid.  The Arduino cannot do what you think it does.

Yes, you could program the Arduino to act like some of the simple old video games, but there is no way it can run a pre-existing emulator program like your computer can.

You need something more like a Raspberry Pi - in fact there is an interesting project that might be just what you want: RetroPie


Casting a struct member between uint8_t and char, with regard to serial transfer Im simply trying to pass my payload to another device that has the same architecture and struct. I'm using UART to transfer, and modeling the protocol from EasyTransfer.
When I call Serial.print((char*)mydata.data); in Transfer it prints Hello World as expected.
Calling that same line in Receive prints a '?' to console. This may be some background behavior with Arduino, or I'm just not casting/handling the pointers correctly. How can I get this print out to function properly?
Transfer Sketch
#include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
SEND_DATA_STRUCTURE mydata;

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

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

  //initalize not so random number generator
  randomSeed(analogRead(0));

}

void loop()
{
  //mydata.blinks = random(5);
  //mydata.pause = random(5);

  //Create payload to transfer
  char* payload = "Hello World!";

  //Fill array with data
  strncpy((char *)mydata.data, payload, PAYLOAD_SIZE);

  //Print sample
  Serial.print((char*)mydata.data);

  //send the entire struct
  TransferObject.sendData();

  delay(5000);
}

Receive Sketch
    #include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct RECEIVE_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
RECEIVE_DATA_STRUCTURE mydata;

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

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

}

void loop()
{
  //check and see if a data packet has come in.
  if(TransferObject.receiveData())
  {
    Serial.print("active");
    //print data payload
    Serial.print((char*)mydata.data);
    }

  //you should make this delay shorter then your transmit delay or else messages could be lost
  delay(250);

This is an exerpt and variant from this library

You're actually falling into a common problem with pointers in structs.

This structure:

struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t *data;
};

contains three values: blinks, pause and a pointer to the data.

uint8_t *data;

That doesn't contain the data. That only contains the address that the data is stored at in memory.  When you transfer the struct it's that address that you are sending - then when the other end tries to print it all it can do is look at the address it's been told about and try and print whatever is in there - and that is complete garbage.

Instead of storing a pointer to the data you need to store the actual data itself. That means that you need to decide upon a maximum size for that data and pre-allocate the memory within the struct:

#define DATA_SIZE 40

struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[DATA_SIZE];
};

Now in order to get the data into that struct you need to fill that array with your payload. For strings the simplest way is:

strncpy((char *)mydata.data, payload, DATA_SIZE);

That will copy up to DATA_SIZE characters from payload into mydata.data.

Note that if payload contains more than DATA_SIZE-1 characters the data in mydata.data will not be NULL terminated. You can get round that by forcing NULL termination:

mydata.data[DATA_SIZE-1] = 0;

In your revised code your payload size is too big. The way the EasyTransfer library works is it has a single byte for the size of the payload. Your total payload size is PAYLOAD_SIZE + 2 ints - that is 255 + 2 + 2 = 259 bytes.  Placed into a single byte that gets truncated to 3. That means you are actually transferring one and a half integers and nothing else.

You need to ensure that your entire struct never exceeds 255 bytes. So you can have a maximum size of data, once you have taken your two integers into account (assuming 16-bit integers on an 8-bit Arduino), of 251 bytes.


What are examples of large Arduino code bases and how are they organized? I'd like to find out:

how big can an Arduino project get, is there some limit?
are there examples of large open source code bases? I did some research but find only example projects with single .ino file. Are there projects with multiple files e.g. functions, constants in separate files say to avoid a 10K+ .ino file?

Big projects are likely not developed with Arduino IDE. Arduino IDE was make for designers/inventors, not for programmers.

  Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming.

Source

Programmers will use a fully-fledged IDE which has many features a programmer needs on a daily basis, such as:

handling multiple files efficiently
allowing to create libraries instead of just setup() and loop()
code completion (suggestions as you type)
debugging (inspection and changing of variables at runtime)
refactoring (modifying the structure of your code without changing the behavior)
integrated version control (like Git / Github)

Such an IDE could be Eclipse with an Arduino Plugin or Atmel Studio and perhaps Visual Studio.

So, what do you need to look for? Don't look for .ino files. Instead, look for .h and .cpp code, just like other non-Arduino C++ code.

Some examples:

SPI: 297 lines
Wire: 453 lines
SoftwareSerial: 486 lines
I2S: 533 lines
USBHost: several files, up to 1600 lines


How to connect/call to the PSTN network using Arduino? For a few months I made an alarm for my house, it is very simple: it is based on magnetic sensors DC-1561 (for windows and exterior doors), a few PIR sensors for rooms, buttons, LEDs and (of course) an ArduinoNano v3. Something simple!

The question is that lately I do not spend much time in my house and I would like it when I'm away from home the alarm calls me (when is activated) to my cell phone using the public switched telephone network (PSTN) because I live in Cuba and it's the easiest way and cheaper (the GSM modems/modules are very expensive for me). I do not want to leave any message or sound record, just call me and receive the call on my cell phone, using the RJ-11 connector (in my country only 2 pins are used) to connect it with the Arduino/some_IC.

I have been investigating since yesterday and have found quite a bit of information. The most recommended/successful that I found (remember that I want to continue using the system that I already have, I just want to add to the Arduino the ability to use the mark through the PSTN) is to use an IC (HT9200B) that is a generator of DTMF codes (as see in the figure) with serial AND parallel connection, aparently, compatible with the electronic logic of the Arduino (5V).

But of all the information that I found is to connect to this IC (HT9200B) a speaker and reproduce the DTMF codes. This is not what I want, what I want is to connect directly to the phone line and be able to "call" from it.

Anyone have any ideas, links, projects in progress, or anything that can help me?

As already written in the comments, you may use any RS232 modem you can find. They use the so-called AT commands, which is a very common way to exchange commands with this kind of peripheral. You can check on wikipedia or on google to get more information on it.

The main problem is that this kind of modems are a bit hard to find (or at least, they are a bit harder to find and a bit too expensive for my liking). That's why, for a project of mine, I wanted to switch to a cheaper alternative. Looking on the internet, a lot of people stated that it was much better to have an already approved instrument rather than designing your own. For this reason, I bought a mini-phone like this one:

You just have to open it, wire the keys (or rather, the rows and columns of the keypad) to the arduino and let it do the magic.

This solution is cheaper (I spent 4€ for this, but if you have an old phone it becomes free) than getting a RS232 modem, but needs more work on your side.


Which board has the highest max current via 3.3v pin? Is there any arduino board which can deliver 600-800ma via 3.3v pin? Maybe the Arduino due or the nano 33 ble?

Your USB will output only 500mA or max to max 1A in some cases. Even if your board is rated for higher output you will be restricted by your source. First step is to increase your source. Secondly check which 3.3V regulator is present on which board and check the datasheet of the regulator to get information about it.
Either ways you can externally add a high current 3.3V regulator and connect it to your 3.3V pin on the arduino. As voltages are equal no current will flow between them.
But remember your source needs to output the higher current first


Digital output from one nano to digital input of another. Can I connect the digital out of one arduino to a digital input of another? To detect a high/low state...
One powered in one room on USB. The other in another room separate psu (connecting the grounds).
I know I can use tx/rx serial. But if the other way would work, less programming and 1 wire less..

Yes, you can. As you noted, you do need to connect the grounds of both Arduinos.

For some extra protection you could put a resistor between the output and the input. For example a 1kOhm. That way, if you accidentally set both pins as outputs, or plug the wire in the incorrect pin, you won’t get a dead-short.


Undefined reference to stdlib (strtof) while compiling I'm trying to run the AzureIoTProtocol_MQTT/esp8266 example, but I get linker errors:

  Archiving built core (caching) in:
  /var/folders/fj/y3vtrz597kv4885q1b_5qypr0000gn/T/arduino_cache_934614/core/core_esp8266_esp8266_d1_mini_CpuFrequency_80,UploadSpeed_921600,FlashSize_4M3M_e1e103f2055a19e071ac9522162e1787.a
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function sscanfd':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  sscanfllu':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
  undefined reference tostrtoull'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o:(.text.CreateAgentDataType_From_String+0xac):
  undefined reference to strtof'
  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function
  CreateAgentDataType_From_String':
  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:3571:
  undefined reference to `strtof' collect2: error: ld returned 1 exit
  status

The issue can be broken down to the call to strtof function call. I get the same error with only this very simple code snippet:

#include <stdlib.h>

void setup() {
  char szOrbits[] = "686.97";
  float f;
  f = strtof (szOrbits, NULL);
}

void loop() {
}

Tested environment: Mac OS X 10.13.2 with Arduino 1.8.3 AND Windows 10 with Arduino 1.8.5.

Its because the "strtof" function resides in "stdlib.h",
"Stdio.h" deals with i/o tasks.

Since you din't include you get that undefined reference error.
Correct that and compile again. Hopefully the error shall be resolved, else reply in the comments.

  Update1:

  After digging around standard gcc stdlib definitions and avr-gcc definitions found out that the above solution works for a gcc and not avr-gcc especially the 8-bit ones which the arduino IDE compiles for uno and the works as expected for 32bit processors like of Due.

  Cite:

  https://www.arduino.cc/reference/en/language/variables/data-types/double/
  https://www.arduino.cc/reference/en/language/variables/data-types/float/

Reason:

The size of the double and float is the same, ie: 4 bytes
and even if you use double its actually the float itself and wont gain any precision advantage.

Solution:

Since the size of the double and the float is same there is not point in having two function definition doing the same job.
so

Use "strtod"  instead of "strtof" or
Define a macro #define strtof(A, B) strtod(A, B) in the begning of your sketch so that the "strtod" handles the functioning of the "strtof".


Arduino Bluetooth connection with Android I am wondering why my Arduino program won't start its sketch to connect a bluesmirf to an android device and send data to the android whenever I use an external power supply. The sketch starts whenever i open the serial monitor, but using the power supply, it wont work.

You'll probably find that you are not supplying enough power to operate the Arduino and the components attached to the Arduino. Your current (Amps) draw is most likely higher than your external power supply can output.

I had this problem when using a 9v battery to power an Arduino with an XBee chip and some LEDs attached. The 9v would be able to power the kit for a while but would then not output enough current to power the Arduino. In the end I had to scrap a few LEDs.

You need to find out how much current your Arduino and its components are using and use a suitable power supply that can output enough current to power your Arduino.

Also remember when you send and receive a packet out of a Bluetooth radio - more current is required than when the Bluetooth radio is idle.


UART connection between Arduino Nano and NodeMCU I'm trying to create an UART connection between a Nano and an NodeMCU, running MicroPython.

Code for trying is meaningless - Arduino says "HI", and ESP8266 should receive and print msg value.

Connections :

Nano Rx --> ESP Tx

Nano Tx --> ESP Rx

Nano USB -- > Mac running repl

ESP USB --> Linux running Arduino IDE

BUT- when I physically connect as described the ESP BOARD freezes, in a way I can't even connect it using repl. Only after disconnecting wires (not only powering off the Nano), ESP unfreezes.

Appreciate any help.

You can't connect the same Serial to a computer over USB and to a Nano at the same time. Not only because the Nano is on 5 V which disturbs the 3.3 V side of the USB converter.

Disconnect the NodeMCU from computer, try to power it from Nano's 3.3 V pin (not for WiFI) and don't forget to connect ground between the MCUs.

Nano has one Serial, which is connected over USB to computer too. So there too you can't use the USB and RX TX pins at the same time. You could use SoftwareSerial to connect to NodeMCU.

The Nano TX to esp8266 RX should have logic level conversion to not to send 5V to esp8266 3.3V pin.


Print out times tables from 1 to 10 with array I would like to Serial.print(); the multiplication tables, 1 - 10. This is my work so far. Is there an easier way to do this with array? Thanks

// "MultiTable"

//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

//Define variable
int prod;

void setup() {
  // Open serial connection at 9600Bd
  Serial.begin(9600);
}

void loop() {
  //Print the times table for 1

  for(int i = 0; i <=9; i=i+1) {
   prod = i*1+1;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();

//Print the times table for 2

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*2+2;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();

//Print the times table for 3

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*3+3;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();
}

//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

This is not needed, you can use a for lop from 1 to 10.

The void loop will look like this (not checked, no IDE nearby):

void loop()
{
  for (int multiplier = 1; multiplier <= 3; multiplier++)
  {
      for(int i = 0; i <= 9; i++)
      {
         prod = i * multiplier + multiplier;
         // or: prod = (i + 1) * multiplier;
         Serial.print(prod);
         Serial.print(",  ");
      }

      Serial.println();
      Serial.println();
      delay(3000);
  }
}

Some remarks:

To go to the main for loop (with multiplier):

Identify the similar parts
Check the differences within each similar part (only the multiplier value, 1, 2 or 3)
Make this a for loop and instead of 1, 2, 3 use the multiplier variable
Instead if i = i + 1 you can use i++. It means exactly the same.
For clearity I put the Serial.println() together. You also can use Serial.print('\r\n\r\n') or Serial.println('\r\n') to achieve the same


Using 2D servo array in my class I need to use a servo library in my class.
I read this question - Use object of other class within class and it works fine for my LCD application, but now I need to use a 2D servo array in my class. I made one approach, it worked, but I think it is bad programming approach, what is right way to solve my problem?

My main file

#include <SoftwareServo.h>
SoftwareServo servo[5][5];
Servolib Servoarray;

void setup(){
  blah blah blah

My cpp file

#include "Vending.h"
#include "Arduino.h"
#include <SoftwareServo.h>

Servolib::TurnSevo(){
  for(int row=0;row<5;row++){
    for(int collum=0;collum<5;collum++){
      servo[row][collum].attach(Object[row][collum]);
      servo[row][collum].write(0);
    }
  }
}

my .h file

#ifndef Vending_h
#define Vending_h
#include "Arduino.h"
#include <SoftwareServo.h>

class Servolib:SoftwareServo{
public:
  void TurnServo();

private:
  SoftwareServo servo[5][5];
  int Object[5][5]={
    {42,21,20,19,18},
    {37,41,36,38,35},
    {31,33,30,34,39},
    {67,28,66,29,65},
    {56,63,55,64,54}
  };
};
#endif

So this code worked, but please give me better solution.

You can indeed use pointers, but passing multi-dimensional arrays is a bit of a pain in C(++).

There's a pretty good explanation here.


Arduino LDR sensor stained I bought a light sensor (LDR), but he got stained, what it means? It is used? Or is residuum of time?

I must give back? I have to clean up or something?

I bought as new, so I tested one of the LEDs will not turn on.

I bought the (Mercado Livre in BRAZIL).

The product is:
http://www.gbkrobotics.com.br/exemplo-produto/p7-sensor-de-luz-com-leds.pdf

I pay R$8 BRL (equivalent aprox. $2 dollars) but, i just wanted to know if he had something I could do, because only shipping was R$ 13 BRL ($4 dollars)

I'm starting with Arduino, thx

I've read you post a couple of times and I get the impression you would like this board to work, so here are some quick check to try and find the fault.

You need a bread board
An arduino
A 200-300 ohm resistor.
Some wires. About 6 hands :)

Connect the board ground to the breadboard.  Then connect the to the resistor.  Then connect that to the power supply ground.

Take the positive off the power supply and touch it to the LED1 pin and check LED1 lights up.  Repeat with 2 and 3.

Switch every thing off

Connect the Positive to the Vcc connection of the board.
Connect a wire between Arduino A0 and "Sinal Analog"

Load this sketch

   void setup() {
       Serial.begin(9600);
    }
   void loop() {
       Serial.println(analogRead(A0));
       delay(250);
   }

When you cover the LDR it should read a lower number when you shine a light on it should read a higher number.

Turn everything off again, and if you have a multi meter test the resistance of the resistor on the board it should be 300 ohms, but I can't remember which way to read the bands and it might be 10K ohms, which would be a problem.

If anything doesn't work then they can all be fixed for a few cents and you don't need to worry about the discolouration.

Hope that helps you.


OV 7670 + FIFO (AL422B) with arduino I just brought the camera OV7670 with fifo but I am unable to get the wiring of board with arduino and also I do not find any arduino library for OV7670 with fifo.

It will great if you can help to find some link which can help me.

Thanks,
Somnath

Here is a link. Use google to find more. It is not difficult.


SoftwareSerial library How do I rectify this error?
Clearly it says there is some error in the library, so how do I correct it?

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:1: error: expected unqualified-id before 'if'

As you haven't shown the code that produces the error when it's compiled, I can't say for sure what the problem is.  However, here are links to three instances of the same error:

• error: expected unqualified-id before 'if' on stackoverflow

• Arduino: error: expected unqualified-id before 'if' (using ping sensor), also on stackoverflow

• error: expected unqualified-id before 'if' on arduino.cc.

In each case, the problem was due to executable code (as opposed to declarations) appearing outside of a function.  You may have put some executable statements outside of loop() or setup(), etc.


max wattage LED for esp32 Simple spec question I couldn't figure out, what is, practically speaking and ballpark, the maximum wattage of LED you can drive with an ESP32 (I guess about the same as an arduino?).
Conditions:

using a boost converter for higher voltage: Yes
using ESP32 pin as output and power: Yes
use mosfets/external power circuit: no
no other load is connected to the ESP32 board

My silly calculation:

GPIO allows for 12mA output (source)
cheap and small voltage boost elements go to about 9-12V

i.e. (12 milliamperes) * 12 volts = max 0.144 watts.
Is that about right (orders of magnitude)?

No. You're way off.
If the output can provide 12mA at 3.3V that equates to (P=VI) 39.6mW.  Boosting the voltages does not increase the power. Assuming a 100% efficient boost circuit (which does not exist) you would just be boosting to 12V at 39.6mW - which means (I=P/V) 3.3mA.
You can't magic more power out of thin air - if you could we'd all have "free energy" devices powering everything. Instead we have power supplies or batteries.
And that is what you will need. A source for that extra power to come from.


Capture output from external device using Arduino Uno I was unable to find this question anywhere but I want to use my Arduino Uno to capture the output of a Code 39 signal coming out of a separate device. Currently, my setup is similar to this:

I have a biometric hand reader that outputs a Code 39 signal along D1 while D0 stays at a constant 0 which can be seen here:

Ultimately, I want to use the Arduino Uno to take the input from the data line and convert the Code 39 signal to ASCII. The process should functions like this:

User enters their code into the hand reader and hand reader measures their hand
Reader outputs Code 39 signal to Arduino and software on Arduino converts barcode format to ASCII.

Note: I believe the Code 39 signal will represent something similar to this *12345*. The user ID code will always be five digits. * represent the start and stop characters for Code 39 barcode format

Arduino sends ASCII code to computer which checks remote database to ensure user is valid

I have my correct pins set as follows:

#include <SoftwareSerial.h>
#define D1 3
#define D0 2

void setup() {
    pinMode(D1, INPUT);
    pinMode(D0, INPUT);
}

Is it possible to either print out the binary representation of the signal via the Serial console or write to a file that I can view later on? My idea is to use the loop function to listen for the signals via digitalRead()

void loop() {
    digitalRead(D1);
    digitalRead(D0);
}

The last part is the thing I'm having an issue with since I can't seem to get the information printed to the serial console or written to a file. I tried this but it didn't work:

void loop() {
    foo();
}

void foo() {
    digitalRead(D1) == HIGH ? Serial.print("0") : Serial.print("1");
    Serial.println("");
    digitalRead(D0) == HIGH ? Serial.print("0") : Serial.print("1");
}

Any ideas on how to make this happen or is it impossible? I want to see the output of device so I can verify it's outputting what I think it is.

Lastly, I am using Visual Studio with the Visual Micro plugin so I can attempt to debug my code. I also have a OS X machine that has the Arduino IDE installed on it if I need a Mac for anything.

Addendum: I don't have ready access to an oscilloscope. However, I have tested this device on an oscilloscope and I did have output that seemed all wrong. I want to see what the arduino says it is to verify things before I continue with this project.

First, let's find, what's wrong with your method. You try to poll the signal pins continously and write them out to serial. Default serial rate is 9600. Which means, that you can transmit approx. 900 characters per second. Looking at your oscillogram we can tell, that the signal you want to analyse has a base clock of roughly 2.5 kHz. Which means you definitely won't be able to sample every change of level with your method.

You can in fact use the loop() function to listen for changes, i.e. poll the signal, when you increase your serial baud rate. But I suggest using interrupts.

My suggestion is a three step process.

get the signal thoroughly recorded with all relevant information about the signal. This includes transmission to your PC via serial interface.
Analyse the signal offline. i.e. after having it received on your PC
Adapt your arduino code to decode it further before transmitting it to your PC

let's get to part 1):
read Arduino documentation on interrupts
the interrupt allows you to prevent interference of your two tasks (reading the inputs and writing to serial).
What is the interesting information? I think it's the waveform (i.e. the signal in best resolution you can deliver). You can sample your waveform at a high rate, but the resulting data volume will overwhelm your serial output. Fortunately your signal has some obvious characteristics. Which are:

obeys some timing (i.e. a clock)
has a limited transmission length (protocol frame)
has a limited transmission rate (as can be seen from oscillograph)

The best way to keep as much of the signal information by reducing the amount of serial transmission is to record the time of every level change.

Updates: buffer used, buffered output after receiving timeout

#define RECVTIMEOUT 2000 // we think, more than 2000 usec is end of transmission
#define MAXEVENTS 100

uint8_t inpin=2;
volatile unsigned long timestart=0;
uint8_t transmitLevel=LOW;

volatile uint8_t state=0; // little state machine: 0=nothing happened yet, 1=receiving data, 2=receiving timeout
volatile uint16_t tstamps[MAXEVENTS]; // we store timestamps of received symbols here
volatile uint16_t levels[MAXEVENTS]; // we store levels of received symbols here
volatile uint8_t index=0; // we save index of data here.
uint8_t count=0; // counter for later use.

volatile bool conflict=false; // will be set, if transmission conflicts with receive function.

void pinchange() // the ISR (interrupt service routine)
{
    switch(state)
    {
    case 0:
       timestart=micros();
       tstamps[index]=0;
       levels[index]=digitalRead(inpin);
       state=1;
       ++index;
    break;
    case 1:
       tstamps[index]=micros()-timestart;
       levels[index]=digitalRead(inpin);
       ++index;
    break;
    case 2:
       conflict=true;
    }
}

void setup()
{
    Serial.begin(115200); // high serial rate. don't forget to set the same in your IDE
    attachInterrupt(0, &pinchange, CHANGE); // the controller needs to know, where your ISR is.
}

void loop()
{
    switch(state)
    {
    case 1:
       if (index > 20)
       {
          if (micros()-timestart > RECVTIMEOUT)
          {
             state=2;
          }
       }
       if (index >= MAXEVENTS)
       {
          state=2;
       }

    break;
    case 2:
       for (count=0; count<index; ++count)
       {
         Serial.print(tstamps[count]);
         Serial.print(";");
         Serial.println(levels[count]);
       }
       if (conflict)
       {
         Serial.println("too less time to send data");
       }
       index=0;
       conflict=0;
       state=0;
    }
 }

This should output a fine csv with all your signal edges in microseconds, which you can paste directly to your favourite spreadsheet application. This is only for one signal. For analysing both, you have to enhance it accordingly.

Update 1

part 2)

from the gained data of our previous code version (snippet for brevity)

time signal timedifference
2614592 0   468
2615056 1   464
2615524 0   468
2616496 0   972
2616960 1   464
2617956 0   996
2618960 1   1004
2620424 1   1464
2621352 1   928
2622324 1   972
2623320 0   996

we can see two things.

The code in my first version of the answer didn't work properly. Every 1 should be followed by a 0 in column 2 and vice versa. This is apparently not true, which leads us to the conlusion, that we missed some events.
time differences seem to be multiples of roughly 470 μs. We can consider this as the length of a symbol.

So what's wrong with the code? I used noInterrupts() to stop Interrupts for copying the data. I hoped, there won't be level changes in this short period of time, but apparently this was not true. How to fix it? We better find another way to register the events and transfer them.
I recommend sticking to the interrupt technique, but changing the way we store the events and reading it out. Let's use a buffer big enough for all events of a transmission. After a transmission we can send all data without hassle via serial to the PC.

What can we expect? 0s and 1s should be transmitted alternating, with reasonable timings. If we can prove this, we can change the main loop again for decoding code 39.

part 3)

write code which stores a word of code 39 in a buffer
another code which decodes that word into a byte when the buffer is full
transmit that byte via serial

(many improvements possible).


Interfacing Arduino Leonardo with PCA8574AN I'm trying to interface my Leonardo with a "Mindsensors Magic Wand" - 8 LEDs connected to a PCA8574AN chip.
On the manufacturer's page, they say it's compatible with Arduino, however no instructions or code are given.
http://www.mindsensors.com/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=120

I've connected the SDA, SCL, 5v, and GND connectors on the arduino to the device, but have had no luck in communicating with it. None of the LEDs light up regardless of input.

I can verify that power is being supplied.
The i2c address of the device is 0x70.
Code is below.

#include "Wire.h"
#define TWBR=400000L
void setup() {
  // put your setup code here, to run once:
 Wire.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
  Wire.beginTransmission(0x70);
  Wire.write(32);
  Wire.endTransmission();
}

tl;dr: It seems like you need to send a null bit (0) to terminate the communication with this board.

In the downloads section, I found a .nxc file, which I assume is a NXT code file.

In the main loop, they configure the I2C port and a "touch sensor" (I believe this is to figure out how to synchronize the text with the motor). In that, there is a main loop in which they call DispLetter.

This is the DispLetter function:

void DispLetter (const byte & letter[])
{
  int nbytes;
  // Wait for the end of previously sent data
  while(I2CStatus(I2Cport, nbytes)==STAT_COMM_PENDING);
  // Write buffer to send to PCF8574
  byte WriteBuf[];
  ArrayBuild(WriteBuf, I2CAddr8574, letter);
  for(int i=1; i<ArrayLen(WriteBuf); i++)
  {
     WriteBuf[i] ^= 0xff;
  }
  I2CWrite(I2Cport, 0,  WriteBuf);
}

Let's read this code! First of all, it seems to make sure that the I2C port is connected, which we don't really have to worry about in our case since that's platform-specific.

After that, they create an array called WriteBuf[] that will store the data to be sent to the controller. Then we come across a function called ArrayBuild. Looking that up, it combines I2CAddr8574 and letter and places it into the WriteBuf array. (Click here for documentation for that function.) Please note that the I2CAddr8574 is just a byte containing 0x70 (the address of the chip), so we will not have to do this step since the Arduino handles the address. So, you will just have to send the letter array to the controller, ignoring the WriteBuf and ArrayBuild!

Let's figure out how letter is passed. In the main loop, they had this code:

DispLetter(L_);
DispLetter(E_);
DispLetter(G_);
DispLetter(O_);

That must display "LEGO." Let's figure out what L_ is defined as. At the beginning of the document, they have this defined:

// Display patterns
// Each byte represents a column of dots
// Bit set to 1 means lit LED.
// Least significant bit is at top of column.
// Last byte must be all 0
// Maximum number of bytes par pattern: 15

byte L_[] = {0xff, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0};
byte E_[] = {0xff, 0x89, 0x89, 0x89, 0x89, 0x81, 0x81, 0};
byte G_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x91, 0x90, 0x72, 0};
byte O_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

byte La_[] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xff, 0};
byte Ea_[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0};
byte Ga_[] = {0x72, 0x90, 0x91, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};
byte Oa_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

byte N_[] = {0xff, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xff, 0};
byte X_[] = {0x80, 0x41, 0x22, 0x14, 0x08, 0x14, 0x22, 0x41, 0x80, 0};
byte T_[] = {0x01, 0x01, 0x01, 0x01, 0xff, 0x01, 0x01, 0x01, 0x01, 0};

As you can see, they listed out how the dots are configured. There's a max of 15 bytes (I assume including the null bit).

There's one more piece of code that we haven't talked about:

for(int i=1; i<ArrayLen(WriteBuf); i++)
{
   WriteBuf[i] ^= 0xff;
}

So it goes through each bit, and does something to it. That is the shorthand for this:

WriteBuf[i] = WriteBuf[i] ^ 0xff;

No, that is not an exponent. That is an exclusive OR, a bitwise operator. A bitwise operator is basically where it "overlays" the two binary sequences and it does a special computation on them. If the nth bit of each input number is 1 or the nth bit of each input number is 0, the nth output bit is 0. If the nth bit of one input number is 1 and the nth bit of the other input number is 0, then the nth bit of the output is 1.

Since 0xff = B11111111, it will essentially reverse the values of each bit. You can avoid this if you say that a bit set to 0 is on, instead of a bit set to 1 (like they do in the example code). A minor adjustment that just makes your life a bit easier :)

After that, you can write that array to the I2C bus and it should display the data!


Fail to convert time_T from past to tm struct Continuing a Question asked few days ago, answered by Edgar, a new question has rised:
My goal was using a past time_t value, and convert it into a struct tm variable in order to  use it, part as a Char to print a readable text and some for logic queries.
At start NTP is configured as:
void myIOT32::startNTP(const int gmtOffset_sec = 2 * 3600, const int daylightOffset_sec = 3600, const char *ntpServer = "pool.ntp.org")
{
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
}

and every-time I need to get epoch and or struct tm of current time I call this function
void myIOT32::getTime()
{
  int a = 0;
  while (a < 3)
  {
    if (getLocalTime(&timeinfo))
    {
      delay(100);
      time(&epoch_time);
    }
    a++;
  }

BUT, when using the following function I get not GMT (+3) reference as needed :
struct tm *myIOT32::convEpoch(time_t in_time)
{
  struct tm *convTime = gmtime(&in_time);
  //char time_char[40];
  //sprintf(time_char, "%04d-%02d-%02d %02d:%02d:%02d", convTime->tm_year + 1900, convTime->tm_mon + 1, convTime->tm_mday,
          convTime->tm_hour, convTime->tm_min, convTime->tm_sec);
  return convTime;
}

Meaning I get to correct epoch time, but strcut tm is 3 hrs earlier ( and no, I do not want to hard-code +3... )

replacing gmtime(&timeinfo) with localtime(&timeinfo) in myIOT32::convEpoch passes definition of time-zone as needed.
for more information in this cpluspls site


Receive socket when in loop arduino (Interupt a while loop with a socket) I'm currently working on an arduino project. Were the arduino is communicating with a NodeJS server via web sockets.

The socket connection is working fine and has no problems. But the problem I currently have is that I want to be able interupt an infinite while loop with a socket emit from the NodeJS server.

I found a page that had a solution for this problem but only with a button attached to the arduino.

Link to page (Interrupt with button)

This is the loop I want to be able to interrupt with a socket:

bool loopRunning = true;

void rainbow(int wait) {
while(loopRunning == true) {

      for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
        for(int i=0; i<strip.numPixels(); i++) {
          int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
          strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
        }
        strip.show();
        delay(wait);
      }
    }
}

I want to set loopRunning to false when I recieve a socket emit.

Anyone have any ides how I can implement this?

Page to the socket functionality that I use

There are two ways to handle events: interrupts (hardware triggered) and polling (software triggered). Interrupts are much more efficient but also more difficult to use. SocketIoClient uses polling.

The necessary part of polling is... polling. That is, many times per second, you (or your library) needs to check if anything interesting is happening.

With this library, you have to call SocketIoClient::loop() many times a second. That's why SocketIoClient::loop() exists. So it needs to be added to your outer for loop.

(If your delay(wait) takes too long, you may need to break it up into a series of several shorter ones, but I think you can get away with it in this case.)

Then all you need to do is use SocketIoClient::on() to perform an action when an event happens. There is an example in the documentation. You will need to make loopRunning into a global variable.


Does Arduino Uno R3 require cooling in a closure? I was looking at getting an enclosure to house my Arduino Uno R3, but I'm not sure if I should also attach a fan.  Does anyone have experience with this?  It doesn't look like much heat is being generated, but with no ventilation except some slits in the enclosure, there won't be much air circulation without a fan.  My concern with adding a fan was the fact that I'd need to power it.

The only times I had an AVR run hot was when I applied reverse power to it. You'll be fine without a fan for the Arduino board itself, as long as you don't run power hungry peripherals from it.

Probably the only thing you really need to check (apart from absolute maximum ratings: 40mA max per IO pin and 200mA max for the whole microcontroller) is the on board voltage regulator (usually three pin device with a heat sink soldered down to the PCB) if you power it from a voltage > 7V or so.


Arduino offline commands I wanted to know if there is a way for my arduino to keep the last command I sent to it before I disconnected it from my computer. Thanks.

Arduino always store the last sketch you have uploaded. Even if you disconnect your board and then replug it then it follow the same commands that you gave earlier.


Regarding the output voltage and current in arduino This is basically an off-shoot from https://arduino.stackexchange.com/questions/20569/unexpected-output-pin-behavior-was-relay-on-off-doesnt-loop. It's the same schematics and so on, however, I'm now wondering what the output voltage and current is.

I've a 9V battery and the MOSFET transistor from the arduino starterpack (doesn't say the specs) connected to the 5V pin on the board. I need the following output current/voltage for it to activate a solenoid:

6V: 160 mA
7V: 190 mA
8V: 220 mA
9V 240 mA
10V :270 mA
11V :300 mA
12V :320 mA

and I'm just not sure how to calculate it since I'm not sure about the output from the transistor and all the way to the solenoid.

The solenoid: http://www.electrokit.com/en/plastic-water-solenoid-valve-1-2-12v.51108

You don't need to "calculate" anything with a MOSFET.  You will be using it in the saturation zone. That means it is fully turned on and will allow through the current you need.

However, the gate of a MOSFET looks, to all intents and purposes, like a small capacitor. That means there will be a certain amount of inrush current to the gate when you turn it on. To limit that inrush current you need a small resistor (say 100-220Ω) on the gate.

When using a BJT, though, you need to ensure that you allow enough current through the base to allow enough current through the collector.  Divide the current you need through the collector by the Hfe (typically 100 for a small signal transistor) and that is the minimum current you need to allow through the base. Subtract a silicon junction voltage (0.6V) from the voltage of the IO pin (5V). Divide it by your base current calculated above, and that is the maximum resistor you can use on the base.

And also your transistor symbol in your schematic is backwards.


How to detect if running Arduino or bare Atmega328p? I'm building something that will mostly run on bare ATmega328p at 8 MHz (as described eg. here), but sometimes I need to run the same code on an Arduino.

I need to initialize the DHT library depending on the clock frequency. For simplicity, I'd rather detect the running environment runtime, in the program itself.

So, is there a straightforward way to detect the clock speed (from fuses?) or some other difference between a stock UNO board and a bare ATmega328p using the internal 8 MHz clock?

Bare vs Stock is nearly impossible to detect at compile time. Where it depends on what you think you are trying to determine versus detect.

The best I can think of is creating a different Board definition; one for your bare and the other being the stock (i.g. UNO). Where now in IDE 1.5 see github.com/arduino/Arduino/wiki/… the parameter uno.build.board=AVR_UNO, which provides is used to set a compile-time variable ARDUINO_{build.board} to allow use of conditional code between #ifdefs. So you can create bare board definition with e.g. bare.build.board=MY_BARE and then have some #ifdef's for ARDUINO_MY_BARE

Otherwise wrap some #ifdef's around F_CPU as @sechleen points out. This is viable and done often in the core libraries.