Tv remote connection to an Arduino I have a tv remote that I want to connect to an Arduino so that I can send a series of commands to the TV using the remote.  I would like to open the remote and solder transistors or a Transistor Array in place of the buttons.  I have never done this before, so what do I need to be aware of?  I think that I will need to power the remote using the Arduino's power supply, but I am a bit foggy on the details.

If you're just running lines to the buttons, you won't need to power the remote from the arduino.  You could just let it keep the internal batteries.  But it would be possible to wire it up for power as well.

As a learning project, you could just take it apart and see if you can access the button contacts.  See if the contacts are split.  If so, shorting one side to the other should count as a button press.  But the details have nothing to do with an arduino.  They would depend on your specific remote and how it's constructed.

If your purpose is really to control the TV (rather than learning about the remote and fiddling with it), it will be much easier (and probably cheaper) to blast the IR without involving the remote at all.  A single IR transmitter and a library would work in most cases.  As an example: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html

P.S.  By coincidence, Adafruit just posted an updated guide to IR library use on Arduino.  https://learn.adafruit.com/using-an-infrared-library/overview


Why Ethernet webclient fails to initiate? I use the Ethernet shield with an Uno and create a web client. If I put a delay like one second for initialization it works fine. However if I wait for it in a while loop (like waiting for the serial, and as mentioned in Arduino docs) it never gets out of the loop that means the client instance is null.

I found this method on Arduino website in an example code:

while(!client) { ; } // waiting to get ready

Here's the code; if I uncomment it will stay there. Also the same with providing the MAC argument only.

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
char server[] = "www.google.com";    // name address for Google (using DNS)

IPAddress ip(192, 168, 1, 213);

EthernetClient client;

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

  Ethernet.begin(mac, ip);
  delay(1000);
  //while(!client){ ; }
  Serial.println(Ethernet.localIP());
}

What you write is not a function but a variable. And the variable will not change its value (unless you have some interrupt and it is a global variable).

so you need to change 'client' to some function you want to call, probably 'client.xxx()' where xxx is the name of the function you want to call (possibly with parameters).


Have Arduino write data to a MySQL database? Would it be possible to have an Arduino write directly to a MySQL database?

I'm a web programmer, so I'm familiar with how to get records from a MySQL database. I have MAMP installed on my mac, so I have the ability to build an interface, directly in the web browser, that retrives the records from a MySQL database.

What I'm thinking is to connect the Arduino directly to my computer via USB, and write data from the sensors, or the pins, directly to my MySQL database.

I'm using two phototransistor to record whenever something blocks the light. Each sensor records individually a timestamp for when the blocking occur.

Is that possible?

It's possible if you forget about the Arduino directly writing to the database.

Simply put, the Arduino is restricted to a serial connection.  To directly communicate with MySQL you would need a network connection, and then implement the MySQL protocol - a huuuge amount of work.

The normal way is to have an adapter program running on the PC which receives data from the Arduino over the serial connection, then performs any insert, select, etc instructions on the MySQL for you.

There is a "MySQL Connector" available* (https://launchpad.net/mysql-arduino) but of course that requires you to have an active network connection of some form to your Arduino.  Remember that the Arduino (certainly the Uno) is very limited on memory and program space, so having the Arduino connect direct, and doing anything else, might be mutually exclusive.

*Nice find, @SomeHardwareGuy...


Maximum potentiometer resistance I want to hook up a potentiometer to my arduino (Leonardo) as a voltage divider with the middle pin to an analog pin. I want to use the highest resistance to save power. I looked on the datasheet and it said the maximum output impedance is 10kOhm (§24.7.1 on Atmega32u4 datasheet). I also found another question that said I should use a 10kOhm potentiometer. What doesn't make sense is if the knob was turned towards the middle so that there is 5k on both sides, it's not the maximum capable resistance. So should I use a 20kOhm potentiometer?

There is a lengthy discussion about this on the Arduino Forum. As I understand it, the input impedance is only important if you are sampling a rapidly varying signal, as it takes a finite time to charge the sample/hold capacitor. However your potentiometer would not vary rapidly (certainly not in the order of thousands of herz). Thus I don't think the potentiometer resistance will be particularly important, particularly if you are not changing the analog inputs (eg. from one channel to another). The continuous current through the 10k pot would be 0.5 mA.

If you are worried about power, then rather than connecting the +5V side directly to 5V, connect it to an output pin, which you can bring high when you want to take a measurement, and make low at other times. That reduces the power through the pot, since there won't be a voltage potential. You might allow a few microseconds for the reading to stabilize when you need to take one.

  So the lower the pot resistance, the faster response time? Also I will constantly always be taking a measurement

No, I don't think this is an issue. The "response time" is really the time taken to do the ADC calculation (nominally 104 µs if you don't fiddle with the registers).

See ADC conversion on the Arduino (analogRead). As mentioned on that page you can speed up the measurement by changing the ADC prescaler. However even with a prescaler of 128 you get 9615 conversions per second. I doubt you can turn the pot fast enough for this to be a meaningful issue.

Regardless of the response time, the issue here is accuracy. Will a lower pot value give more accurate results? Well, I doubt it. The ADC effectively copies the analog input into a 14 pF capacitor (the "sample and hold" capacitor) which it then tests against the reference voltage divided up in various ways.

The input impedance would be relevant if you were sampling a high-frequency input. On the page I linked I sampled a 4 kHz sine wave and got good results. You just won't be turning the pot that fast (4000 times a second).

  I'm still unsure with how potentiometer resistance affects the data ...

If you keep sampling the same ADC input (eg. A0) then I think the sample and hold capacitor can be charging in the background (while your code is doing other things).

But even if that were not the case, the datasheet says the sample and hold operation takes place 1.5 ADC cycles after the conversion starts. So at 16 MHz clock rate, and a prescaler of 128 for the ADC clock, this means we have:

128 * 62.5 ns * 1.5 = 12 µs

Now since the datasheet says the sample-and-hold capacitor is 14 pF, and the time taken to (almost fully) charge a capacitor is reckoned to be:

5 * R * C

Given R = 110k and C = 14e-12 (14 pF) then it will take:

5 * 110000 * 14e-12 = 7.7 µs

I quoted 110k because the datasheet mentions a resistance of 1 to 100k in series with the capacitor, plus the 10k impedance they recommend.

This means the capacitor will charge within the 12 µs it has available. Bump R up to 1e6 (1 megohm) and the calculation now gives:

5 * (100e3 + 1e6) * 14e-12 = 77 µs

This exceeds the 12 µs quoted for the sample-and-hold.

This is why, I suggest, that for fast-changing signals they recommend a lower input impedance.

However if I am correct that the sample-and-hold capacitor is normally connected to the ADC input, then that 77 µs can be spread over the time you deal with the calculation. Still, that is quite a few clock cycles. :)

My recommendation is to stick with 10k or so potentiometer (as recommended by the datasheet) and use my earlier suggestion of connecting the 5V side of the pot to an output pin instead of continually having it connected to the +5V signal. That way you only need to "power" the pot when you actually need to take a reading. However you can see that a 20k pot (or even 50k) will probably still be in an acceptable range for an accurate conversion.

For example, a 50k pot could charge the capacitor in:

5 * 150000 * 14e-12 = 10.5 µs

I would also be cautious about a 1 megohm pot because then slight variances in other things (eg. heat on the wire, nearby noise) could swamp the reading from it.

  Wait, sorry do I need to half my potentiometers' resistance if I'm using two analog inputs?

No, because the multiplexer chooses one input at a time (the others are effectively out of circuit).

However if you are choosing between two pots (to measure two) then the resistance becomes more relevant. As I showed, with a high value pot it takes longer to charge the capacitor, so if you read A0 and then immediately afterwards A1, you don't want a lengthy charging time for the capacitor, because that would give erroneous readings.


FastLED fade WS2812B Learning how to program with Arduino, but the learning curve is out of my league.

I have this

    #include <FastLED.h>
    #define NUM_LEDS 4
    #define DATA_PIN 3

        CRGB leds[NUM_LEDS];

           void setup() {
       FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
   }

       void loop() {
      // Turn the first led red for 1 second
      leds[0] = CRGB::Green;
      leds[1] = CRGB::Red;
      leds[2] = CRGB::Green;
      leds[3] = CRGB::Red;
      FastLED.show( 99 );
      delay(1000);

      // Set the first led back to black for 1 second
      leds[0] = CRGB::Red;
      leds[1] = CRGB::Green;
      leds[2] = CRGB::Red;
      leds[3] = CRGB::Green;
      FastLED.show( 99 );
      delay(1000);
    }

So, I want them to fade from green to red.
led 1 is green, and led 2 is red
I should probably program this in a different way, but I don't know how.
Any ideas are welcome!

At the moment you have become used to working with pre-defined named colours, like CRGB::Red and CRGB::Green.  Those are just symbolic names for combinations of numeric values for red, green and blue.

So by using numeric values and varying them slightly over time you can create fade effects.  I am not personally familiar with that library or class, so I cannot tell you how to do it, but reading the documentation should show you how you can use variables to specify each of the colour components as a single colour.

As for how to fade from red to green - since they are two completely separate colours (they use separate colour channels in the LEDs) there are two main ways of doing it:

Start with red on full and green off. Slowly increase green to get yellow. Then slowly decrease red to get green.
Start with red on full and green off. Slowly increase green while slowly decrease red. At 50% they will cross over.


Is there a simple HTTP(S) library that doesn't rely on WiFi? I'm trying to implement a Mobile Network (only) for the ESP32 using Arduino IDE. So to be able to connect to website up/download files etc. I need to be able to handle various HTTP PUT/GET/POST requests. However, the available libraries seem to always rely on additional WiFi related libraries. I don't want to have to load those as well, as they are quire bloated and not needed for my use scenario.

What options do I have for minimalist HTTP request libraries that does not rely on WiFi or BT or ETH?

The TinyGSM library implements Arduino networking Client base class over GSM modem's AT commands. The library is available in Library Manager.


How to write a digitalWrite array for MCP23017 expander chip? I'm using multiple expander chips for my project and I was wondering if there is a way to shorten the loop code by using array? So that I don't have a super long code.

void setup() {
  mcp.begin(0);
  mcp1.begin(1);
  mcp.pinMode(0, OUTPUT);
  mcp.pinMode(1, OUTPUT);
  mcp.pinMode(2, OUTPUT);
  mcp.pinMode(3, OUTPUT);
  mcp.pinMode(4, OUTPUT);
  mcp.pinMode(5, OUTPUT);
  mcp.pinMode(6, OUTPUT)
  mcp.pinMode(7, OUTPUT);
  mcp1.pinMode(0, OUTPUT);
  mcp1.pinMode(1, OUTPUT);
  mcp1.pinMode(2, OUTPUT);
  mcp1.pinMode(3, OUTPUT);
  mcp1.pinMode(4, OUTPUT);
  mcp1.pinMode(5, OUTPUT);
  mcp1.pinMode(6, OUTPUT);
  mcp1.pinMode(7, OUTPUT);
}

void loop() {
  mcp.digitalWrite(0, LOW);
  mcp.digitalWrite(1, LOW);
  mcp.digitalWrite(2, LOW);
  mcp.digitalWrite(3, LOW);
  mcp.digitalWrite(4, LOW);
  mcp.digitalWrite(5, LOW);
  mcp.digitalWrite(6, LOW);
  mcp.digitalWrite(7, LOW);
  mcp1.digitalWrite(0, LOW);
  mcp1.digitalWrite(1, LOW);
  mcp1.digitalWrite(2, LOW);
  mcp1.digitalWrite(3, LOW);
  mcp1.digitalWrite(4, LOW);
  mcp1.digitalWrite(5, LOW);
  mcp1.digitalWrite(6, LOW);
  mcp1.digitalWrite(7, LOW);
}

Use a variable ( iterator) and count from 0 to 8 (excluding):

void setup()
{
    mcp.begin(0);
    mcp1.begin(1);

    for (uint8 pin = 0; pin  < 8; pin ++)
    {
        mcp .pinMode(pin, OUTPUT);
        mcp1.pinMode(pin, OUTPUT);
    }
}

void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
        mcp1.digitalWrite(pin, LOW);
    }
}

If the order in which the digital pins are written to LOW matters than split them like in your example, (however, I do not think that is the case).

void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
    }

    for (pin = 0; pin < 8; pin++)
    {
        mcp1.digitalWrite(pin, LOW);
    }
}

Note : for clarity I would call the mcp variables mcp1 and mcp2 instead of mcp resp mcp2, or an even more intuitive name if there is a clear function for both mcp's.

Using uint8 creates an unsigned byte instead of an int which saves also one byte of stack memory.


Arduino Timer 1 Library manipulate Timer value I'm using Timer1 library for generation of pulse.
But in my code, at some places i need to change the timer values.
Can anyone suggest the ways to do it.

In below code in place of 370000, I need to change the value after getting some inputs in conditional loops.
Ex. if (x==1) Timer value should be 370000 else 185000.

#include <TimerOne.h>

int count = 0;
int LED = 13;

void setup() {
 pinMode(LED, OUTPUT);
 Timer1.initialize(370000);
 Serial.begin(9600);
}

void loop() {
 Serial.print("Count Value: ");
 Serial.println(count++);
}

When you look into TimerOne.h, which is the header file for the TimerOne library, you can see at line 55 the method

void setPeriod(unsigned long microseconds)

which can be used to set the period of the timer at any time in your program. The method TimerOne.initialize() also calls this method to set the timer period.


Calculate absolute time based on cycles and RTC I'm developing a low power data logging device. It samples sensors at the frequency of 20Hz, and also has a real time clock for absolute time (the logged time need to be exact down to ms).

I think that querying time for every samples would be wasteful of energy. One solution is calculate time based on number of cycles, and after a fixed duration (10 minutes) query RTC to update the time.

Here is my attempt:

#define INTERVAL 12000 //10 minutes: 10*60*20 samples

int count = 0;
int checkPointMillis;
int checkPointRTC;

// timer interrupt at 20Hz
ISR() {
    int a = analogRead(A0);
    int time = millis() - checkPointMillis + checkPointRTC;

    // write data to a buffer

    if (count > INTERVAL) {
        count = 0;
        checkPointMillis = millis();
        checkPointRTC = getRTCTime();
    }
}

Is this a correct approach?

In general, the idea is sound.  But there are problems with some of the details and tuning.

The most important detail:  Use the correct data type for storing and computing with time variables (like time, checkPointMillis and checkPointRTC).  The correct data type is unsigned long (or, equivalently, unsigned long int or uint32_t).

A second detail:  Rather than storing your calibration correction in two variables which you always use as a difference (in effect, checkPointRTC-checkPointMillis) just compute and store the difference.  For example:

...
unsigned long clockCorrection;
...
unsigned long time = millis() - clockCorrection;
...
clockCorrection = getRTCTime() - checkPointMillis;

This will save a few bytes of RAM and a few cycles of computation.

A third detail:  If outside of the ISR you will need to access any of the values computed in the ISR, declared their variables volatile.  Example:

volatile unsigned long time;

Fourth: If getRTCTime() or any of your sensor-reading code use interrupts, you will need to move such code out of the “timer interrupt at 20Hz” section, into (for example) loop(), triggered by a volatile variable going true.  [That's the model under which the balance of this answer was conceived; I overlooked, at first, the “timer interrupt at 20Hz” label.]  Note that millis() itself does not use interrupts.  But if your 20-Hz ISR runs longer than a millisecond, the millis() total will drop one millisecond per millisecond of additional ISR time.

By tuning, I refer to the number of measurement intervals to wait between recomputing the clock correction.  Under reasonable assumptions, the number of compute cycles is so closely the same with a one second interval versus a ten minute interval, that one probably should use only a second (or at the outside, a minute) interval between clock correction computes.

For example, suppose the total number of cycles awake per second is given by the following equation:

  a = 20*s + 1000*t + k * r

where s is the number of cycles used per sensor-set reading and recording; t  is the number of cycles used per clock interrupt; k is the number of clock correction computes per second; and r is the number of cycles used per clock correction compute.

For example, if s is 2000, t is 100, and r is 200, the equation becomes

  a = 20*2000 + 1000*100 + k * 200 = 140000 + k * 200

Now consider three cases: k equal to 20, or 1, or 1/600, corresponding to a clock correction compute 20 times per second, or once a second, or every 10 minutes:

   k           a
  20        144000
   1        144200
1/600       144000.3

As you can see, under the assumptions s is 2000, t is 100, and r is 200, there is no compelling reason to prefer 1/600 corrections per second to one  correction per second.

If your RTC can be read reliably and quickly, reading it either every time (ie 20 per second) or every second has other advantages:  you compensate more quickly for MCU clock drift (ie, every second, rather than every 10 minutes) and strongly decrease the risk of out-of-order times.

For example, if your MCU clock drifts 2 seconds fast per 10 minutes, readings taken during the first two seconds of each new 10-minute interval would show smaller times than those taken during the last two seconds of the previous interval.  With secondly corrections, no such non-monotonic readings will occur.

Here is a slightly more correct analysis of the 2 seconds fast per 10 minutes case:  2 seconds error in 600 seconds is 3.33 milliseconds per second.  With sensor readings 50 milliseconds apart, and corrected clock readings not more than 3.33 milliseconds out of whack, non-monotonicity won't occur.  However, this does not meet the “logged time needs to be exact down to ms” criterion.  To meet that, drift of more than a half millisecond must be prevented.  That requires drift correction at least 6.67 times per second.  You could accomplish that by making a  clock correction compute at every third sensor cycle.

It should be clear from the example calculations of awake cycles that the major contributor to the count is ISR cycles, here taken as 100*1000, or 100000 cycles per second.  You could set up timer 1 to interrupt 20 times per second and turn timer 0 off (which would disable millis() and require a different time = ... formula).  If each timer 1 interrupt took 1000 cycles, that would contribute 20000 cycles instead of 100000 per second.

Edit 4: As I noted in a comment to Edgar Bonet's answer, one can change the TOP value used for timer interrupts, to control interrupt rate with better resolution than can be obtained by merely subtracting base values.

According to Gerben's comment, “getRTCTime only has 1sec resolution”.  As I haven't seen any code for your getRTCTime() I don't know if that is true or not; but if so, here is another approach for time-rate correction:

  • At some beginning point coincident with an RTC seconds-change, record millis() and an RTC reading, in eg millibase and RTCbase.
  • At some interval (eg, 10 seconds or a minute, in each case coincident with an RTC seconds-change) measure millis() and an RTC reading, in eg millinow and RTCnow.  Compute RTCdeltaK as the number of milliseconds from RTCbase to RTCnow.  Compute millidelta as millinow-millibase.
  • Whenever elapsed time in milliseconds is needed, compute elapsedms = ((millis()-millibase)*RTCdeltaK)/millidelta.

The above is an algorithm, and may need some adjustment before use as an implementation.  First, the elapsedms calculation can be arranged to avoid division, using a scaled multiplicative factor based on millidelta, RTCdeltaK, and some powers of 2.  Secondly, relatively constant clock drift is assumed.  If that assumption is incorrect, an average ratio with exponential decay could be used, instead of just a factor equivalent to RTCdeltaK/millidelta.


Arduino reads string from another Arduino only if the string is in a loop why? In my setup I have connected two arduino's Serially. An Arduino Mega is the on that is sending the string and a Arduino Uno is the one receiving it.

Arduino Mega : RX1(19),TX1(18) - Serial1
Arduino Uno : RX(10),TX(11)  - using SoftwareSerial
Gnd is connecetd on both boards

When I send a single string from the mega to Uno multiple times(In void loop)
I receive the string sent infinite number of times on the Uno which is to be expected:

Arduino Mega - Single string sent multiple no. of times

void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
}

Now I want to only send the string a single time, so I inserted an exit(0) or an infinite loop after the delay that is always true.

Arduino Mega - Single string sent only one time

void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
  while(true);
}

Arduino UNO - code is same for both cases

#include <SoftwareSerial.h>
SoftwareSerial s(10, 11);
void setup()
{
  delay(200);
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) ;  // wait for Arduino Serial Monitor
}
void loop()
{
  if(s.available()>0)
  {
     Serial.print("\nrec\n");
     delay(100);
     String b = s.readStringUntil('\n');
     delay(100);
     Serial.print(b);
     delay(40);
  }

}

Note : Arduino uno is receiving the string using : readStringUntil('\n')

But when I send the string only once I receive nothing on the Arduino Uno, can anyone help me figure out why this is happening

What I want to know is why the uno receives the string only when it's sent an infinite number of times and not when it is sent 1 time.

EDIT (July 8)

Still haven't got a solution that I'm looking for, if anyone needs any extra information to help me out please mention it to me.

EDIT (July 8-9)

Sorry it's my fault for writing Tx1 as 19  and Rx1 as 18 although I did not make the same mistake in the code.
When I pressed the reset button on the mega the string was received on the uno side.How did this happen?  Until now, after I uploaded the code in both the arduino's I opened the serial monitor of the port connected to Uno and I did not receive the string.

Why do I need to reset the mega in order to send the string , shouldn't it work when the serial monitor is opened?

Also I need the mega to send the string automatically without any forced/physical reset is that possible?

I'm asking this because sending a string is part of a larger code where values get updated as time goes by,and a reset will  reset all the values to their original state which I don't want happening.

exit(0) is not the command to use, it is used to completely stop the program, although I'm not sure what happens exactly for an Arduino sketch.

To stop a loop (and continue, normally a break statement is used. This works inside a while or for loop and the sketch continues after the while or for loop where the break statement is executed.

Note, you also can start at the beginning of the while or for loop with the continue statement.


RadioHead and DallasTemperature error The RadioHead library only runs on a very old core for the ATtiny85.
It sends data but I would like to send something useful. The problem is I cannot read any sensors using this core. And on any other core the RadioHead library fails.

RadioHead library
ATtiny core

An old post in the Arduino forum, probably the same issue.

I would like to know what is in the DallasTemperature that conflicts with RadioHead making the code to hang.

The problem appears when I add DallasTemperature sensors(&oneWire); to the code.

// RadioHead ASK
#include <RH_ASK.h>

// DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS PB0
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Sleep
#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Absolute reference PB to overcome inter-IDE issues
#define T_PIN PB1 // transmission
#define L_PIN PB3 // optional LED pin
#define BAUD 2000

// Baud rate, receiver, transmitter
RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

// the Tickle structure, what a name, ugh
struct tickle {
  uint16_t id;
  uint16_t value1;
  uint16_t value2;
};

// Watchdog
volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

// Sleep
void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// Setup for Watchdog
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

// With set_watchdog at 8 (4 sec.) we cycle from 0 to 14
// This timer is not precise
void minute_sleep(int ms) {
  for (int c = 0; c < ms; c++) {
    for (int i = 0; i < 15; i++) {
      system_sleep();
    }
  }
}

void setup() {
  // Debugging, if this takes less than a second, check fuses (core)
  if (!driver.init()){
    pinMode(L_PIN, OUTPUT);
    digitalWrite(L_PIN, HIGH);
    delay(500);
    digitalWrite(L_PIN, LOW);
    delay(500);
  }
  setup_watchdog(8);
  sensors.begin();
}

void loop()
{
  if (f_wdt==1) {
    f_wdt=0;
    struct tickle package; // make a Tickle package

    package.id = 38; // hard-coded device ID
    package.value1 = analogRead(PB0); // any positive int up to 2^16
    package.value2 = analogRead(PB2); // any positive int up to 2^16

    // sending data
    driver.send((uint8_t *)&package, sizeof(package));
    driver.waitPacketSent(); // wait for it ~Barney
    minute_sleep(10); // tested: 10 was 10:30, I like
  }
}

I have experienced many issues when using RadioHead library on ATTiny85 together with the Arduino IDE. Your issue is not the Dallas temp sensor.

The problem lies in that RadioHead uses timer 0 on the ATTiny and changes the prescaler on the timer to match the baudrate you have requested for your tranciever. The change of prescaler changes the way Arduino IDE functions like delay()works since those also use timer 0. I believe your Dallas library depends on delay() to synchronize the signals on the 1-bus so there you have a conflict between the two libraries.

I solved this by rewriting the RadioHead RHASK files to allow for ATTiny85 timer 1 to be used instead. Here's my code. Although I use TinyHead instead of RadioHead, the change will be the same as TinyHead is a RadioHead clone.

The only change I made to RH_ASK.h is the code to define whether to use TIMER1 or not.

// Flag to indicate whether to use timer1 in attiny85.
#define RH_ASK_ATTINY_USE_TIMER1

The below changes goes into RH_ASK.cpp

First change. Update pre-scaler code and add the pre-scalers used by timer 1:

// Put these prescaler structs in PROGMEM, not on the stack
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO) || (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
#if defined(RH_ASK_ARDUINO_USE_TIMER2)
// Timer 2 has different prescalers
PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 32, 64, 128, 256, 3333};
#else
  #if defined(RH_ASK_ATTINY_USE_TIMER1)
   PROGMEM static const uint16_t prescalers[] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16834, 3333};
  #else
   PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 64, 256, 1024, 3333};
  #endif
#endif

Second change. This code sets up the timer 1 and goes before the existing code for ATTINY timer0 in function RH_ASK::timerSetup(). please note the "... existing code" part. The existing code for setting up timer 0 goes between the #else and the #endif

#if defined(RH_ASK_ATTINY_USE_TIMER1)
#warning RH_ASK_ATTINY_USE_TIMER1 set.
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);
   if (!prescaler)
       return; // fault

   TCCR1 = 0; // Stop the timer
   TCNT1 = 0; // Zero the timer
   GTCCR = _BV(PSR1);  // Reset the prescaler

   // Number of ticks to count before firing interrupt
   OCR1A = uint8_t(nticks);

   TCCR1 = _BV(CTC1); // Turn on CTC mode / Output Compare pins disconnected

   // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
   TCCR1 |= prescaler; // set CS00, CS01, CS02 (other bits not needed)

   // Set mask to fire interrupt when OCIE1A bit is set in TMSK
  #ifdef TIMSK0
   // ATtiny84
   TIMSK1 |= _BV(OCIE1A);
  #else
   // ATtiny85
   TIMSK |= _BV(OCIE1A);
  #endif
#else
#warning RH_ASK_ATTINY_USE_TIMER1 not set.
   // use timer 0 (default)
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);

... existing code

   // ATtiny85
   TIMSK |= _BV(OCIE0A);
  #endif
#endif

Third change goes where the vectors are set up. Note the added #if defined for TIMER1 and the corresponding vector. Note also that the vector for timer0 is now called TIM0_COMPA_vect in later RadioHead/TinyHead but the names TIMx and TIMERx are interchangeable.

#if (RH_PLATFORM == RH_PLATFORM_ARDUINO)
#if defined(RH_PLATFORM_ATTINY)
 #if defined(RH_ASK_ATTINY_USE_TIMER1)
  #define RH_ASK_TIMER_VECTOR TIMER1_COMPA_vect
 #else
  #define RH_ASK_TIMER_VECTOR TIMER0_COMPA_vect
 #endif
#else // Assume Arduino Uno (328p or similar)

Mind you that I have had other issues using the DallasTempSensor library. I'm not sure whether the issue is a low quality crystal in my ATTiny or not, but I get garbage readings from my sensor. The same code works flawlessly on my Arduino Nano, so I'm currently investigating whether my ATTiny is too far off in its timings to work properly with that library. I'm also going to try the OneWire protocol to see whether that one works better. However, the above code change resolved my issues with Arduino IDE and RadioHead/TinyHead.


NodeMCU Power supply I got a question about externally powering my NodeMCU V3. It has an onboard voltage regulator (3v3) which breaks out to 3 header pins. Now I want to power 3v3 from an external board. Can I supply 3v3 to all of those pins at the same time? (Basically connected in parallel).
Anyone has done this before or has this experience with NodeMCU V3?

I have supplied a link below:
https://www.theengineeringprojects.com/2018/10/introduction-to-nodemcu-v3.html

Thanks a lot!

Yes, you may connect all 3V pins together (red) and all GND pins together (black), like so:

In some cases, more wires will improve the circuit. E.g. when you build the Ben Eater 8-Bit CPU, you'll find that connecting power in a ring instead of a line will reduce voltage drop by about 50%.

When first reading your question, I got the impression that you wanted to solder the 3.3 V wires directly to the voltage regulator. Here's my original answer for that:

That's not a good idea: if you connect the same wire to all pins, your're creating a short, typically causing a malfunction if not worse. You may destroy your equipment (external board as well as the NodeMCU v3). Do NOT connect 3.3V to all pins of the voltage regulator.

A voltage regulator has 3 pins:

voltage in (for an unregulated voltage you can't exactly control; typically higher than the output voltage)
voltage out (for the stabilized resulting voltage you want to have)
ground

The only pin to connect the voltage to is the "voltage in" pin (VIN). And typically, a development board has a pin for that:

However, you'll find that the input voltage must be between 4.75V and 10V, so supplying 3.3V from an external board is not sufficient.

If you have regulated (stable) 3.3V already, you can connect that to a pin labelled 3V:

Also, you need to connect the grounds (GND) of both circuits together (GND of external board to GND of NodeMCU), otherwise the current will not find its way back.


How can I increase resolution for current sensor? I purchased a ACS711 Hall effect-based linear current sensor (http://www.pololu.com/product/2197) and when i read the input it's basically always the same. After doing some research I think it's because there is only a 10bit AD converter and since the current is only changing a little bit it's not enough to catch the change. For my situation I'm pulling around 40-90ma idle and when the motor turns on it jumps up so I want this sensor to see that but it only jumps up to about 120ma. Any tips on how to fix this? Maybe a different sensor? Can I use an amplifier to boost the analog signal?

In default configuration, the Arduino's ADC has a range of 0v-Vcc (5v or 3.3v depending on the model). If you are sure your input voltages will always be way lower than Vcc, spreading the ADC's resolution over that range is a waste of accuracy. What you need to do is to properly configure your analog reference voltage.

Basically, this is a way of telling your Arduino "instead of spreading your ADC's bits over a range of 0v to Vcc, just cram all that accuracy between 0v and [refVoltage]."

So:

Measure the highest analog output your sensor will give.
Setup a voltage divider to output a little more than that
Connect the voltage divider's output to the AREF pin
in setup(), declare analogReference(EXTERNAL);

And that's basically it. As noted, in this specific case you'd probably be better off buying another sensor altogether. However, you won't always have that luxury, and knowing how to set the analog voltage reference always comes in handy.


Standard Arduino kit button caps? Are there any caps available for these buttons, or am I better off using other, more stylish buttons if I want to make a presentable arduino-based gadget?

The circular hole drilled in their square-section moving part seems to suggest that something can be plugged there, but I can't seem to find caps anywhere.

Thanks for your attention.

You can use a different type of buttons on with your Arduino, there are some that keep the state or just push button.

The most used are the "arcade" style or the push button on a breadboard.

Just remember to have a pull up/down resistor and add some code to avoid debouncing when the button has been pressed.
https://www.arduino.cc/en/Tutorial/Debounce

If you want some more custom, you can use a normal push button and add small piece of wood/plastic/metal into the hole and having low friction you will be able to press the button with a nice look and feel.


Merging arduino code I have a project where we need to create a virtual cane for blind people and it will have 3 functions:

Pressure button when pressed will connect to an android phone through HC-06 Bluetooth modulo to an app that I developed and will
can to someone that I defined
Temperature sensor that is attached to a buzzer that will buzz if the
temperature is higher than 40 Degrees
Ultrasonic sensor attached to and vibration motor that will vibrate
if there is any object less than 70 cm from the person.

When I combine the code from the ultrasonic and the temperature sensor, everything works fine, when I add the bluetooth code, nothing works, anyone see the problem? Or could you show me the problem and solveit?

Code without Bluetooth:

int DHT11_PIN=8;
dht DHT;
int buzzer=6;
int trigPin=3;
int echoPin=2;
int motor=7;

void setup(){
  Serial.begin(115200);
  pinMode(DHT11_PIN,INPUT);
  pinMode(buzzer, OUTPUT);
  delay(5000);

  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motor, OUTPUT);
  delay(5000);
}

void loop(){
  Stemperature();
  Sultrassom();
}

// sensor de tempratura e Buzzer-------------------------------
void Stemperature(){
  digitalWrite(buzzer,LOW);
  DHT.read11(DHT11_PIN);
  float t=DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t>40){
    digitalWrite(buzzer,HIGH);
    {tone(6,100,20);
    delay(1);
    noTone(1);
    delay(1);
    }
    delay(1000);
    Serial.print("ON T=");
  }else{
    digitalWrite(buzzer,LOW);
    Serial.print("OF T=");
  }
}

//Sensor de Ultrassom e Motor vibração-----------------
void Sultrassom(){
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){ // se a distância for menor que 70 cm o motor vibra
    digitalWrite(motor,HIGH);// quando a distância for menor que 70 cm
    Serial.print("MOTOR ON=");
  }else{
    digitalWrite(motor,LOW);// quando a distância for maior que 70 cm
    Serial.print("MOTOR OFF=");
  }
  delay(5);
}

Bluetooth Code:

const int buttonPin = 4;     // the number of the pushbutton pin
boolean buttonState;         // variable for reading the pushbutton status

void setup(){
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  buttonState = LOW;
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if(buttonState == HIGH) {
    // send char 1 via Bluetooth:
    Serial.println("1");
    delay(20000);
    while (0);
  }
}

In the bluetooth loop you use:

delay(20000);
while (0);

This means you first wait 20 seconds, and while(0) does not do anything (unuseful instruction).

Actually, this results when the button is pressed, it starts the loop again, but you have to merge both codes into one.

I would add the sending of the serial command in the code above, remove the while and see what happens. If you need some delay for debouncing reaons for the button, implement a decent deboucing algorithm instead of the delay of 20000.

And why there are two }} at the end?


Sync issue with signals #include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "digitalWriteFast.h"

#define BUTTONPIN 2
#define FDCSPIN 6
#define CIPIN 5
#define SPEAKERPIN 4

float RPM=1000.0;
int PWus=1.5*1000.0;
int FDCSoffset=(1000.0/RPM/60.0/4.0) - (PWus/1000.0);
int CiCnt;
int totalCnt;
int CIState=B01100000;
bool Buttonstate=0;
LiquidCrystal_I2C lcd(0x27, 20, 4);

void setup()
{
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  lcd.clear();
  lcd.print("READY TO TEST"); // Waiting for button press
  pinMode(BUTTONPIN, INPUT);// Setting button as Input
  pinMode(FDCSPIN, OUTPUT); // Fuel Delivery Control Signal
  pinMode(CIPIN, OUTPUT); // Cylinder Identification
  digitalWriteFast(FDCSPIN, LOW);
  digitalWriteFast(CIPIN, LOW);
}

void loop()
{
 Buttonstate=digitalReadFast(BUTTONPIN);
 if(Buttonstate==1)
 {
  delay(5);
  if(Buttonstate==1)
  {
    runInjectorTest();
  }
 }
}
void runInjectorTest()
{
  lcd.print("Test Run");
  playtesttone();

    for(totalCnt=0;totalCnt<8000;totalCnt++)
    {

      PORTD=CIState;
      delayMicroseconds(FDCSoffset);
      PORTD=PORTD^B01000000;
      delayMicroseconds(PWus);
      if(totalCnt%4==0)
      {
        CIState=CIState^B00100000;
      }
    }
  totalCnt=0;
  playfinishtone();
}
void playtesttone()
{
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
}
void playfinishtone()
{

  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 2000, 500);
  delay(700);
  tone(SPEAKERPIN, 500, 500);

}

I am using this code to generate 2 signals, called CI and FDCS. CI stays on until the 5th FDCS pulse. I checked the output which is connected to a driver using the scope and I got this.
The rising edge and falling edge of the longer signal (CI, dark green) are supposed to sync with the rising edge of the FDCS signal (Lime green),but they are inline with the falling edge. Note that the output is inverted (when compared to the code) hence the signal generated by the Arduino pins is according to the code.

I did not tried it out. But something like this might help to synchronize the inverted signals to the rising edge of the high frequent signal.
I removed the FDCSoffset delay, because it is negative according to the variables at the top.
// initialize CIState with 00
int CIState=B00000000;

// lines not shown .....

for( totalCnt=0; totalCnt<8000; totalCnt++ )
{
  CIState=CIState^B01000000;
  if(totalCnt%4==0)
  {
    CIState=CIState^B00100000;
  }
  // both signals are set at the same time
  PORTD=CIState;
  delayMicroseconds(PWus);
}


Arduino ADK, other board, shield or what? Sorry for bothering.
I have a problem with my project and I can't fine someone who can help me yet.

I need the next configuration:
PC --------------USB cable-----------------MegaA---------------USB cable----------------MegaB

I need serial communication with USB cable in both boards.

I have now solved the ( PC --------USB cable------MegaA) part.

And the other part, I have done PC------------------USB cable------------------MegaB

But I need do that like the first schematic.
I don't have access to the MegaB because this is inside a machine, I can't access to its pines, I need connect to it by USB Cable.
Is possible do that with ARDUINO MEGA ADK in the MEGA A position? or I need other kind of board or add one shield (like USB host)?
I need send one thing from the pc to MegaA and Mega A send the same thing to MegaB.
Is it possible? because I can't find some way to specify that I need recieve the information from one serial port, and send it to another different serial port.
I need help, is very important.
Excuse my english
Thanks

You would need a USB host shield to achieve what you want.

The Arduino by itself is not capable of connecting to both a PC and another Arduino through USB without the addition of extra hardware.  In this case the USB Host Shield as detailed on the Arduino website:

http://www.arduino.cc/en/Main/ArduinoUSBHostShield

In the list of supported devices is:

USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.

The magic word there is ACM - that (or more specifically CDC/ACM) is what the Arduino USB Serial interface is.


How does the Space Replay record audio? The Space Replay
A hovering object that explores and manipulates transitional public
spaces with particular acoustic properties. By constantly recording
and replaying these ambient sounds, the levitating sphere produces a
delayed echo of human activity.

In this project, the Arduino board and an Adafruit Wave Shield is used. The Wave shield is not designed to record audio however, they say that they use the board for both recording and playback.

The sphere responds sonically to people and its surroundings by means of a battery-powered Arduino, an Adafruit Wave Shield hacked to record and playback audio on-the-fly and a small speaker.

This generates a few questions.

How would this be done?
Where would the microphone be placed inside the balloon for decent audio capture?
Would there be a better way to design this?

It seems to be possible to record with the shield using a library called waverp

  WaveRP is an Arduino library for recording and playing Wave files with
  the Adafruit Wave Shield. It records 8-bit mono files at 4,000 to
  44,100 samples per second.

Some details adafruit blog:

  It records 8-bit mono files at 4,000 to 44,100 samples per second.


How to find how much data in the transmit buffer? How do you find how many bytes are currently waiting in the transmit buffer?

I'm trying to diagnose a weird serial disconnection problem with an Arduino Uno and a rosserial node. It works fine for 10-20 minutes, and then mysteriously losing connection. At first, I thought the Arduino was running out of memory, but I'm able to use the MemoryFree library to log available memory, and it never drops below 9051 bytes.

I now want to make sure the problem isn't because the serial buffer is overflowing, from the Arduino trying to send too much data.

If you really want to know (not that it would do you any good) you can use the Serial.availableForWrite() function (which returns how much space is left in the buffer) and subtract the returned value from the size of the buffer.

int used = 64 - Serial.availableForWrite(); // Assuming a 64 byte buffer

I haven't tested it, but you may be able to use SERIAL_TX_BUFFER_SIZE instead of the 64 to make it properly portable.

int used = SERIAL_TX_BUFFER_SIZE - Serial.availableForWrite(); // Possibly portable


Sending a value from one arduino to another I wonder if it is possible to send a value from one  arduino to another.

Basically, I have one arduino measuring let's say weight, but I want to display that value using an lcd in another arduino.
Is it possible to  send the value to a pin using analogwrite or digital write in the arduino doing the measurement and use analogread/digitalread at the other arduino making the display?

I do not know if this is possible but what is attractive is that one can have several arduino making weight measurements, all showing up in the display of just one central one...

You could have the LCD Arduino be an I2C master and all the weighing Arduinos be slaves. There's an example of master/slave communication and wiring here: https://www.arduino.cc/en/Tutorial/MasterReader.

I2C supports up to 128 devices and the wiring is very simple.


Split up Arduino code into multiple files using Arduino IDE I am working on a very long code that requires multiple functions defined. I want to split the code into two files as main code ("Feeder_Control" in the screenshot) and functions ("connections" in the screenshot) How to import the second file into main code to use its functions?

PS: In C/C++ same thing is done with #include "connections.h". How is it done in Arduino IDE.

.

There is no need to use an #include directive for the additional .ino file.
Before compilation starts, the Arduino IDE concatenates all .ino files in your sketch into a single file, starting with the .ino file that matches the sketch folder name, followed by the rest of the .ino files in alphabetical order. So there is no difference between one massive .ino file and breaking the same code among multiple .ino files, other than the greater ease of navigating the code via tabs. After a bit more processing, this file is compiled as C++.
Reference:
https://arduino.github.io/arduino-cli/latest/sketch-build-process/#pre-processing


Any advice on how to repeat the song 6 times instead of infinitely? //Here is my code so far
int speakerPin = 9;

int length = 28;

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo);

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   delay(tempo);

}

}

Assuming, the program can stop after playing 6 times, put another for loop in the loop function:
void loop()
{
   for (int nTimes = 0; nTimes < 6; nTimes++)
   {
      // Existing loop code
   }

   while(true) {};
}

A less crude way is to create a global variable:
int _timesPlayed = 0;

And change the for loop:
void loop()
{
   if (_timesPlayed < 6)
   {
      // Existing loop code

     _timesPlayed++;
   }
}


Arduino IDE/Visual Micro - Undefined reference to constructor I am using Visual Studio Community 2015 with the newest version of the Visual Micro Arduino Plugin, however I also tried compiling my code in the Arduino IDE.
When compiling my code, there is the following error:

Compiling debug version of 'Autonomous_Car' for 'Arduino/Genuino Uno'
Autonomous_Car.cpp.o:In function `setup
Autonomous_Car.ino:undefined reference to `List<UpdateAble>  List()
Autonomous_Car.ino:undefined reference to `List<UpdateAble>  ~List()
collect2.exe*:error: ld returned 1 exit status
Error creating .elf

Some info

Adding #include "List.cpp" fixes the error, however this does not seem like valid C++.
The files do not lay in any sub-directory
In my Project Explorer both List.h and List.cpp are added to the project.
I also removed both files from the project, deleted them and added them again
I deleted the ´%AppData%\Local\Arduino15´ directory
I am fairly new to C++ and Arduino, there might be something obvious, what I just can't find

Autonomous_Car.ino

#include "List.h"
#include "UpdateAble.h"

void setup()
{
    List<UpdateAble>* myList = new List<UpdateAble>();
    myList->GetCount();

    delete myList;
}

List.h

#ifndef _LIST_h
#define _LIST_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif

template <class T>
class List {
public:
    void Add(T &item);
    bool Contains(T &item);
    bool Remove(T &item);
    void Clear();
    int IndexOf(T &item);
    T* GetItem(int index);

    inline int GetCount() { return count; };
    inline int GetCapacity() { return capacity; };

    List();
    ~List();
private:
    void EnsureCapacity(int capacity);

    int count;
    int capacity;
    T** items;
};

#endif

List.cpp

#include "List.h"

// Constructor
template <class T>
List<T>::List() {
    List::capacity = 4;
    List::count = 0;

    List::items = new T*[List::capacity];
}

// Cleanup
template <class T>
List<T>::~List() {
    delete[] List::items;
}

template <class T>
void List<T>::EnsureCapacity(int capacity) {
    if (List::capacity < capacity) {
        // Kapazität verdoppeln
        List::capacity = List::capacity * 2;

        // Speicher für neues array reservieren
        T** newArray = new T*[List::capacity];

        // Array kopieren
        for (unsigned int i = 0; i < List::count; i++) {
            newArray[i] = List::items[i];
        }

        // Speicher von alten array freigeben und neues array zuweisen
        delete[] List::items;
        List::items = newArray;
    }
}

// Adds a new item to the list
template <class T>
void List<T>::Add(T &item) {
    List::EnsureCapacity(count + 1);

    List::items[count] = item;
    List::count++;
}

// Gets whether the list contains an item or not
template <class T>
bool List<T>::Contains(T &item) {
    return List::IndexOf(item) != -1;
}

template <class T>
bool List<T>::Remove(T &item) {
    int index = List::IndexOf(item);

    // If the item does not exist, we cannot remove it
    if (index == -1) return false;

    // Move every item behind our item one further
    for (int i = index + 1; i < List::count; i++) {
        List::items[i - 1] = List::items[i];
    }

    List::count--;
}

// Release the heap
template <class T>
void List<T>::Clear() {
    for (int i = 0; i < List::count; i++) {
        delete List::items[i];
    }

    delete[] List::items;
}

// Gets an index of an item, -1 if not found
template <class T>
int List<T>::IndexOf(T &item) {
    for (int i = 0; i < List::count; i++) {
        if (List::items[i] == item) {
            return i;
        }
    }

    return -1;
}

template <class T>
T* List<T>::GetItem(int index) {
    if (index < List::count && index >= 0) {
        return List::items[index];
    }

    return 0;
}

I'd be very glad, if we can find the solution.

You're using a template class. A template class is a special corner case that breaks the "code in .cpp and definitions in .h files" rule.

Because it's a template it can't be pre-compiled - it needs to be specially compiled each time it is used, so that it can get the right values compiled in to the template place-holders, which are provided by the CU that has the template class included with it.

Because of that it is one of the rare cases where the code has to be in the header file.

For a full example you can take a look at my Average library which is a fully templated class.


Hooking up 12v Push button to arduino uno/nano I want to use one an push button with an led in middle, similar to this one on eBay.
The push button has a 12v input I want to hook it up to an Aduino Uno or Nano.

Is there a way to hook it up and receive the signal?

Specifications from the eBay page:

  Latching type, push it—on, push it again — off
  Switch Rating: 3A/250VAC
  LED voltage: 12V only
  Contact Configuration: 1NO1NC
  Pin Number: 5

Most likely, there will be a push button, and on separate wires, there is a light. If this is the case, you can hook the push button part up to the arduino. You can test this - find two random wires, test the resistance with a multimeter, then press the button and see if the resistance changes. Keep trying until you find two wires that change when you press the button.

Once you find the pair, you can hook one of those two to a digil pin on the Arduino, and via a resister (large, anything 10kilo-ohm or larger is fine) to ground (GND). Then, connect the other side of your pushbutton to 5V. See http://arduino.cc/en/tutorial/button for photos and a circuit diagram - their wiring is more complicated than it needs to be, and their button has 4 pins in two pairs (left pair, and right pair in the picture with the breadboard; the left-top and left-bottom are permanently connected, and the right-top and right-bottom are permanently connected). Have a look at the circuit diagram - that's a lot simpler. The zig-zag at the top is the resistor, and the disconnected looking thing is the switch (open). There is sample code there too.

Note that push buttons typically "bounce" - that is, when you push them, they will go (starting off) on-off-on-off-on-off-on, so if you're counting the number of pushes you will get a result which is way too high. If you delay long enough in between (10ms?) then you won't get these. The code I linked to already has debounce built in.

The other part is the light. This is a little more tricky. The light will probably use too much current for the arduino to supply directly. You will need a transistor and a resistor (again, at least 10 kiloOhm is good).

The transistor should be an NPN transistor, and should look like the top one in http://www.reprise.com/host/circuits/transistor_pinouts.asp. The easiest one is the base - this is the middle one. Connect this via your resistor to another digital pin on your arduino (pin 13 is great for testing this, because it will also light up the led on the Arduino). Next, connect your emitter to ground (GND). Then, IF YOUR POWER SUPPLY IS NO MORE THAN 12 VOLT! you can connect VIN to the + side of the light, and the - side of the light to the collector.

Next, load a sketch - the "blink" sketch is good to test this. Adjust the pin as necessary.

Note that, these switches have a resistor already built in to the light; if you want to do the same with an ordinary led, you will have to add one yourself. Check out http://ledcalc.com/ to tell you which resistor you need.


error: invalid conversion from 'char' to 'char*' [-fpermissive] I have written a simple code to read data from capacitive keypad and display it on LCD.

I am getting the data from keypad in following data structure.

char phoneNumber[PHONE_DIGITS];

and then displaying the data on LCD as

   LcdString(phoneNumber[i]);

where my LCD string function is

void LcdString(char *characters)
{
  while (*characters)
  {
    LcdCharacter(*characters++);
  }
}

There is a type cast error

  error: invalid conversion from 'char' to 'char*' [-fpermissive]

How can I debug it?

You're calling your function with a single char, specified by phoneNumber[i], but your function is expecting an array.

If you change your call to:

LcdString(phonenumber)

then that will pass the entire array.

Are you trying to say that you're storing multiple phone numbers?  i.e. a two dimensional array?  Check out the String reference for more details: https://www.arduino.cc/en/Reference/String


How to add if condition in RFID example? Using an Arduino Mega 2560 and PN532 NFC/RFID module, I want to be able to scan a card and see if its value is (0xF0, 0x21, 0x5D, 0xA7). It should print "accepted" in the serial monitor.

However during compilation it keeps telling me:

iso14443a_uid:99:11: error: expected primary-expression before ']' token

if (uid[] = {0xF0, 0x21, 0x5D, 0xA7}){
        ^

exit status 1 expected primary-expression before ']' token

This is my code:

/**************************************************************************/
    /*!
        This example will attempt to connect to an ISO14443A
        card or tag and retrieve some basic information about it
        that can be used to determine what type of card it is.

    Note that you need the baud rate to be 115200 because we need to print
    out the data and read from the card at the same time!

    To enable debug message, define DEBUG in PN532/PN532_debug.h

*/
/**************************************************************************/

/* When the number after #if set as 1, it will be switch to SPI Mode*/
#if 0
  #include <SPI.h>
  #include <PN532_SPI.h>
  #include "PN532.h"

  PN532_SPI pn532spi(SPI, 10);
  PN532 nfc(pn532spi);

/* When the number after #elif set as 1, it will be switch to HSU Mode*/
#elif 0
  #include <PN532_HSU.h>
  #include <PN532.h>

  PN532_HSU pn532hsu(Serial1);
  PN532 nfc(pn532hsu);

/* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
#else
  #include <Wire.h>
  #include <PN532_I2C.h>
  #include <PN532.h>
  #include <NfcAdapter.h>

  PN532_I2C pn532i2c(Wire);
  PN532 nfc(pn532i2c);
#endif

void setup(void) {
  Serial.begin(115200);
  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // Set the max number of retry attempts to read from a card
  // This prevents us from waiting forever for a card, which is
  // the default behaviour of the PN532.
  nfc.setPassiveActivationRetries(0xFF);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A card");
}

void loop(void) {
  boolean success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

  if (success) {
    Serial.println("Found a card!");
    Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("UID Value: ");
    for (uint8_t i=0; i < uidLength; i++)
    {
      Serial.print(" 0x");Serial.print(uid[i], HEX);
    }
    Serial.println("");
    // Wait 1 second before continuing
    delay(1000);
  }
  else
  {
    // PN532 probably timed out waiting for a card
    Serial.println("Timed out waiting for a card");
  }
  if (uid[] = {0xF0, 0x21, 0x5D, 0xA7}){
    Serial.println("Success");
    }
}

As has been noted in the comments you can't compare arrays like that. Instead you have to iterate through each entry and compare the individual elements.

If it's just a few entries, then you can do it manually:

if ((uid[0] == 0xF0) && (uid[1] == 0x21) && (uid[2] == 0x5D) && uid[3] == 0xA7) {
    // ...
}

If your values are both in arrays then you can use the memcmp() function to compare them:

uint8_t compare[] = {0xf0, 0x21, 0x5d, 0xa7};

if (memcmp(uid, compare, 4) == 0) {
    // ...
}

memcmp returns 0 if the two arrays match up to the number of bytes given (4 in this case), or a negative or positive number if the one is "less than" or "more than" the other.


Can BUS Shield on Arduino Leonardo - Can't init CAN I'm hoping to get some help with this as I am unable to get the CAN to Initialize.

I have the sparkfun Can-Bus shield: https://www.sparkfun.com/products/13262

and an Arduino Leonardo board.

I'm using the following code to try to connect my 2008 Audi S6 to the Arduino board:

#include <Canbus.h>
#include <defaults.h>
#include <global.h>
#include <mcp2515.h>
#include <mcp2515_defs.h>
#include <Canbus.h>
char UserInput;
int data;
char buffer[456];  //Data will be temporarily stored to this buffer before being written to the file

//********************************Setup Loop*********************************//

void setup(){
Serial.begin(9600);
while(!Serial);
Serial.println("CAN-Bus Demo");

if(Canbus.init(CANSPEED_500))  /* Initialise MCP2515 CAN controller at the  specified speed */
  {
Serial.println("CAN Init ok");
  } else
  {
    Serial.println("Can't init CAN");
  }

  delay(1000);

Serial.println("Please choose a menu option.");
Serial.println("1.Speed");
Serial.println("2.RPM");
Serial.println("3.Throttle");
Serial.println("4.Coolant Temperature");
Serial.println("5.O2 Voltage");
Serial.println("6.MAF Sensor");

}

//********************************Main Loop*********************************//

void loop(){

while(Serial.available()){
   UserInput = Serial.read();

if (UserInput=='1'){
 data=Canbus.ecu_req(VEHICLE_SPEED, buffer);
 Serial.print("Vehicle Speed: ");
 Serial.print(data);
 Serial.println(" km/hr ");
 delay(1000);
}
else if (UserInput=='2'){
 data= Canbus.ecu_req(ENGINE_RPM, buffer);
 Serial.print("Engine RPM: ");
 Serial.print(data);
 Serial.println(" rpm ");
 delay(1000);

}
else if (UserInput=='3'){
 data= Canbus.ecu_req(THROTTLE, buffer);
 Serial.print("Throttle: ");
  Serial.print(data);
 Serial.println(" %% ");
 delay(1000);

}
else if (UserInput=='4'){
 data =Canbus.ecu_req(ENGINE_COOLANT_TEMP, buffer);
 Serial.print("Engine Coolant Temp: ");
 Serial.print(data);
 Serial.println(" degC");
 delay(1000);

}
else if (UserInput=='5'){
 data=Canbus.ecu_req(O2_VOLTAGE, buffer);
 Serial.print("O2 Voltage: ");
 Serial.print(data);
 Serial.println(" V");
 delay(1000);

}
else if (UserInput=='6'){
 data=Canbus.ecu_req(MAF_SENSOR, buffer);
 Serial.print("MAF Sensor: ");
 Serial.print(data);
 Serial.println(" g/s");
 delay(1000);

}
else
{
  Serial.println(UserInput);
  Serial.println("Not a valid input.");
  Serial.println("Please enter a valid option.");
}

}
}

Overall, I just can't get the CAN to initialize. I've looked online and just can't seem to find a solid solution. I've tried other libraries as well to no avail.

Please assist!

Had this problem myself. Found this fixed it

Change the following line...

_delay_us(10);

To...

_delay_us(50);

In the MCP2515.c file in the library


How can I reduce the size of my sketch? Looks like I'm overshooting the storage of my Adafruit Trinket:

Sketch uses 5,600 bytes (105%) of program storage space. Maximum is 5,310 bytes.
Global variables use 109 bytes of dynamic memory.

Any tips for reducing the footprint of my code?

#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <RTClib.h>

#define LEDPIN 1
#define TONE 4
#define BTNPIN 3

RTC_DS1307 rtc;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, LEDPIN, NEO_RGB);

long fadeTime = 1 * 10000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int timeHour = 14;
int timeMinute = 43;
uint32_t alarmLength = 5 * 60000L; // 5 minutes

void setup() {
  rtc.begin();
  if(!rtc.isrunning()) {
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }

  pinMode(TONE,OUTPUT);
  pinMode(BTNPIN, INPUT);
  digitalWrite(BTNPIN, HIGH);

  strip.begin();
  strip.show();
}

void loop() {
  DateTime now = rtc.now();

  if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 0){
    // Fade in light
    for(int i = 1; i<colorStops; i++){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(i,i,0));
      }
      strip.show();
      delay(delaySpeed);
    }

    // Play tone after light fully bright
    for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
      if (kill() == true){ break; }

      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
      }
      strip.show();

      beep(TONE, notes[random(0,3)], 50);
      delay(100);
    }

    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
  }
}

void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
  int x;
  long delayAmount = (long)(1000000/frequencyInHertz);
  long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
  for (x=0;x<loopTime;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}

bool kill() {
  if (! digitalRead(BTNPIN)) {
    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(0,0,0));
    }
    strip.show();
    return true;
  }
  else {
    return false;
  }
}

The AdaFruit Trinket just doesn't have a lot of memory - 8kb, of which 3kb is used by the bootloader.
The order I look for things to reduce the footprint of an Arduino program are:

data (e.g. large strings)
libraries
your code (especially doing the same things several times, which might be combined into loops or functions).

In this case, you don't have much data. Most of your resulting program size is in the libraries you use.
It seems like you use the clock solely to detect the year - that seems like a lot of overhead just to figure out what year it is. It then does nothing for subsequent years (or prior years), if I read your code correctly. Maybe you would consider dropping this code? Then you can skip the entire RTC library. At least try it to see how much you save. I suspect that the RTC library will use another library to do the underlying work.
You use the <Wire.h> library, but don't reference it in your code. It should be optimized out (unless used elsewhere), but there's no reason to have it there.
You may also save a little space by replacing initialized variables which don't change to constants. Storing 25 in a variable takes 1 byte, plus 2 bytes every time you reference it; 25 in a constant gets optimized away, and will take up 1 byte every time you reference it.
As mentioned in the comments, you can also save a few bytes by specifying the size of your int's, especially initialized ones.
Another option would be to use a larger chip - the AtMega328p used in (for example) the Arduino has 32kb of flash - 6 times the (available) size.
You can also save some bytes by removing the clause  if(!rtc.isrunning()) {, once you have set it up once.
Additional: I have had some success reducing footprints by reimplementing a subset of a library. Usually, libraries are very well implemented, but if your needs are substantially different/simpler than what the library was designed for, or you are willing to forgo parts of it (e.g. error checking), then SOMETIMES this can help. WARNING! There is a HIGH price to pay (coding, debugging, loss of error checking, undetected bugs etc), and it may not save you anything in the end.
You can also (sometimes) move data (e.g. large strings) to eeprom. The Trinket has 512 bytes of eeprom. You may need one sketch to load the data into eeprom, to run before loading your main sketch. eeprom has it's own overhead, so may not be worthwhile for 512 bytes, it is slower (which probably won't matter for this), and you have a limited number of writes.
Another few bytes may be saved by doing all the maths for the tone frequency/time beforehand, and sacrificing something. For example, you beep for 50ms. If, instead of passing the frequency (between 262 and 349 hertz) and instead pre-calculate the delayAmount (for 262 hz, this would be 1,000,000/262 = 3817ms); your looptime for this is ((timeInMilliseconds1000)/(delayAmount2)) = (501000)/(38172) = 6.55 cycles. 7 cycles is probably "close enough" for all the tones you want to produce. So you can hardcode 7 cycles (using a constant of 7 for looptime), and get rid of that formula to calculate looptime.
In a similar way, if you don't care too much about the exact frequency (which varies between 3817ms and 2865ms depending on your random number), you might specify the delayamount as 2865+random(0,3)*238 (make sure you store at least the random number, you don't want it to change during the loop!).
You now have:
#define random_beep_length 7
void random_beep (unsigned char speakerPin)
{   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
    // Heavily modified!
  int x;
  unsigned char pitch = 2865+random(0,3)*238;
  for (x=0;x<random_beep_length;x++)
  {
    digitalWrite(speakerPin,HIGH);
    delayMicroseconds(delayAmount);
    digitalWrite(speakerPin,LOW);
    delayMicroseconds(delayAmount);
  }
}


Limited to 1MP still captures with OV5642 ArduCam Mini + Arduino Uno I have an Arducam-Mini-5MP with Arduino UNO R3. I am running the unaltered example ArduCAM_Mini_OV5642_Video_Streaming to the arduino and am running ArduCAM_host_v1.0.exe on my PC with huge successes.

In this state, I can reliably take photos at low resolution (up to 1280x720) in all tested settings. However, when I go to higher resolutions (2592x1944, 2048x1563, and 1920x1080), certain situations result in consistently corrupt images all with the exact size of 524288 bytes.

The images are corrupted whenever I point the camera outside my window, and images are fine when taking photos inside my house. At 1280x720, a typical photo inside my house is 80kb and a typical photo out the window is 190kb (more than double in size). I suppose some content of the photo is impacting the jpg compression?

Unfortunately, images are corrupt 100% of the time for the actual subject I want to take; but the camera works perfectly when I'm testing it indoors. In my scenario I can only capture 0.8MP before images become corrupt.

The frame buffer limit for Arducam is 512kb, so am I just running up against the constraints of the hardware? I feel a bit fooled because I bought a 5MP camera and can only take 0.8MP photos with it.

Is my understanding of this failure correct -- is this the frame buffer size being hit by conditions impacting jpg compression? Are there Arducam shields available with higher frame buffers? Can I avoid this situation somehow?

The Arducam Mini Shield is limited to 512kb frame buffer, so photos of larger resolution easily overflow the buffer. You can fit higher resolution photos onto the frame buffer by increasing the compression or adjusting other settings on the camera that reduce the file size of the resulting image (reduce saturation, windowing, etc).

To change the compression, adjust register 0x4407. The higher the number the more compression there is. The camera's default is 0x0C and the Arducam sample code sets it to 0x04.  myCAM.wrSensorReg16_8(0x4407,0x09);

To adjust other settings on the camera (including the ones listed above) check out the detailed list of camera registers at http://www.dragonwake.com/download/camera/ov5642/OV5642-DS.pdf

Also, Arducam is releasing the Arducam Mini Plus which has an 8 MByte frame buffer and is available on advanced order for $35 USD by contacting Arducam directly.


Piezo buzzer not sounding well with ATmega328 I am using an ATmega328 to drive a 16x2 LCD, a LED, and a piezo buzzer. Piezo buzzer needs to buzz after every 5 seconds. But it doesn't make a nice sound it just gives out a faint buzz. Suspecting the buzzer to be faulty, I tested it separately from a 5V supply and it worked well. Then I put it back in the circuit and checked for the amount of current the whole circuit used. It was about 26mA when buzzer and LED were turned off, and 36mA with buzzer and LED ON. So no problem there. Additionally, the buzzer sometimes start sounding well too occasionally. This occurs after about half a minute the circuit is turned ON. This looks like that the buzzer is somewhat warming up before it can work properly. But this occurs occasionally.

I am using A0 Analog pin (or Pin no. 23 on ATmega328) for driving the Buzzer and giving 100Hz square wave to it.

What could possibly be the reason for this problem?

If it works well with direct 5v supply and not from an Arduino pin, you probably need a transistor to drive the buzzer.

Here is an example how to drive a buzzer using a transistor:
https://www.maxphi.com/piezo-buzzer-interfacing-arduino-tutorial


How to store firmware configuration or image in source-control? I'm writing an Arduino application in C/C++ and I'm storing my source code in Github.

However, to make my code runnable, I have had to install multiple libraries through the Arduino desktop tool like this:

And I have had to update the firmware and certificates through the Arduino desktop tool like this:

How can I store these firmware updates, library changes and certificates in source control? Is there a binary image I can download and check in? Better yet, is there some plain-text source file that I can check-in to derive such a binary?

For libraries only add comment next to #include with version number and author's name if the library is in Library Manager or the download location if it is not in Manager.

Example:

#include <MemoryFree.h> // https://github.com/mpflaga/Arduino-MemoryFree
#include <Ethernet.h> // Ethernet 2.00

Put NINA firmware version in some comment at the top of the main sketch file. The firmware is part of the Arduino boards package so no need to store it in your repo. If you modified the firmware, publish source code in your fork of the official repository and there you can then release the binary too.

Put public certificate keys and similar files in sketch folder in subfolder called extras or data.

And write a README file for your repository.


MQTT - Can lastwill be sent to multiple topics? I'm using an ESP8266 as an IOT device, with MQTT to send status messages.
Each device have its own availability topic, to state its online or offline state ( needed for Home Assistant indication on web GUI )

Since multiple devices are present- I was wondering if a lastwill status can be sent for a joint topic to be monitored ( for example :"device_id:offline" )

my relevant part of the code defining a lastwill for devices topic is : mqttClient.connect(deviceName, user, passw, availTopic, 0, true, "offline")

EDIT1:
using PubSubClient.h

The "Last Will & Testament" facility of MQTT is controlled by the server, not the client.

The topic and payload are specified when the client connects as part of the connection handshaking. When the client disconnects this stored information is published automatically by the server.

The specification only allows for one topic and payload to be set.

Of course, you can specify the same topic for many clients and give each one its own distinct payload, but you can't also have a unique topic for each client at the same time.

This is according to the specification - however that doesn't stop a broker implementing its own extensions to the specification to allow such things - but I know of no such extensions being implemented. But, given the open-source nature of many MQTT implementations (PubSubClient.h and Mosquitto, for example), there is no reason you couldn't extend the protocol to implement your own requirements (at the cost of compatibility with other systems of course).


digitalPin giving lower voltage than Vcc I am using an ATTINY88 for a project that requires to turn on an LED. Right now I am using pin PA1(ADC7/PCINT25). I noted, however, that when the pin is ON, I get about half the voltage that is connected to Vcc. I checked the voltage in other pins and they are close to Vcc. Will anyone know, what could be the reason for this?

I figure this pin has an internal resistor enable, but I am not certain.

You should connect the AVCC pin to VCC. From the datasheet (emphasis
mine):

  AVCC is the supply voltage pin for the A/D converter and
  a selection of I/O pins. This pin should be externally connected to
  VCC even if the ADC is not used. [...]

  The following pins receive their supply voltage from AVCC:
  PC7, PC[5:0] and (in 32-lead pack- ages) PA[1:0]. All other I/O
  pins take their supply voltage from VCC.


How to improve response time of this sound operated LED? I have written the following code for lighting an LED on a  clap ( using sound sensor)   that I have connected via a resistance of  330 OHM on pin number 4.

However, when I clap once,  close to the sound sensor,  it does not lights  the LED. But it only lights the LED if  I provide prolong exposure to sound  ( more than 6 seconds) on the sound sensor.

How can I improve this , so that even if I clap once for a seconds duration, the LED glows?

int soundSensor=10;
int LED=4;

void setup()
{
 Serial.begin(9600);
 pinMode(soundSensor,INPUT);
 pinMode(LED,OUTPUT);
}

void loop()
{
  int SensorData=digitalRead(soundSensor);
  if(SensorData==1)
  {

     digitalWrite(LED,HIGH);
  delay(3000);

     Serial.println("LOUD, LOUD");
     delay(1000);
  }
    else
  {

     digitalWrite(LED,LOW);
     Serial.println("SLOW, SLOW");
     delay(1000);
  }
 }

I think the problem is in the times you check the sensor. If you clap exactly when you check it will glow even if clapped for 1 ms, but if it checks in between two claps it doesn't detect it.

So check more often (reduce the delays) and check for so many sound detections within one second.

Or, as JRE below proposes, use an interrupt, this is even better but needs a bit more programming skills. Still interrupts are used a lot in microcontroller programming so it is worthwhile to check into this.


How can I enable the security bit of a teensy board? I want to prevent someone from connecting an arduino device to a computer and downloading the code (yes, the hex-dump code) because I want to embed a wifi password inside a device that should be kept secret

With that said, I stumbled upon this answer that mentions a security bit

I would like to ask for more details regarding it - i.e. how can I use it, enable it, what are it's limitations, etc. (Preferably for a Teensy v3.2 board, but if it's standard/generic, I would accept such an answer as well).

The Teensy 3.2 board is based on MK20DX256. The processor core is an ARM and not AVR. The best way to learn about security on the MK20DX256 is to read the documentation.

  Chapter 8 Security
  8.1 Introduction
  This device implements security based on the mode selected from the flash module. The following sections provide an overview of flash security and details the effects of security on non-flash modules.

  8.2 Flash Security
  The flash module provides security information to the MCU based on the state held by the FSEC[SEC] bits. The MCU, in turn, confirms the security request and limits access to flash resources. During reset, the flash module initializes the FSEC register using data read from the security byte of the flash configuration field.

  NOTE The security features apply only to external accesses: debug and
  EzPort. CPU accesses to the flash are not affected by the status
  of FSEC. In the unsecured state all flash commands are available to the programming interfaces (JTAG and EzPort), as well as user code execution of Flash Controller commands. When the flash is secured (FSEC[SEC] = 00, 01, or 11), programmer interfaces are only allowed to launch mass erase operations and have no access to memory locations.

  Further information regarding the flash security options and enabling/disabling flash security is available in the Flash Memory Module.

The next step is to search for an open-source project that uses the FSEC setting. And by chance the mbed does. Here is link to how it is done in the mbed CMSIS Cortex-M4 Core Device Startup File for the MK20DX256. There should be the same setting in the Teensy Arduino core. Locating that is left to the reader.

Cheers!


5v input on ATmega328p running on 3.3v The ATmega328p can run on 5v but will it cause problems if it runs on 3.3 v and one input signal is 5v?

The voltage at any input must be less than VCC+0.3V unless it is restricted to only a few milliamperes (so it doesn't burn out the clamping diode). Use a proper voltage translator if it is available, otherwise use a 1kohm or greater resistor (at the cost of life expectancy for the MCU).


Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V? To control my robot, I need to generate negative and positive voltage in a single line, because the motor I try to control is an industrial one.

Do you have any suggestion for it? How can I produce a negative voltage using an Arduino board and simple electrical elements?

Your question should read:

  How do I scale a 0 to 5 V signal to -10 V to +10 V?

First write the conversion formula:

Vout = 4 * Vin - 10

Testing the formula gives the following:

Vin = 0.0 V ==> Vout = -10 V
Vin = 2.5 V ==> Vout = 0 V
Vin = 5.0 V ==> Vout = +10 V

You will need an op-amp circuit to create this function. In addition you will need a +12 and -12 V supply.

simulate this circuit – Schematic created using CircuitLab

How it works:

OA1 is an op-amp wired in an inverting summing amplifier configuration. We'll address the inversion later but for now all the answers will be "upside-down". The gain is set by -R2/R1 = -40k/10k = -4. If we feed 1 V in from the ADC we will get -4 V out.
R3 provides a negative input. The gain will be set by -R2/R3 = -40k/48k = -5/6. Since it's connected to -12 it will contribute +10 V to the output.
The actual output will be the sum of the two: in our example, +10 - 4 = 6 V.
C1 and C2 provide noise filtering for the op-amp. Place them close to the chip.

Now, what to do about the inversion? We have three choices:

Fix it in the micro controller code. Set +5 V as maximum reverse speed / torque. Set 0 V as maximum forward speed / torque.
Fix it in the servo amplifier and tell it to reverse its command signal.
Fix it in the electronics. By adding another inverting op-amp we can turn the signal the right way up.

The TL082 opamp suggested has two op-amps in the one 8-pin package.

Ref: Inverting Summing Amplifier.

Servo Enable

simulate this circuit

Delay the servo enable until the micro controller has initialised and all other functions are ready. See manual Section 3.2.3, page 73.

Note that this is a simplified relay drive schematic. You need a transistor drive and a snubbing / flyback diode around the relay so one of the small 5V relay boards would be a good solution as they are already built in. An opto-isolator would be simpler.

Ensure that safety circuits (guarding and e-stops) are correctly wired using safety-rated components (and not only, for example, the micro).


How can I play music using a speaker and Micro SD card Module? I am trying to play music using my Arduino and micro SD card module but can't seem to do it. Can anyone shed some light on this? The SD card module I'm using is a Catalex sainsmart micro SD card module. It has the outputs VCC, GND, MISO, MOSI, CS, and SCK. VCC is in 5v, GND is in GND, CS is in Pin 4, MISO is in Pin 12, and MOSI is in Pin 11.

This Arduino project is one of the most simple and fun projects you
  can build with Arduino in 10-15 minutes. The result of this make will
  be an Arduino Audio Player which will play “.wav” files. It consist of
  a speaker, a simple transistor acting as an amplifier and a micro-SD
  card adapter with a micro-SD in it through which the .wav files are
  loaded and played.

https://diyhacking.com/arduino-audio-player/


How to properly use interruptions with twi (I2C) I would like to reprogram Wire.h, or a part, to use interruptions, in order to not waste time to wait. I'm using an Arduino Mega with an Adafruit motor shield v2.3.

In the datasheet, page 262, 24.9.2, bit 0, I can read that I have to set the TWIE flag to one to be able to catch the interruption.

So, I started to write this code :

//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

int etat = 0;
uint8_t currentstep = 0;
uint8_t _addr;
uint8_t _data;

ISR(TWI_vect)
{
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);

  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
        //Serial.println(etat);
      }
      else
      {
        etat = -1;
      }
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
        //Serial.println(etat);
      }
      else
      {
        etat = -2;
      }
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
        //Serial.println(etat);
      }
      else
      {
        etat = -3;
      }
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      //Serial.println(etat);
      //Serial.println("Next");
      break;
  }
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b1010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }
  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

My problem is, once I reset TWIE to one on my interruption, the code looks like to freeze(in ISR(), case 0, TWCR =...). In my mind, the interruption is call only when TWIE is set to one and when the twi module says (when he sets TWINT to one I guess) that he finished the job. I don't understand how to properly use this interruption.

EDIT :
Thanks to @jfpoilpret, know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). In the datasheet, p246, they clearly explain how to use registers, but I'm not sure how to use the flag TWIE. I don't know if I have to set them both to one, or if i have to completely leave TWINT (I tried both, but nothing worked...).

Thanks for your help,
julien

After some tests, it's working !
First off all, I used Serial.println in my ISR, that's made it freeze apparently.
Second, apparently, I can't send more than 6 bits, else I'll have an error (data NACK), I thought it was 8.

This is my code working :

//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

volatile int8_t etat = 0;
volatile uint8_t _addr;
volatile uint8_t _data;

ISR(TWI_vect)
{
  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
      }
      else
        etat = -1;
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
      }
      else
        etat = -2;
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
      }
      else
        etat = -3;
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      break;
  }
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE)|(1<<TWINT);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b0010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }

  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

Thanks a lot to jfpoilpret !


VirtualWire `vw_get_message`: docs and examples on the PJRC site I'm looking at he following page, that describes functions from VirtualWire library and provides some examples.

https://www.pjrc.com/teensy/td_libs_VirtualWire.html

Some basic questions I have after reading it:

The description of vw_get_message function states.

  Read the last received message. This should be called only when a message is known to be received with any of the 3 functions above.

"3 functions above" refers to vw_have_message, vw_wait_rx and vw_wait_rx_max functions.

However, in the example on that very same page vw_get_message function is called from receiver's loop() without making any attempts to call any of those 3 functions first.

Why? Is it legal to use vw_get_message by itself? And how does it work in this case, i.e. what is the semantics of the return value?

The function is explicitly described as non-blocking, apparently implying that if this usage is legal, there's no way to tell "corrupted message" situation from "no message" situation.
Does the library preserve the granularity/separation of messages? I.e if the TX side sends 1-byte messages, does it guarantee that each call to vw_get_message on RX side will return 1-byte messages? It seems to be implied by the description of the protocol, but I'd like to ask just in case.
If the answer to the second question is "yes", then does this API preserve zero-length messages? Or are they discarded immediately?

The example with only vw_get_message is the common usage of the VirtualWire library. It returns true if something was received and the checksum was okay.
Yes, each message is seperated from the other messages. Each message gets extra bits (intro bits) and extra bytes (checksum and length).
I don't know, I have never tested that. Looking at the source code, there is no problem with zero length messages.

The VirtualWire library is outdated, although it is still used with Arduino boards with little memory (Arduino Uno, Nano, Leonardo, Pro Mini, and so on).
The RadioHead library (www.airspayce.com/mikem/arduino/RadioHead) has included the VirtualWire protocol with the RH_ASK mode. The examples for the RH_ASK mode shows that the usage is almost the same. The RadioHead library should be used when there is more memory (Arduino MKR, Zero, Due, and so on).


Accessing raspberrypi.local from Nodemcu Currently I am trying to access a rest API from NodeMCU. The API is hosted on my local LAN on a Raspberry pi 3 b. The Raspberry pi is accessible on LAN using the raspberrypi.local domain address.
But the problem is I am unable to access the raspberrypi.local address form NodeMCU.
It is unable to just resolve the address.
Can anyone please help me resolve this issue?

In order to access the API, your NodeMCU needs to know the IP address your Pi has at this time. There are several ways to resolve raspberrypi.local to the actual IP. Assuming the NodeMCU got its IP assigned by your WiFi hotspot, it also received a DNS server IP. This is where the NodeMCU would ask first. However, if this DNS server is hosted by your internet provider, it obviously would not know what to respond when asked for your raspberrypi.local.

Another way, especially for .local domains, is mDNS. NodeMCU has a module to do that.

If you work with this a lot, consider running a local development network with your own DHCP/DNS combo. dnsmasq is a good place to start. Lots of tutorials online. The Pi can host that for you.