Can I read from a memory card with three pins? I have a project where I have three pins to use and I just realized it would be better to use a memory card than replacing the code each time.

I'm building a Arduino with a push button. Press the button and it sends keystrokes to the connected computer with login details.
The login details need to change every three months so having that on a memory card will be easier.

So since I use a digispark Attiny 85 with a total of 6 pins (where two is used to send the keystrokes).
I have one to the push button, and three pins left.

Is there any card reader that can work with three pins? I only need to read if that makes a difference.
The ones I find use four pins (+ vcc and gnd).

Pretty much any memory card type is ok.

Not with an ATTiny85, and not with so few pins, no.

However, all is not lost.

The ATTint85 has 512 bytes of EEPROM inside it where you can store your login details. All you need is some way of telling setting that data in your sketch from the PC - and the simplest way is probably through a USB serial connection.

If you don't have a serial connection available (I think Digispark has a custom interface they use) then you can use whatever interface you have available to do the job.


ESP32 send UDP packets from both cores Im using AsyncUDP in an ESP32 project, where I initialize AsyncUDP udpSender and call udpSender.write(sendbuffer, sendbuffer_size) from both cores, with different buffers on each core.
One core is continually collecting GY-91 (accel/gyro/magnet) sensor data many times a second and sending it via UDP multiple times a second (after every collection), and the other one is collecting some other data like temperature once a second, as well as responding to commands a server sends.
So I'm basically using one sender on both cores and wondering if this is "thread-safe", if that terminology even applies to this scenario.
Can this cause problems? Is there a specific way this should be done? Like using semaphores?

I don't know if it's thread safe or not. However I would be inclined to play it sage and use a queue and notifications.

Create a queue
Create a "sender" thread that waits for notification then sends anything in the queue through UDP
Create any number of "sensor" threads that place items into the queue then notify the sender thread.


Getting RTK-precision GPS with arduino devices like NavSpark? In trying to learn how to create a reasonably precise 3d model of my (very hilly) property, I stumbled across a product called Navspark, which appears to be a $22 arduino-compatible development board, with an RTK-capable (and RTKlib-compatible) GPS chip.

The idea with RTK is that a reference-position base-station transmits its positional error to a mobile unit, giving the mobile unit cm-level precision relative to the position of the base station. The error calculation is computationally intensive, but apparently within the capabilities of a Pi.

Is it actually possible to build an RTK-capable mobile/base pair using low-priced equipment like this?  Can you link a howto or project example?

How about the http://www.navspark.com.tw/tutorial-4 tutorial?  It seems to indicate you need a couple of the more capable $80 NS-RAW units with carrier-phase info rather than the less capable $22 NAV-SPARC plain GPS units.

The RTK system doesn't transmit only its positional error, (which it knows from external information) but also communicates the phase information for the particular channels, and then the RTK software re-calculates the positions of both using common sets of satellites and the phase info.  With the same framework, it knows the relative positions accurately, and with assumptions about the location of the base station, it can correct mobile station

This isn't an arduino problem, unless you are asking about porting RTKlib to something arduino.


What is the difference between running code with the scope of the void setup() or void loop() vs. outside their scope? Good evening everyone,

I have bene playing around with making my own library, specifically for the controlling Timer1 on the Arduino Mega 2560. I'm sort of new to OOP but I am trying my hand at it here.

I wrote some code to generate a PWM wave with a 100 ms period and a 25% duty cycle, and I have Siglent SDS 1052DL, 50MHz oscilloscope that I'm using that verifies the code is successful. I am using clear-timer-on-compare-match mode and timer interrupts to generate the PWM wave. My code is below:

#include "Timer1.h"

Timer1 timer;

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

void loop(){
  // put your main code here, to run repeatedly:
}

I made a Timer1.cpp file and a Timer1.h to go along with this file. They are below.

Timer1.cpp

#include "Arduino.h"
#include "Timer1.h"

float frequency = 10.0;
float period_ms;
float clock_pulse = 16.0;

unsigned long opening_time = 25000;

unsigned int ocr1a;
unsigned int ocr1b;

Timer1::Timer1() { // Object used to control 16-bit timer1

}

void Timer1::begin() {
  CRITICAL_SECTION_START; // Clear I bit
  CLEAR_TCCR1A; // Reset TCCR1A
  CLEAR_TCCR1B; // Reset TCCR1B
  SET_CTC_MODE; // Set to CTC mode
  DISABLE_TIMER1_INTERRUPTS; // Disable OCIE1A/B
  TCCR1B |= (1 << CS12); // 256
  period_ms = (1000.0f / frequency);
  ocr1a = 1000UL * (period_ms / clock_pulse);
  OCR1A = ocr1a;
  TIMSK1 |= (1 << OCIE1A);

  ocr1b = (unsigned int)float(opening_time) / clock_pulse;
  OCR1B = ocr1b;
  TIMSK1 |= (1 << OCIE1B);
  TCNT1 = 0; // Reset counter

  CRITICAL_SECTION_END; // Set I bit
}

ISR(TIMER1_COMPA_vect) {
  digitalWrite(13, HIGH);
}

ISR(TIMER1_COMPB_vect) {
  digitalWrite(13, LOW);
}

Timer1.h

#ifndef TIMER1_H
#define TIMER1_H

// ========== HANDY MACROS ========== //
#define CLEAR_TCCR1A                  TCCR1A = 0
#define CLEAR_TCCR1B                  TCCR1B = 0
#define SET_CTC_MODE                  TCCR1B |= (1 << WGM12)
#define DISABLE_TIMER1_INTERRUPTS     TIMSK1 &= ~((1 << OCIE1B) | (1 << OCIE1A))
#define CLEAR_CLOCK_SELECT_BITS       TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10))

#define CRITICAL_SECTION_START unsigned char _sreg = SREG; cli()
#define CRITICAL_SECTION_END   SREG = _sreg

class Timer1{
  public:
  // Constructor:
  Timer1();
  // Begin:
  void begin();

};

#endif // TIMER1_H

This code works exactly as I would expect. I originally had placed the whole block of code found in the Timer1::begin() method in the Timer1::Timer1() constructor method. When I did this, I was getting a completely different signal (2.04 ms period with about an 80% duty cycle). Is there a simple explanation for what is occurring?

In your test code, you declare Timer1 in global scope. This means its
constructor will be called right when the program starts, even before
main() is called. The first thing the Arduino main() does is
to call init(), which configures all the timers for PWM
operation, as expected by analogWrite(). Then, any initialization of
Timer1 done by the constructor will be undone by init(). That's why
you want to defer that initialization until setup().

Edit: I took the liberty to do a code review on your post. Below are
a few suggestions. I hope some of them might be useful.

Put the empty constructor in the .h file, this avoids it being
compiled into a real empty function.
Qualify frequency, clock_pulse and opening_time as const,
and make period_ms local to Timer1::begin(). This way all the
floating point operations are performed at compile time and you
don't get all the floating point support compiled into your program.
Your CRITICAL_SECTION_* macros are redundant with
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) from avr-libc. But
then, do you really need to block the interrupts the whole time?
I don't find the other macros in Timer1.h really useful either: just
put comments next to each access to a hardware register.
I would set TCCR1B last: the timer starts counting the moment you
set this register.
You should subtract 1 from the values you set in OCR1A and
OCR1B: the period and HIGH time are OCR1A+1 and OCR1B+1
respectively.
You may want to round the period and HIGH time to the nearest
integer. It may make no difference here but you users may want to
change frequency and opening_time.
Your variables ocr1a and ocr1b serve no useful purpose, they
just needlessly eat RAM.
You casting opening_time to float, then back to unsigned int,
serves no useful purpose either.
You may want to replace digitalWrite() with direct port access, as
this function is really slow and you are calling it from an ISR.

Below is my throw at Timer1.cpp. Note that port and bit could be
made private data of the class, and the pin number could be a parameter
to the begin() method.

#include "Arduino.h"
#include "Timer1.h"

/* The three constants below can be tuned to taste:  */

const float frequency    = 10;  // hertz
const float opening_time = 25;  // milliseconds
const int   pin          = 13;

/* Nothing should need to change below this line. */

const uint16_t prescaler = 256;
const float f_timer = float(F_CPU) / prescaler;
static volatile uint8_t *port;
static uint8_t bit;

void Timer1::begin() {
    // Prepare the output.
    port = portOutputRegister(digitalPinToPort(pin));
    bit = digitalPinToBitMask(pin);
    pinMode(pin, OUTPUT);

    // Configure Timer 1.
    TCCR1A = 0;  // undo the configuration done by...
    TCCR1B = 0;  // ...the Arduino core library
    TCNT1  = 0;  // reset counter
    OCR1A  = round(f_timer / frequency) - 1;
    OCR1B  = round(f_timer * opening_time * 1e-3) - 1;
    TIMSK1 = _BV(OCIE1A)   // enable TIMER1_COMPA interrupt
           | _BV(OCIE1B);  // enable TIMER1_COMPB interrupt
    TCCR1B = _BV(WGM12)    // CTC mode
           | _BV(CS12);    // prescaler = 256
}

ISR(TIMER1_COMPA_vect) {
    *port |= bit;
}

ISR(TIMER1_COMPB_vect) {
    *port &= ~bit;
}


Arduino PWM malfunctioning I am controlling 4 motors using the PWM ports on an Arduino Uno (3,9,10,11). For some reason, the motor hooked up to port 11 doesn't move with my current code. I know it's a code issue because I can create a new basic code that just moves the motor and it works fine, but for some reason it doesn't in this code.

#include <SPI.h>
#include <Pixy.h>

Pixy pixy;

int personX = 0;
int offCount = 0;

void setup()
{
  pinMode(3, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  Serial.begin(9600);
  while (! Serial);
  pixy.init();
}

void loop()
{
  static int i = 0;
  int j;
  uint16_t blocks;
  char buf[32];

  blocks = pixy.getBlocks();

  if (blocks)
  {
    personX = pixy.blocks[0].x;
  }

  if (blocks){
    Serial.println(personX);
    if (personX < 110){
      analogWrite(11, 130);
      analogWrite(3, 130);
      analogWrite(9, 250);
      analogWrite(10, 250);
    } else if (personX > 190){
      analogWrite(11, 250);
      analogWrite(3, 250);
      analogWrite(9, 130);
      analogWrite(10, 130);
    } else {
      analogWrite(11, 190);
      analogWrite(3, 190);
      analogWrite(9, 190);
      analogWrite(10, 190);
    }
    offCount = 0;
  } else {
    if (offCount < 1000){
      offCount = offCount + 1;
    } else {
      analogWrite(11, 190);
      analogWrite(3, 190);
      analogWrite(9, 190);
      analogWrite(10, 190);
    }
  }
}

Also, when I take the motor and swap it with another, the old one works in the new PWM port, but the new one stops working once I put it in port 11.

Pin 11 is shared between both PWM and SPI. By activating SPI you've disabled PWM from working on that pin. Either use another PWM pin instead, or switch to software SPI on different pins.


How to disable the write protection of the USART mode register? I have a device which transmits USART with inverted polarity, and I would like to read data from it with the help of an Arduino. I use an Arduino Due, which has a SAM3X processor, so it should be able to invert the polarity without any external hardware.

The settings accessible from the Arduino SDK are minimalistic, Serial.begin() only allows to set the baudrate and start/parity/stop, nothing else.

In the SAM3X datasheet I found the "USART Mode Register", US_MR, which dedicates bit 23 (INVDATA) to invert the polarity.

Although it seems not to be documented anywhere, I found in a forum that to access the US_MR register, I have to use UART->UART_MR. I can read that register but cannot change it. The SAM3X datasheet mentions that this register might be write protected, and that the write protection can be cleared in the US_WPMR register.

However, the Arduino SDK doesn't seem to know about this register. I tried several possibilities,

US_WPMR
UART_WPMR
WPMR
UART->US_WPMR
UART->UART_WPMR
UART->WPMR

None of which are known.

The string WPMR is nowhere to be found in any of the files in my Arduino installation folder.

EDIT:

Interestingly, the source code for the UART class doesn't contain any reference to the WPMR. It just sets the required configuration registers without bothering with it.

void UARTClass::begin( const uint32_t dwBaudRate )
{
  // Configure PMC
  pmc_enable_periph_clk( _dwId ) ;
  // Disable PDC channel
  _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;
  // Reset and disable receiver and transmitter
  _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ;
  // Configure mode
  _pUart->UART_MR = UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ;
  // Configure baudrate (asynchronous, no oversampling)
  _pUart->UART_BRGR = (SystemCoreClock / dwBaudRate) >> 4 ;
  // Configure interrupts
  _pUart->UART_IDR = 0xFFFFFFFF;
  _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME;
  // Enable UART interrupt in NVIC
  NVIC_EnableIRQ(_dwIrq);
  // Enable receiver and transmitter
  _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;
}

However, when I try to change UART_MR, it remains the same.

Under Windows, Arduino puts the source code for hardware specific stuff in User\AppData\Local\Arduino, and not in the installation folder.

/* -------- US_WPMR : (USART Offset: 0xE4) Write Protect Mode Register -------- */
#define US_WPMR_WPEN (0x1u << 0) /**< \brief (US_WPMR) Write Protect Enable */
#define US_WPMR_WPKEY_Pos 8
#define US_WPMR_WPKEY_Msk (0xffffffu << US_WPMR_WPKEY_Pos) /**< \brief (US_WPMR) Write Protect KEY */
#define US_WPMR_WPKEY(value) ((US_WPMR_WPKEY_Msk & ((value) << US_WPMR_WPKEY_Pos)))

I would guess unlocking / locking would take the format:

????->US_WPMR = (US_WPMR_WPEN | US_WPMR_WPKEY(0x555341));
????->US_WPMR = (~US_WPMR_WPEN & US_WPMR_WPKEY(0x555341));


How to use Atmega1284AU with Arduino IDE Is there any support to this chip in Arduino IDE, like bootloaders and boards definitions.. i want to use this chip with 3.3V and 8Mhz crystal speed..

I have seen Nick Gammon bootloaders supports this chip for bootloaders, but not with 8Mhz.? and how to add this chip to Arduino IDE.

anybody help..

thanks you

Please check out MightyCore library by MCUdude.

https://github.com/MCUdude/MightyCore

I have used it and can verify it works pretty well with ATmega1284.


why can Arduino variables of int type contain a value such as A2 How come the following statement is true:
int inputPin = A2;

I thought int variables can only hold integer numbers. Is the A just a representation of a number?
Thanks for any help

You are correct. A2 is just a number (like everything in a microcontroller). We can look at the corresponding part in pins_arduino.h (a file defined in the variants folder of your used core and of your used board, for me: ~/arduino-1.8.9/hardware/arduino/avr/variants/standard/pins_arduino.h):
#define PIN_A0   (14)
#define PIN_A1   (15)
#define PIN_A2   (16)
#define PIN_A3   (17)
#define PIN_A4   (18)
#define PIN_A5   (19)
#define PIN_A6   (20)
#define PIN_A7   (21)

static const uint8_t A0 = PIN_A0;
static const uint8_t A1 = PIN_A1;
static const uint8_t A2 = PIN_A2;
static const uint8_t A3 = PIN_A3;
static const uint8_t A4 = PIN_A4;
static const uint8_t A5 = PIN_A5;
static const uint8_t A6 = PIN_A6;
static const uint8_t A7 = PIN_A7;

So here the core first defines the macro PIN_A2 as 16 (which is the pin number of that pin) and then it declares a static constant A2 with PIN_A2. So A2 is just the pin number of that pin, 16 in this case.
This is done to make the code more readable. The analog pins are marked with A0 to A7, so it is good to also be able to refer to that with these names. If you wanted, you could also use the pin number directly. But that wouldn't be as easy to read.


ESP-12e - RX/TX pins flickering on boot when used as GPIO pins I am using ESP-12e as a controller for my garden lights. I am using pins 1 (TX), 3 (RX) and 5 as an analog output (PWM signal with mosfets) for three separate light sets. ESP is powered on when wall switch is turned on (wall switch turns on power adapter). When I turn the switch on, for short period of time lights connected to pin 1 and 3 work at full power and after that they are set according to PWM signal. Lights on pin 5 works just as expected. I am not using Serial communication, just elegantOTA library for OTA updates and async web server. Is it possible to somehow disable RX/TX functionality at all/before they are set to high, or I am forced to solder lights on pins 1 and 3 to another ones? I tried some software tricks I found online, but without success.

According to this reference, GPIOs 1 and 3 have dedicated behaviour during boot (debug output or pulled high) which can not be disabled in your sketch.
You have to either choose different pins or implement an additional circuitry.


Shield Compatible third party motor driver I recently purchased an Arduino UNO along with some other hardware. At the time of purchase, I didn't know about Arduino's motor shield and so I purchased a two channel stepper motor driver (2A per channel) that was said to be "Shield Compatible". I recently received my hardware and have been following the introductory tutorials since I'm completely new to the Arduino platform. Things are going well but I didn't receive any documentation with the motor driver. There is a datasheet provided on the vendor's website but it is beyond my current level of competency.

My question: since the driver is said to be "Shield Compatible", does this mean that I can assume that I can interface with it the same way as an authentic Arduino shield. In other words, can I follow the motor shield tutorial on Arduino's website without any risk of damaging hardware and expect the driver I purchased to function properly.

The product that I purchased can be seen here: http://www.robotshop.com/ca/en/dual-bipolar-stepper-motor-controller-arduino.html

You should do you own research as the path followed here did not result in the identically pictured nor identically model numbered item.

You indicated you are using a certain Arduino motor driver board.  On that page there is an "made by" or "by" reference to an OEM.  On the OEM's web page there is a "Dual Bipolar Stepper Motor Shield for Arduino" but the part number and the picture do not (exactly) match your original link.  Regardless, there is what they are calling a "WIKI page" for this (slightly) different motor shield.  I scanned this page and the example code.  I don't see where any device driver is mentioned.  And I don't think the code will compile by its self.

In general, I suggest people who are starting out with Arduino's to stick with well known hardware and software.  Even then I have had problems with newly released hardware.  Also check if drivers and SDKs have been updated each time you start a project.

Another approach you might entertain is to follow a path starting with the chip used on your shield.  It appears to use two DRV8825.  (But I cannot be sure as pictures and model numbers do not (exactly) match.) Here is a discussion on the a well known Arduino web site where people are talking about boards with this chip on it.


Servo motor sweeps beyond 180 I'm trying to get my servo motor to sweep from 0 to 180 degrees then back to 0 degrees for infinite amount of times. I using the following code but my motor keeps resetting when it get backs to 0 degrees (meaning it goes 0-->180-->0 then completes a 360 and starts over). Also the 0-180 degree sweep appears to be more of a 0-270 degree sweep. Anyone running into these problems?

int angle = 0;

void setup() {
  myservo.attach(9);
  myservo.write(angle);
}

void loop()
{
  for (angle = 0; angle < 180; angle += 1)
  {
    myservo.write(angle);
    delay (50);
  }

  for (angle = 180; angle > 0; angle -= 1)
  {
    myservo.write(angle);
    delay(50);
  }
}

Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?


What happens if I try to draw power from the VIN port while under USB power on an Uno? I would like to have a shield permanently attached that use the VIN (not 5v) for it's power - the problem comes in when I want to program the arduino (via the USB port), do I need to also have the barrel connector plugged in, or can I just expect the shield to not work (no, it won't be damaged from not getting enough/any power), but have the arduino itself be fine - or am I somehow damaging the power regulator by attempting to use it in reverse?

You do run the risk of damaging the 5V regulator, yes.

Power will attempt to flow from the 5V rail (USB port) through the voltage regulator (backwards) and into the shield to power it.

As your shield doesn't mind being under-powered from 5V while you're programming the Arduino you can add a diode between 5V (anode) and Vin (cathode). This will bypass the regulator when the voltage of the 5V rail is higher than the Vin rail, and your shield will be supplied with about 4.3V (slightly higher for a schottky diode).


RAM cost of entering functions A friend has told me I shouldn't rely on functions because, during execution, they occupy a significant amount of RAM.
Is that true or, if it isn't, what's the maximum suggested level of function nesting at runtime?

I guess avoiding functions may have been relevant with dumb compilers, a
few decades ago. Compilers today are pretty good at optimizing and,
since recently, the Arduino environment enables “link time
optimization”. This means the optimizer can see the whole program at
once, which enables:

function inlining across compilation units (and the optimizer does
this pretty aggressively)
saving, in the function prologue, only the registers that really need
to be saved.

In most cases, the “optimal” size for a function is whatever size
optimizes the readability of the code. In the rare cases where you would
need to merge a function into its callers for performance purposes, you
can qualify the function as
inline __attribute__((always_inline))

But this only makes sense after you disassembled the program and noticed the
compiler did not make the right optimization choices. A quite infrequent
situation.


Arduino bluetooth module as a server I was looking around becouse I need to simulate a OBDII device. I think about to use Arduino for that. I was reading some tutorials how to use bluetooth module but I didn't find any tutorial when Arduino is a server. Alway Android app is a server. Is there way to put SP server in Arduino and Android as a client? And do I need special shield/module for that? If you could gave me some links to tutorials or code would be grate.
Interesting for me would be also possibility to send data form computer by USB to Arduino then Arduino push it forward to Android. - but that is not must have, first possibility is more importand for me.

There are two types of bluetooth devices for Arduino. Some are "slave" only and some are both "master or slave".

There is little difference in price so you should buy one that is master or slave.

This page (HC-05) describes one that appears to be commonly used but there are many and I do not have a recommendation. Some devices are in the form of small boards which connect to the pins on the Arduino (normally serial tx/rx) and some are shields that plug onto an Arduino. The article also shows the connection.

This appears to be an ODBII bluetooth arduino forum thread that uses bluetooth and ODBII. Video

By default Android is in bluetooth master mode. This article appears to show the Android programming required to enable a bluetooth slave.


Strange RPM Readings on Teensy 3.2 While trying to read RPM from a computer fan using the 4-wire protocol, I am getting strange readings. +12 and GND from the fan are connected to a power supply, and the tachometer to the PIN-0 or a Teensy 3.2.

I wrote code to read the tachometer pulse using the internal pull-up and interrupts. The strange thing happening is that the number of recorded revolutions is increasing as I manually slow the fan using my fingers.

Here is the code :

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

const int fanPulse = 0;
volatile long half_revolutions;
elapsedMillis timeElapsed;

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

  pinMode(fanPulse, INPUT_PULLUP);
  attachInterrupt(fanPulse, rpm_fun, FALLING);

  half_revolutions = 0;
  // analogWriteFrequency(20, 25000); // Teensy 3.0 pin 3 also changes to 375 kHz
}

void rpm_fun() {
  half_revolutions++;
}

void loop() {
  if (timeElapsed < 1000)
    return;

  Serial.printf("%d revolutions in %d miliseconds\n", half_revolutions / 2, (unsigned long)timeElapsed);

  timeElapsed = 0;
  half_revolutions = 0;
}

Here is the strange output :

0 revolutions in 1000 miliseconds  // Start
0 revolutions in 1000 miliseconds
82 revolutions in 1000 miliseconds
394 revolutions in 1000 miliseconds  // "normal" reading
412 revolutions in 1000 miliseconds
576 revolutions in 1000 miliseconds
456 revolutions in 1000 miliseconds
554 revolutions in 1000 miliseconds
585 revolutions in 1000 miliseconds
799 revolutions in 1000 miliseconds  // Slowing the fan
712 revolutions in 1000 miliseconds
691 revolutions in 1000 miliseconds
683 revolutions in 1000 miliseconds
625 revolutions in 1000 miliseconds
531 revolutions in 1000 miliseconds
239 revolutions in 1000 miliseconds
0 revolutions in 1000 miliseconds
0 revolutions in 1000 miliseconds  // End

Without the ground of the teensy connected to the ground of the fan all you will be measuring is noise. Ground is required to complete the circuit between the teensy and the fan.


Most efficient method to turn a gear extremely slowly? I have a gear that needs to have roughly one rotation per day.  It does not have to be smooth or consistent.  So far, the best I have come up with is to have a stepper motor with an arduino that sleeps, wakes up once an hour maybe and turns the stepper a little bit.

Which arduino should I use for this and is there perhaps a simpler method?  Is there any way to fully cut power then when powered on the arduino advances the motor and then shuts off?

Any ideas?

I want to run off of a 9v battery and get as much time as possible.

edit: adding details as requested

the rotation needs to happen slowly over the 24 hour period.  The tube being turned is a light plastic 1" diameter tube that weighs about 2 lbs.

Steppers require current - and power, due to I^2*R losses) to hold a position. Power off, they free-wheel. What kind of efficiency do you need? A stepper might not be the most power efficient.

An escapement permits or causes a gear to index one position and prevents it turning any farther. In a clock, it permits a weight-driven or spring-driven shaft to index. You'll probably want one that drives the shaft as well, probably with a solenoid.

Another option that comes to mind and doesn't need an Arduino, is a clock motor. Gear down the hour hand 2:1 and you're done. Find a 24-hour clock motor and even that gearing will have been done for you.


Measuring ADC sample rate - Arduino DUE I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode.
Hints are welcome, I really don't know where to start.

I think using an interrupt controlled measurement might provide the best results for you.

Note: you might get more complete feedback using the Arduino forum.

In general the process would look like this:

Set up an interrupt vector for the ADC peripheral (in this case support for ID37).
Setup ADC registers (res, clock etc)
Set up a timer to time the conversion.
Create Active flag and Timer variables for processing inbound timer values.
Start timer and ADC conversion.
Loop waiting for active flag to set (it gets set in the ISR), when detected do average or store timer values, then clear active flag.

This methodology times each individual conversion using a high speed timer, which could mean a lot of values to process. You could equally not time each conversion, but simply set up say a 1 second timer, and count the total number of conversions in 1 second for your particular ADC configuration.

Peripheral ISR

Waiting for Interrupt.
In peripheral ISR, read and store timer value, reset timer, set active flag
Return from ISR


How to chose softserial library use on Arduino project? I want to do a project that has multiple Arduino communication through UART, that project project one of limit is using Arduino Nano (small and cheap). I need to set 4 serial port instance on Nano to connect other nano to receive and write, I searched about serial port of nano that only have one hardware serial port, so after I found the many softserial library such as pre-bulite softserial and altsoftserial NeoSWSerial and NeoHWSerial and NeoICSerial.
Because library too libraries i don't know which one can help complete my project.

I think your problem is that you need 4 serial ports.

With software serial that's just not going to happen:

SoftwareSerial can only receive on one serial port at any given time.
AltSoftSerial is limited to specific pins, and only one instance because there is only one set of pins
NeoSWSerial is kind of between the two. More efficient than SoftwareSerial, but still (as far as I can tell) limited to one instance (it uses a timer interrupt to drive the communication, so can use any pins)

If you need communication between lots of devices over serial then you will either need devices with more hardware serial ports (Arduino Mega, for example), or implement a multi-drop bus system (like RS-485) which only needs one serial port to communicate with many devices. Extra external hardware is required though.


Problem with Micro SD card breakout I was connecting my arduino uno to a adafruif micro SD card breakout and everything worked just fine, i could read the sd, write to it and see all the info about it. To do it i just followed the tutorial in here.

My problem is that when I arrived home the exact some thing wouldn't work and I couldn't read the SD card anymore.

I was thinking it could be a bad contact problem since sometimes i get:

Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

And other times (almost never), i would just get:

Initializing SD card...Wiring is correct and a card is present.
Card type: SD2
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

I would like to know if I can assume it is the breakout board failling and I would buy a new one, or if it can be any other thing.

Thank you in advance!

Did you try:

Reading the SD card in your computer ... if  you can read (or write) files, that means the SD card is intact
Use a SD card that worked before or similar. Some bigger SD cards (like SDHC, SDXC have less good compatibility). Preferably use a 2 GB or smaller card (unless you have used bigger cards successfully and of the same or smaller type, e.g. SD, SDHC, SDXC).
Try different formattings, like FAT, FAT16, FAT32. I think FAT is the mostly recognized formatting.
Check connections/wires to/from SD breakout, maybe during your leave accidentally you (or someone else) or due to pressure/tension, a contact/wire got loose.
Check another SD card in the SD breakout where the SD card you know is good. If this also does not work, it must be the breakout (or Arduino).
Replace every piece of hardware (including wires) one by one and recheck if it works (after you are sure the SD card itself is ok).


MQTT connection not being recognised in void loop() I am trying to publish MPU 9250 readings in the Adafruit IO sending the data from ESP32. The WiFi connection is being established, but the code is not going inside the if(mqtt.connected()) inside the void loop() whereas it's going inside the same command inside the void setup().
I am sure there are no connection issues because once I change if(mqtt.connected()) to while(mqtt.connected()) inside setup(), code is going inside the while loop continuously.
Why is the code not going inside the if command and how can this be solved?
#include <WiFi.h >
#include <Adafruit_MQTT_Client.h>
#include <MPU9250.h>

#define wifi "********"
#define password "********"
#define server "io.adafruit.com"
#define port 1883
#define username "*******"
#define key "********"

WiFiClient esp;
MPU9250 IMU(Wire,0x68);
Adafruit_MQTT_Client mqtt(&esp, server, port, username, key);
Adafruit_MQTT_Publish feed = Adafruit_MQTT_Publish(&mqtt, username"feeds/accelerodata");

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println("Adafruit MQTT Demo");
  Serial.println("Connecting to");
  Serial.println(wifi);
  WiFi.begin(wifi,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Connecting to MQTT");

  if (mqtt.connect()) {
    Serial.println("MQTT Connected");
  }
}

void loop () {
  Serial.println("Test line to check if code reaches inside loop");
  delay(1000);

  if (mqtt.connected()) {
    int data=IMU.getAccelX_mss();
    Serial.println("\nSending accelero data");
    Serial.println(data);
    Serial.println("....");
    if (feed.publish(data)) {
      Serial.println("Success");
    } else {
      Serial.println("Fail");
    }
    delay(800);
  }
}

I believe your problem is that you are attempting to use the MQTT connection before it's actually connected.  So your check:
if(mqtt.connected())

is always FALSE since it's not really connected.  The Adafruit library information here:
Adafruit MQTT
Says to initialize MQTT as:
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
  }
  Serial.println("MQTT Connected!");
}


less expensive alternative arduino board to CMUcam4 Is there any similar (less expensive alternative) arduino board to CMUcam4?

CMUcam4:The CMUcam4 is a fully programmable embedded computer vision sensor. The main processor is the Parallax P8X32A (Propeller Chip) connected to an OmniVision 9665 CMOS camera sensor module.

I have used OpenCV on Intel Galileo for doing recognition of sub images from a larger image (given the cover of a magazine, identify it in a pile of magazines partially covering it). The frame rate is far from stellar.
I haven't tried with Edison but it should be much faster, as it's an Atom core vs the pentium-like Quark. OpenCV is optimized for x86.

I used a normal webcam to capture the image, so this solution gives more flexibility in the choice of the sensor.

You could have a look at ROS on Edison.


Using Arduino Mega with multiple HC05 Modules as masters, communicating to multiple HC05 Modules as slaves, each connected to separate Arduino So I have not actually experimented with the HC05 Bluetooth Module yet, but I have read up about it and watched some videos. From what I understand, you cannot use one module (master) to communicate with more than one other module (slaves), or at least its pretty difficult. But, you can use a module hooked up to an arduino to communicate to to another module hooked up to another arduino (I believe pretty simply).

However, I thought it might be possible to use an Arduino Mega (because it has multiple TX/RX pins) with 3 HC05 Bluetooth modules, to each communicate to 3 separate HC05s which would each be hooked up to an arduino nano. I know this might have to do something with running multiple Software Serials (I have no idea what that is to be honest)?

The project involves using the master arduino to "listen" for a button pressed on the slave arduino (across the room without connecting wires), then listening for another button press from one of the other slaves in some sort of sequence and within a certain time frame.

Does anyone have any idea about how this might be done, even if it doesn't use the HC05 Bluetooth Module?

Thanks!

Yes, this is possible. According to arduino.cc, the Arduino Mega has 4 hardware serial ports, so you can connect 3 HC-05 modules and still have 1 serial interface left. The Mega is a good choice, when you need this many serial interfaces, so at this point you don't even need SoftwareSerial. You will have to configure the HC-05 modules correctly from the master and command them to connect to the correct slave modules.

About SoftwareSerial: The serial interfaces mentioned above are "hardware" interfaces, meaning, that the itself microcontroller contains hardware, that does the main part of the receiving/transmitting by itself, without any need for code. The Serial library then only adds a bigger buffer for the data, wrapper functions to write to it and reacts to the interrupts, that come from the hardware interface. But since most microcontrollers only have a very limited number of hardware serial interfaces (often only 1 or even none), the SoftwareSerial library comes in handy. It emulates the UART protocol (which is a more professional term for the Serial interface from the Arduino world) with software (and some help from interrupts). This means, that you can use it with any pair of pins and you can even define multiple interfaces with it. But it also has drawbacks. For example: Only 1 SoftwareSerial interface can listen at once, you cannot use high baudrates, it uses interrupts, that you might need for an application.

That said, I don't think, that Bluetooth is the best way to go, if you only want to test a small number of buttons per slave. It is simply too much hassle to configure the modules and establish the connections correctly. Instead you can use 433MHz radio modules. They don't involve such a complex protocol like Bluetooth does, so it's a very simple solution. In the simplest case, you only need transmitters for the slaves and a receiver for the master. Every slave can send a short identifier, if the button was pressed. The master can then receive this data. Of course, if more than one slave sends simultaneously, the data will be garbage. But as long, as this is not a problem, you can keep it that simple.

There are many tutorials on the web, that explain how to use these modules. You can even find libraries, that are ready to use.


Soft debouncing from an interrupt during stand-by My current setup has the arduino in 'stand-by' power saving mode, therefore i am unable to use any means of a traditional soft debouncer, such as Bounce2, as far as I know.

I went ahead and attached the buttons to pin change interrupts, since I have one button on each bank, i.e. pin 7 and pin 11.

The technique I'm using doesn't seem to be behaving since the routines are being fired too regularly (inconsistently), and at the rising edge too.

I have the pins set to use their internal pull-ups.

Using the PCI library:

void pciSetup(byte pin)
{
  *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
  PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
  PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the

pciSetup(POWER_SWITCH);
pciSetup(SELECTOR_BTN);

// check if IR IN or Power switch
ISR (PCINT0_vect) // handle pin change interrupt for D8 to D13 here
{

  if (digitalRead(POWER_SWITCH) == LOW)
  {
    noInterrupts();
    unsigned long last_millis = millis();
    while (millis() - last_millis >= 500);
    ir_power_pressed = true;
  }
  interrupts();
}

ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7
  noInterrupts();
  unsigned long last_millis = millis();
  while (millis() - last_millis >= 500);
  ir_selector_pressed = true;
  interrupts();
}

Am I doing something silly?

Update 1

As suggested in the comments, i've adjusted the code, but it still triggers on the rising edge, and a few times rapidly at the falling edge.

ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7 here
{
  if (digitalRead(SELECTOR_BTN) == LOW)
  {
    noInterrupts();
    static unsigned long last_millis = millis();
    if (millis() - last_millis >= 500)
    {
      ir_selector_pressed = true;
      interrupts();
    }
  }
}

You don't update last_millis.
Also, you don't know whether SELECTOR_BTN went from HIGH to LOW or whether another pin fired the interrupt while SELECTOR_BTN was low. Remember the previous state to solve this.

const unsigned long debounceTime = 50;
volatile bool ir_selector_pressed = false;

ISR (PCINT2_vect) { // handle pin change interrupt for D0 to D7 here
  static unsigned long previousStateChangeMillis = 0;
  static bool previousPinState = HIGH;

  bool pinState = digitalRead(SELECTOR_BTN);
  if (pinState != previousPinState) { // ignore pin changes of pins other than SELECTOR_BTN
    if (pinState == LOW) { // only falling events
      if ((millis() - previousStateChangeMillis) > debounceTime) { // debounce
        ir_selector_pressed = true;
      }
    }
    previousPinState = pinState;
    previousStateChangeMillis = millis();
  }
}


Remove all items from an array i'm trying to remove all the data i've in an array.
Example:
I've arr[5,3,2] and i want to clear the array totally and finish with an array like this arr[], ready to add new values. How can i do that? Thanks in advance.

The easiest way is not to create a new (dynamic) array every time you need one, but create one array (like you probably have). However, an array always has a fixed length, which is defined during declaration. An easy way to denote that e.g. only the first 10 items are filled, is to create an integer variable, that has value 10, which means that from the array (e.g. int myArray[20] only the first 10 values are saved. Whenever you add a new value in the array, use

myArray[filledSize++] = newValue;

This will add the new value at array element [filledSize] and increase the filledSize. You can add protection that filledSize should never be more than the size of the array.

To clear an array you simply use

filledSize = 0;

And whenever you iterate through the array you use

for (int elem = 0; elem < filledSize; elem++)
   {
       myArray[elem] ...

However, in many cases you want a ring buffer, I will not elaborate on it, but maybe you can check into this, to see if this is more appropriate in your case.


Simultaneous button reading? I'm currently working on a project that requires that I simultanously check the state of two buttons. Each button HIGH state is assigned to one if loop. Here's the basic concept:

void loop() {
  S1_State = digitalRead(S1_Pin);
  S2_State = digitalRead(S2_Pin);
  ButtonPRESSED = false;

  P1_Time = random(2000, 5000);
  delay(P1_Time);
  digitalWrite(P1_Pin, HIGH);

  while(ButtonPRESSED == false) {
    if (S1_State == HIGH) {
       Serial.print("Player 1 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }
    if (S2_State == HIGH) {
       Serial.print("Player 2 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }

The problem is that checking for the button states this way requires that the S1_State loop _has to be read before the S2_State loop_, thus giving player 1 an advantage. Although I'm not sure how pronounced this issue is in practice, it certainly was noticable when I was first trying this project out through python code on a Pi through similar means.

Is it possible check the conditions to both if loops simultanously? If not, are there other ways to circumvent this problem?

Instead of using the high level digitalRead() function access the low level port registers. See this documentation.

A port register is one byte and each bit represents one of the digital inputs on the arduino.

Do something like this:

pin_status = PIND; //Input port D (pins 0-7)
button_1 = bitRead(pin_status, 2); // digital pin 2
button_2 = bitRead(pin_status, 3); // digital pin 3

The values are read simultaneously so it is possible to have a tie.


I2C LCD Serial Interface Board not displaying text The code dont gives error, but not displays "Hello World"

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  // initialize the LCD
  lcd.begin();
  // Turn on the blacklight and print a message.
  lcd.backlight();
  lcd.print("Hello, world!");
}

void loop() {
}

This can be due a lot of reasons, among:

Most common:

Backlight is set too low (there should be a small dial)
Circuit problem (recheck), and post it.
The I2C address is wrong, there are sketches to check it.

Less common:

Broken LCD
Broken Arduino
No power on Arduino (check LED)


How to have code/sketch that's easily toggleable to work on different nodes i have a question about best practice to achieve what i want to do. I would like to have a sketch setup, and then to be able to deploy to different devices of the same type, but each device/node will have a few different parameters, like ip address and mqtt topic etc,

What would be the quickest way to be able to upload new changes to all of my nodes without having to track my changes and update each seperate sketch for each node?

I was thinking about using some IFDEF statements if i can figure out how to? would that be the best way to go or is there something better?

Thx in advance

You can put the per-node parameters in a external EEPROM and load them during setup(). For example the IP address is the first 16 bytes of the eeprom (IPv6), the next bytes would the the topic, etc..

That way every node has exactly the same sketch and the customization is in the eeprom that you could put in a socket and possibly have a separate programmer for them.

EEPROMs with I2C interface are easy enough to get and can store 64kB. Which should be more than enough for most things.


ESP32 and wifi router I connected my ESP32 to Wifi and I can see this in my Wireless Statistics:
ID |       MAC Address      |Current Status| Packets Received | Packets Sent | SSID
1  | 3C: 71: BF: 0D: CB: 00 | Connected    |         52       |       47     |mySSID

I can ping via IP but I can't see ESP device in the DHCP list or ARP.
Could you explain why? And how I can fix this?

I made a binding IP and MAC and now I see my ESP)


0 value integer does not enter If I'm sure this is a very basic coding mistake...

I'm picking up a reading from A0. If the value is 0, I want the value of the serial to be written to the Serial Monitor.

I also want it only to write to the Serial Monitor for the first time that the value falls to 0.

I don't understand why, when the value for SensorValue = 0, the if is not performed.

This is my code:

boolean must_print = true;
int sensorValue = 0;

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue = 0) {

     if (must_print = true)
    {
     must_print = false;
     Serial.println(sensorValue);
    }
  else
    must_print = true
  }

   delay(500);        // delay in between reads for stability
}

Thanks!

if (sensorValue = 0) {

That assigns zero to sensorValue, which then tests false. You want:

  if (sensorValue == 0) {


Why doesn't the Micro OLED library compile on my DUE? I have an Arduino DUE and just got a Micro OLED display from SparkFun.

Using their library, when I try to compile I get the error below.  Other example code works just fine and I've programmed this thing a million times with my code.  So it's clearly in the SparkFun code.

Here is the SparkFun tutorial page with a description of the product:

https://learn.sparkfun.com/tutorials/micro-oled-breakout-hookup-guide?_ga=1.19136059.2055231411.1404437767

Here is the library I am using:

https://github.com/sparkfun/Micro_OLED_Breakout/tree/master/Firmware/Arduino/libraries/SFE_MicroOLED

Here is the error I get:

Build options changed, rebuilding all

/Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::spiSetup()':

/Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:46:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    ssport  = portOutputRegister(digitalPinToPort(csPin));
            ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:48:51: error: 'portModeRegister' was not declared in this scope
    ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                     ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::i2cSetup()':
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:84:2: error: 'TWBR' was not declared in this scope
    TWBR = ((F_CPU / I2C_FREQ) - 16) / 2;
    ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp: In member function 'void MicroOLED::parallelSetup()':
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:109:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    ssport  = portOutputRegister(digitalPinToPort(csPin));
            ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:111:51: error: 'portModeRegister' was not declared in this scope
    ssreg  = portModeRegister(digitalPinToPort(csPin));
                                                     ^
  /Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:114:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    wrport  = portOutputRegister(digitalPinToPort(wrPin));
            ^

/Applications/Arduino.app/Contents/Resources/Java/libraries/SFE_MicroOLED/hardware.cpp:119:10: error: cannot convert 'RwReg* {aka volatile long unsigned int*}' to 'volatile uint8_t* {aka volatile unsigned char*}' in assignment
    rdport  = portOutputRegister(digitalPinToPort(rdPin));
            ^
  Error compiling.

That library is uses some AVR specific methods, that aren't implemented for the ARM processor in the Due.

I don't see a real easy way to port those methods.


How to give an analog output of 0-5V I'm trying to program an Arduino to control a motor at different intensities by giving a 0-5V reference value from the board. I have some programming experience, but have very little knowledge of manipulating an Arduino or about electricity. As I understand from reading this, I need to call the AnalogWrite function to output the signal, but how do I do this? How can I control when the voltage (and by extension, the motor intensity) is increased or decreased. Is it possible to do this without additional hardware?

Any help is much appreciated, it doesn't have to be code. I mostly want to understand how to use the Arduino, but code would also help a lot with that. I'm using an Arduino Due, which as I understand, has true analog out.

You would indeed need to use analogWrite to send a PWM signal to the motor. PWM will turn on and off the power to the pin really fast. In effect powering the motor with pulses. The length of these pulses will determine how much power the motor receives.

The DUE also has a true analog output, but you don't want to use that for motors. The use of the word analogWrite is a bit misleading when it's used for generating a PWM signal.

analogWrite will ask for a value between 0 and 255 to indicate the pulse length. 0 is OFF, 255 is full ON, 127 is ON for 50% of the time.

Also note that most motors require more current that the Arduino pins can provide, so you need to use a transistor/mosfet to "amplify" the signal to a higher current.


Dust sensor code with a few errors I'm fairly new to this and I'm having trouble with a code for a dust sensor. Getting a couple of errors. I downloaded this code from GitHub.
Anyone have any idea how to fix any of these errors? Any help is appreciated.
Sorry if this formatted wrong, this is also my first post. Thanks for your time

// SDS011 dust sensor example
// -----------------------------
//
// By R. Zschiegner (rz@madavi.de).
// April 2016

#include "SDS011.h"
#include<SoftwareSerial.h>
SoftwareSerial myserial(0, 1);
SDS011(byte pin_rx, byte pin_tx)
float p10,p25;
int error;

SDS011 my_sds;

void setup() {
  my_sds.begin(0, 1);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
}

void loop() {
  error = my_sds.read(&p25,&p10);
  if (! error) {
    Serial.println("P2.5: "+String(p25));
    Serial.println("P10:  "+String(p10));
  }
delay(100);
}

here are the errors I'm getting

code:10: error: expected ')' before 'pin_rx'

 SDS011(byte pin_rx, byte pin_tx)

             ^

C:\Users\Nick\Desktop\code\code.ino: In function 'void loop()':

code:26: error: 'p25' was not declared in this scope

   error = my_sds.read(&p25,&p10);

                        ^

code:26: error: 'p10' was not declared in this scope

   error = my_sds.read(&p25,&p10);

                             ^

exit status 1
expected ')' before 'pin_rx'

You have to use the begin command. Instead of:

SDS011(byte pin_rx, byte pin_tx)

...

SDS011 my_sds;

Use

SDS011 my_sds;

(Thus remove the first line: SDS011(byte pin_rx, byte pin_tx)).

And in setup add:

my_sds.begin(0, 1);

This follows the library function of SDS011:

void begin(uint8_t pin_rx, uint8_t pin_tx);

Other errors: because you forgot the ; in

SDS011(byte pin_rx, byte pin_tx)

the next line:

float p10,p25;

is misinterpreted, and p10 and p25 are not known. Therefore errors are shown while trying to use p10 and p25.

These errors will go when changing the begin code as described earlier.


Simple question about && vs || I want to skip all '\r' and '\n' chars and I have IF statment:

char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

VS

char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

What is better and what is the difference?

Think about it "logically" (pun intended...):

You read a character.  Say it's "A".  You then compare it to both '\r' and '\n'.

char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR or A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR or CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  If it's OR, then if either part is true then it will be true.  So since CR is not LF it will add it.

Now:

char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR and A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR and CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  Just as before.  However, if it's AMD, then if BOTH parts are true then it will be true.  So since CR is CR it won't add it.

In summary, the first one will ALWAYS be true since one half is always going to be true.  The second one will ONLY be true if BOTH parts are true.  So the first one just plain isn't going to do what you want.


Where is the Arduino IDE log file located? Not the Serial Monitor "An error ocurred while uploading the sketch"
I'm having this specific error when uploading a sketch to my board and the IDE doesn't specify the problem correctly.
It's version is 1.8.13 for Windows 10.
I would like to get a file with detailed information about the IDE's error. Where should I look for it?

There is no log file. Instead you need to turn on both "compilation" and "upload" under the "Show verbose output during:" option in Preferences.
This will give you far more information about any errors in the output scroll pane at the bottom of the IDE.
On Linux if you run the IDE from the command line you get large amounts of logging on stdout. There may be a way of doing the same from Windows.


Accuracy of liquid level measurement using sonar sensor Is it a good way to measure liquid level in a water tank using a general purpose sonar sensor? How can echoes from the tank walls affect measurement accuracy?

I have a cylinder shaped horizontal 700L water tank, used for emergency water supply. I need to measure the water level with approx. 5% accuracy and display it in my kitchen.

UPDATE! Today I found this helpful page: Home Heating Hacking Part 1 or How to Measure an Oil Tank.
I had no time to realize my idea, but it's exactly what I wanted to do. So take a look.

I've implemented this on my 2 x 23,000 litre water tanks using 2x hc-sr04 sensors mounted on the tank lids and a nano in the pump house. Yes water is a good hard reflective surface to bounce the ultrasonic sound waves off. My tanks have an overflow outlet but not sure how well the eletronic will last? However they are cheap to replace. It is only early days but the overall the results are looking good.
Couple of points:

1.polling occurs hourly.

2.I only power the ultrasonic sensor just before taking a reading.

3.Has a sound detection sensor to alert on water pump overrun, ie a leak.

good luck


How to make precise square wave? I am playing with stepper motors and I need a precise square wave generator for f=29.710617283951Hz. I've done this on Raspberry Pi without any problems, but I need something smaller and with less power consumption.

Is it even possible to get that frequency?

Reducing the power requirement, compared to an R-Pi, should be straightforward, achieving 29.7106Hz is doable, reducing the size is harder (an R-Pi is quite compact).

Some of the available options depend on your electronics skills, and budget.

I'll assume you want to use off-the-shelf hardware as much as practical, but are okay to wire 'modules' together (size could be a bit smaller than an R-Pi using off-the-shelf parts, but could be significantly reduced by a custom made part).

I'll also assume you want to keep costs under $100. (I apologise if I am wrong, but this seems like a level that many of this community might find interesting :-)

Preamble:

Even at 16MHz, 29.7106Hz represents a count of approximately 538,528, which requires 19 bits. So I would not use a chip with 8 or 16 bit timers. I would make my life easier by using a chip with 32 bit timers.

Further, the code will be manipulating quantities with at-least 19 bits, so I would not use an 8 or 16bit CPU. I would make my life easier by using a 32bit CPU that operates on 32bit quantities in a single operation. This may become very important if you opt for a software-heavy approach.

Initial Approach:

Lets assume our 32 bit processor has a clock of 64MHz.
To generate a clock frequency close to 29.710617284Hz (as good as my calculator will do), load a timer with 2,154,112 (maybe 2,154,111, depending on how the counter triggers).

The more accurate divisor is 2,154,112.094.

That count is within 0.05ppm (parts/million) of 29.710617284Hz at a 64MHz clock.
Also, a count of +/- 1 is a change of less than 0.5ppm. That is about 30x better than the more relaxed requirement, '29.7106', mentioned in your comments.

Using 64MHz to drive the count will enable 4x better accuracy, 0.5ppm, than using a 16MHz clock, 2ppm, when we examine ways to implement this in the 'Options' section below.

Summary so far: if the microcontroller had a very accurate clock (much better than 0.5ppm error), then the problem is solved.

However, the crystals used to drive the microcontroller typically have a frequency stability of 30-50ppm, and may be even worse.

Options to reach 0.5ppm:

1. Replace the MCUs crystal with a much better part.
This will typically require some soldering skill, and the parts I've seen (which are likely to replace the existing crystal) are stable at about 10ppm. That might be a factor of 3-5 better than the factory fitted crystal, so may be worth the effort, however there are better options.

2. Feed the MCU with a higher-stability clock source than a crystal.
Most MCU's can accept an external clock source in place of the crystal. Temperature Compensated Crystal Oscillators (TCXO) cost about $5, and can achieve 0.5ppm (0 to 40C, 2ppm -30C to +85C). So an improvement over an 'ordinary' crystal of 30-100x.

If this is appealing, I'd actually recommend looking at ST Micro's Nucleo boards. They are low-cost (under $12), so not much wasted if it doesn't work, and many of the boards already take an external oscillator, so may be easier to change. (They are 32bit CPU's with 32bit timers, and can run at 64MHz,) I imagine folks can recommend other boards.

3. 'Discipline' the square-wave counter with an external high-quality clock
The idea is to use a very accurate external clock, and adjust the square-wave count to get high-accuracy than the existing MCU crystal. While counting the MCU clock for the square wave, use a second counter to count the number of MCU clock cycles a known, high-quality, external timing source event takes. The external clock source could be a TCXO, an Oven Controlled Oscillator (OCXO), which can achieve 0.001ppm) or GPS.

Program code could estimate the error of the MCU clock vs higher-quality clock, and adjust the square-wave count within each square-wave cycle. This may keep the square-wave within 0.5ppm using one or more +1 or -1 adjustment of the counter. This approach has the advantage that the only electronics is connecting the high-quality timing source to a pin on the microcontroller. The rest is (carefully written) software.

Edit:
To be clear, this option 3 can use an unmodified, off-the-shelf, MCU development board. The original crystal is unchanged; there is no need to modify it to replace its crystal.

So it could use a small, e.g. Arduino-Nano size, microcontroller running at a reasonable rate (e.g. 64MHz) connected to a TCXO (or even OCXO), and get close to 0.5ppm error.


Low power RGB LED for wearable device I am trying to prototype a wearable device which will have about 120 RGB LEDs. I was considering the WS2812B but they seem to draw about 50mA and so may not be a good option since I will be powering them from a battery.

I would be glad to know of other options or ways to implement the LEDs in order to consume less power.

You can reduce the current by simply reducing the duty cycle. For example, to display red, rather than sending 255 as the red component, send 42.

If you divide each of the R/G/B values by the same figure you get the same colour, just duller. In a quick test I found that a 24-pixel strip only used 67 mA if I sent red=0, green=0, blue=42 which made them look a dull blue. If you send a value of 8 (in a single channel) then it takes 25 mA for 24 pixels.

A bit more testing reveals a base consumption of 21 mA even if you are sending black. That is, the overhead is 21 mA, which works out at about 1.1 mA per neoPixel.

Based on that, you would consume 335 mA to make 120 NeoPixels show a moderately bright red.

I don't think there is going to be some "magic bullet" that lets you light up 120 LEDs brightly, but not use much power. However using the NeoPixels which lets you have fine control over the brightness of each of the R/G/B pixels is probably going to be about as close as you can get.

The figure of 50 mA which you quoted is to have "full brightness" on all three colours (ie. bright white).


Simple ESP to ESP reading blink program not reading input voltage One ESP32's 3v3 is connected to GPIO 26 of another ESP32.
The program is uploaded. The built-in LED lights for two seconds as expected. Then, it turns off. No matter what GPIO pin the 3v3 is connected to (besides 2), the LED remains off.
/*
 * ON Board LED GPIO 2
 */

#define LED 2
#define inPin 26

void setup()
{
  Serial.begin(9600);
  // Pins 34, 35, 36, 39 are input only
  pinMode(LED, OUTPUT);

  // Sanity check LED works
  digitalWrite(LED, HIGH);
  delay(2000);
}

void loop()
{
  Serial.println(digitalRead(inPin));
  digitalWrite(LED, digitalRead(inPin));
}

Any reason this is happening? Grounds are connected. Simply trying to turn LED on/off if external voltage occurs at any GPIO pin (e.g., 26).

Arduino GPIO automatically set as inputs, so I assumed the same for ESP32. Once the pinMode of the input pin was set, it worked:
#define LED 2 // ON Board LED GPIO 2
#define inPin 26

void setup()
{
  Serial.begin(9600);
  // Pins 34, 35, 36, 39 are input only
  pinMode(LED, OUTPUT);
  pinMode(inPin, INPUT); // <----------
}

void loop()
{
  Serial.println(digitalRead(inPin));
  digitalWrite(LED, digitalRead(inPin));
}


Keyboard.h: No such file or directory - Arduino pro micro (leonardo) I've just bought a new pro-micro and I want to simulate some keyboard inputs with it, the thing is the Arduino IDE (version 2:1.0.5) can't seem to find neither HID.h or Keyboard.h libraries. The steps to reproduce the problem are:

plug the device using usb cable on the pc
Open arduino ide
try to compile my code
it fails with the error

  test_keyboard.ino:27:22: fatal error: Keyboard.h: No such file or directory
  compilation terminated.

The code is:

#include <Keyboard.h>

void typeKey(int key)
{
  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */
void setup()
{
  // Begining the Keyboard stream
  Keyboard.begin();

  delay(400);

  //Keyboard.press(KEY_LEFT_GUI);

  Keyboard.press(KEY_CTRL);
  Keyboard.press(KEY_ALT);
  Keyboard.press(KEY_T);

  Keyboard.releaseAll();

  delay(100);

  Keyboard.print("echo 'hello world'");

  typeKey(KEY_RETURN);

  delay(100);

  // Ending stream
  Keyboard.end();
}

/* Unused endless loop */
void loop() {}

By the way, I'm running this on linux, after pluging it and running lsusb on terminal I got:
  Bus 002 Device 071: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

The Keyboard functions were moved into their own library in Arduino IDE 1.6.6/Arduino AVR Boards 1.6.9. In previous Arduino AVR Boards versions, those functions were part of the core library and there was no Keyboard library or Keyboard.h. Since you're using a very outdated version of the Arduino IDE, you don't have a Keyboard library, thus the error. There are two options to solve this problem:

Remove the line #include <Keyboard.h> from your sketch.
Update to a modern version of the Arduino IDE. Note that when you install the Arduino IDE via sudo apt-get install arduino, you end up with the very outdated IDE version you're using. I recommend always installing the official Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software.

For anyone wanting to write code that's backwards compatible with old IDE versions, you can do this:

#if ARDUINO > 10605
#include <Keyboard.h>
#endif

Reference: https://github.com/arduino/Arduino/pull/3304


Accelerometer sample code Just to illustrate my work here, I found a tutorial on how to code an accelerometer, I wanted to understand how does it work, literally get how it works, and not simply using the code without understanding it.

In the beginning of the program,there's a char variable declared as :

char values[10];

then later on the code, there was couple lines of getting the information stored in this variable, I'll give this as as example :

x = ((int)values[1]<<8)|(int)values[0];

we want X to receive values[0] and values[1] , that's what that line does up there.

My question is : can someone explain to me how does that line work, and why can't we simply write it as x = ((int)values[1])|(int)values[0]; ?

To understand this you have to start thinking in binary.

The | operator is "Perform a binary OR on these two values".

The <<8 is "Shift this value 8 bits to the left".

If you have two 8-bit values, say (in hex) 0x37 and 0x42, and you OR them together you get:

0x37 = 00110111
0x42 = 01000010
--------------- |
0x77 = 01110111

In each column where there is a 1 in either value you get a 1 in the result.

Now if you shift the first number 8 bits to the left, you end up with:

0x3700 = 0011011100000000
0x0042 =         01000010
------------------------- |
0x3742 = 0011011101000010

You do this when a 16-bit value has been split into two 8-bit values and you want to join them back together again into the original 16-bit value.


Can a connection of HC-05 and Arduino Nano receive audio and display waveform on computer? Working to receive Music for Bluetooth Speaker via HC-05

No, it can't.  The HC-05 is a Bluetooth Serial device, Bluetooth speakers are Bluetooth Audio Sink devices.

It's like asking "Can my bicycle fly?"

I think you'll agree the answer is "NO".

The only possible way of doing it using the HC-05 is to receive the audio using your computer then pre-process it and send the important information to the Arduino through the HC-05, so the Arduino can then send it back to the computer for displaying.  But then, what really is the point of the Arduino...?!


EspMQTTClient inside a class I'm trying to use EspMQTTClient inside a class, called myIOT32.

An error, which I don't find the reason for is generated.

/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp: In lambda function:
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp:25:5: error: 'this' was not captured for this lambda function
     client.publish("mytopic/test", "This is a message sent 5 seconds later");
     ^
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp:25:5: error: invalid use of non-static data member 'myIOT32::client'
In file included from /home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp:1:0:
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.h:20:19: note: declared here
     EspMQTTClient client;
                   ^
Multiple libraries were found for "WiFi.h"
 Used: /home/guy/.arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/WiFi
 Not used: /home/guy/arduino-1.8.12/libraries/WiFi
exit status 1
Error compiling for board LOLIN D32.

.h file:

#ifndef myIOT32_h
#define myIOT32_h

// OTA libraries
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

#include "secrets.h"
#include "EspMQTTClient.h"
#include "Arduino.h"

class myIOT32
{
private:
    void onConnectionEstablished();  // <--- this is a must have function ( was taken as is from lib's built-in example

public:
    EspMQTTClient client;
    myIOT32(char *ssid, char *wifi_p, char *mqtt_broker, char *mqttU, char *mqttP, char *devTopic, int port = 1883);
};

#endif

.cpp file:

#include "myIOTesp32.h"

myIOT32::myIOT32(char *ssid, char *wifi_p, char *mqtt_broker, char *mqttU, char *mqttP, char *devTopic, int port)
    : client(ssid, wifi_p, mqtt_broker, mqttU, mqttP, devTopic, port)
{
}

void myIOT32::onConnectionEstablished()
{
  // Subscribe to "mytopic/test" and display received message to Serial
  client.subscribe("mytopic/test", [](const String & payload) {
    Serial.println(payload);
  });

  // Subscribe to "mytopic/wildcardtest/#" and display received message to Serial
  client.subscribe("mytopic/wildcardtest/#", [](const String & topic, const String & payload) {
    Serial.println(topic + ": " + payload);
  });

  // Publish a message to "mytopic/test"
  client.publish("mytopic/test", "This is a message"); // You can activate the retain flag by setting the third parameter to true

  // Execute delayed instructions
  client.executeDelayed(5 * 1000, []() {
    client.publish("mytopic/test", "This is a message sent 5 seconds later");
  });
}

Appreciate any help in constructing such a class

For the fix, just add the reference capture and it should compile fine:

   // Execute delayed instructions
  client.executeDelayed(5 * 1000, [&]() {   // [&] instead []
    client.publish("mytopic/test", "This is a message sent 5 seconds later");
  });

I could not test, but you will have to apply to other functions as well.

[] Capture nothing
[&] Capture any referenced variable by reference
[=] Capture any referenced variable by making a copy


AccelStepper library advanced codes! I was trying to find out how this library can run multiple stepper motors at the same time, and I saw this important function called...
void AccelStepper::setOutputPins(uint8_t mask)
{
    uint8_t numpins = 2;
    if (_interface == FULL4WIRE || _interface == HALF4WIRE)
    numpins = 4;
    else if (_interface == FULL3WIRE || _interface == HALF3WIRE)
    numpins = 3;
    uint8_t i;
    for (i = 0; i < numpins; i++)
    digitalWrite(_pin[i], (mask & (1 << i)) ? (HIGH ^ _pinInverted[i]) : (LOW ^ _pinInverted[i]));
}

why is it using uint8_t? and what is a mask? and Is this line:
digitalWrite(_pin[i], (mask & (1 << i)) ? (HIGH ^ _pinInverted[i]) : (LOW ^ _pinInverted[i]));

sending a step signal to multiple stepper?

The setOutputPins() function sets the pins for a pulse for a single stepper. Depending on the used stepper motor a different number of pins has to be set (normal stepper drivers have 2 pins, the ULN2003 and its siblings have 4) in a different way. For that the function first determines the number of pins to use via the _interface member variable of the class.
The mask parameter contains the states of the pins. Each bit represents one pin. If the corresponding bit is set to 1, the pin will be set to an active state. If not, it will be set to an inactive state. Normally an active state (like I have called it here) is HIGH, an inactive state is LOW. But when working with different stepper drivers, some pins might work with an inverted logic. Thus the value (LOW or HIGH) is inverted, if the pin is marked as inverted in the _pinInverted array. This logic is in the line
digitalWrite(_pin[i], (mask & (1 << i)) ? (HIGH ^ _pinInverted[i]) : (LOW ^ _pinInverted[i]));

The idiom condition ? expression : expression represents an embedded if condition. If the condition evaluates to true, the first expression is used, else the second expression. With mask & (1 << i) we are checking, if the ith bit in mask is set. If yes, we use the next expression: HIGH ^ _pinInverted[i]. Here the ^ bitwise XOR operator is used to invert the value, if _pinInverted[i] is set to 1 (and thus marked the pin as inverted). If _pinInverted[i] is zero, the value will stay as it is. The handling of the LOW value is similar.
For understanding that better, you might want to read more about bitwise operators, if you haven't already done so.

why is it [the mask parameter] using uint8_t?

uint8_t is the smallest type, that could be used: 1 byte. As each bit represents one pin, and the library supports steppers with up to 4 pins, only 4 bits are needed at max. Thus using the smallest type with 8 bits is sufficient.

Is this line sending a step signal to multiple stepper?

No, it is setting the pins of a single stepper motor. Each instance of the AccelStepper class represents a single stepper motor. Thus every function in it also only talks to one single motor. You haven't really explained, how you want to add the feedback functionality. But you should not change the AccelStepper class to handle multiple motors. That does not make sense to me. Each motor has to be controlled individually and this class is there to capsule the work behind that. Thats the idea behind making a class for this.
I guess you want to drive multiple motors, each with it's own feedback loop. So then you first need to change the AccelStepper class for supporting that feedback loop. How this is done depends very much on your type of feedback loop. Also the setOutputPins() method is not a good place for that. It is a very low level function. You need to start further up in the call chain, maybe in the step() method or the runSpeed() method (this really depends on how you want to handle the feedback). Also you need to write methods to set up and handle the encoders input. You may need to configure timers and/or interrupts for reading them correctly.
For then supporting multiple stepper motors, you could still look into the MultiStepper class. You could change it to fit with your changes in AccelStepper or write your own wrapping class. That mostly depends on how you want the multiple steppers to behave.


Where is random defined with no arguments? I can't seem to find void random() (with no arguments) defined in the library and yet my sketches seem to compile just fine when calling random() with no arguments.

I've found random with 1 argument and random with 2 arguments but no cases of random with no arguments.

Is random() defined in the library with no arguments?

If so, where is it defined?

If it isn't, what could explain how my code compiles despite me not providing any arguments?


How to use a coma as the decimal separator? I have a LCD that displays a float variable. I would like to show a comma instead of a dot as the decimal separator.

float temp = 23.50;
lcd.setCursor(0, 0);
lcd.print(temp);

I want to show 23,50 instead of 23.50.

Is there any function to convert or format it?

Print the integer part, print a comma, then print the value minus the integer part.

float value = 123.45;
int ival = (int)value;
int frac = (value - ival) * 100;

Serial.print(ival);
Serial.print(",");
if (frac < 10) Serial.print("0");
Serial.println(frac);


Blinking LED's at changing rate I am trying to blink two LED's, starting at slow rate then increasing to fast s follows: 1 on, 1&2 on, 2 on, 1&2 on, 1 on, etc. The blinks go through the loop twice then speed up and repeat until both are on continuously. Then I want LED's 3 & 4 to come on.
I got the 1 & 2 LED's to blink as I want but anything I put following my for / if loop goes into the loop.
This works for blinking the 1 & 2 LED's:

int led1 = 9;
int led2 = 10;
int led3 = 11;
int led4 = 12;
int delay1 = 700;
int delayAmount1 = delay1 / 10;

void setup() {

pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
}

void loop() {{
delay1 = delay1 - delayAmount1;

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

if (delay1 > 10)

digitalWrite(led1, HIGH); //yellow on (yellow)

delay(delay1);

digitalWrite(led2, HIGH); //red and yellow on (orange)

delay(delay1);

digitalWrite(led1, LOW); //yellow off (red)

delay(delay1);

digitalWrite(led1, HIGH); //yellow on (orange)

delay(delay1);

digitalWrite(led2, LOW); //red off (yellow)

digitalWrite (led1, LOW); //yellow off (all off)

}
}

// digitalWrite(led3, HIGH); //blue on

//delay(1000);

//digitalWrite(led4, HIGH); //green on

}

If I remove the // from

// digitalWrite(led3, HIGH); //blue on
//delay(1000);
//digitalWrite(led4, HIGH); //green on

they become part of the loop. Can someone tell me what I am doing wrong? Kind of new to this.

The if(delay1>10) does not have the conditional code in {}, so it should look like

if(delay1>10) {
//conditional code, what happens if statement == true
}

And if I understood your project and code correctly, when delay1 <= 10 then you want the led3 and led4 to light up. So you want to add an optional else{} block. This optional block will be skipped, if the if statement is executed. If the if statement is not executed, because for example your delay1 is smaller or equal to 10, then the else block will be executed.

else{
//led3 and led4 light up
}


USB connector between Arduino and a lever (switch) I am not sure an Arduino forum is the right place to ask this question, but since I'm using Arduino here I thought it would be a good starting point. I am trying to connect a lever (you can think of it as a switch, when it's pressed it's ON, and otherwise it's OFF) to an Arduino via a USB connector. My setup worked perfectly fine when I connected the lever directly to the Arduino, but via the USB it doesn't work. Since I already built and invested in USB connectors I would like to solve this issue, or at least understand what I am doing wrong in here.

I've attached a photo to demonstrate the wiring. Note that it works if I bypass this USB connection. I'm trying to understand why this doesn't work via a USB.

I'd suggest using a multimeter to figure out what's connected to what after hooking up the complete wiring scheme; there aren't that many options and you should be able to figure out what's connected to what soon enough. On a more philosophical note, it's only a bad idea if the alternatives weren't worse.


Nano resets or freezes on calling a function I'm controlling a light bulb with my Arduino Nano from serial or RF (via nRF24L01+) and I'm passing the commands as a string. After I get all the variables (3 ints) I try calling the function execOrder but no matter what I put in there, the Arduino just hangs or resets. Code is as follows:

#define SSR 3
#define SW 4
#define nanoID 1
bool isPWM = false;
int value;

// Módulo RF
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
#define PayLoad 20

#include <MemoryFree.h>

void setup() {
  pinMode(SSR, OUTPUT);
  pinMode(SW, INPUT_PULLUP);
  digitalWrite(SSR, LOW);
  value = 0;
  Serial.begin(9600);
  Serial.println("------ CEACI SAS -- Controller Module ------");
  Serial.println("Module No: " + String(nanoID));
  // Inicializar RF
  Serial.println("Inicializando RF");
  radio.begin();
  radio.setRetries(15,15);
  radio.setPayloadSize(PayLoad);
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_250KBPS);
  radio.setCRCLength(RF24_CRC_16);
  delay(100);
  radio.openWritingPipe(pipes[1]);
  radio.openReadingPipe(1,pipes[0]);
  radio.startListening();
  //radio.printDetails(); //RF Debug
  Serial.println("RF listo!");
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

void loop() {
  if (Serial.available()) {
    Serial.println("Rcvd Serial!");
    String msgRcvd = Serial.readString();
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    String msgRcvd(msgBuff);
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else {
    chkSwitch();
  }
}

void execOrder(int ID, int CMD, int VAL){
  if (ID == nanoID || ID == 0){
    switch(CMD){
      case 0:
        State();
        break;
      case 1:
        value = VAL;
        OnOff();
        break;
      case 2:
        value = VAL;
        PWM();
        break;
    }
  }
}

I wanted to process the incoming string in a function, but it resets as well.

By the way, I'm using MemoryFree library to check if I'm out of memory, and there's plenty of it, so I don't really know where's the problem. Any help would be greatly appreciated!

EDIT:

For the serial part I can do the following (my original code):

if (Serial.find("MOD=")) {
  int ID = Serial.parseInt();
  if (ID == nanoID || ID == 0) {
    Serial.find("CMD=");
    int command = Serial.parseInt();
    int cmdVal = 0;
    if (command != 0){
      Serial.find("VAL=");
      cmdVal = Serial.parseInt();
    }
    Serial.println("MOD: "+String(ID)+", CMD: "+String(command) + ", VAL: " + String(value));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    execOrder(ID,command,cmdVal);
  }
}

And it works flawlessly. But I don't know how to achieve the same results with the RF input. The problem seems to be with using so many strings.

Your problem is not due to memory shortage, but because you are erroneously using pointers.

Even with your fix you are doing the same mistake, you are just not incurring into the same problem by luck as you are not addressing anything new after the bad definition of your variable msgBuff.

Putting all that into simple terms, you should change your code and probably read some articles on C pointers as it looks like you have a Java background (like me).

Your issue is in the char msgBuff[]=""; statement which should be moved after the the call to obtain the payload size and turned into char msgBuff[RFlen];:

int RFlen=radio.getDynamicPayloadSize();
char msgBuff[RFlen];
delay(10);
radio.read(&msgBuff, RFlen);


SPI Temperature sensor interface with Arduino Uno I want to interface with an AD7314 Temperature Sensor. I want to only read the temperature value from the sensor and output the value on to 8 LEDs connected to the Arduino. But so far I have not been able to read from the sensor. The datasheet says that the temperature readings are in 10 bit 2's complement, so I plan to convert to 8 bit before putting it out on the LEDs. Here is my code so far.

I am new to SPI and clearly don't understand the temperature sensor's datasheet. Please can anyone elaborate or explain where I am going wrong?

Note: I have chosen pin A0 (PIN 23 of ATMEGA328P) as slave select and not pin 10

#include <SPI.h>

byte val;

void setup (void) {
  pinMode(0, OUTPUT); //LED 1
  pinMode(1, OUTPUT); //LED 2
  pinMode(5, OUTPUT); //LED 3
  pinMode(6, OUTPUT); //LED 4
  pinMode(7, OUTPUT); //LED 5
  pinMode(8, OUTPUT); //LED 6
  pinMode(9, OUTPUT); //LED 7
  pinMode(10, OUTPUT);//LED 8
  pinMode(11, OUTPUT); // MOSI
  pinMode(12, INPUT); //MISO
  pinMode(13, OUTPUT); //CLOCK PIN
  digitalWrite(A0, HIGH);  // ensure Slave select stays high
  SPI.begin ();
  Serial.begin(9600);
} // end of setup

void loop (void) {
  // enable Slave Select
  digitalWrite(A0, LOW); // enable communication with slave
  delay (0.425);// wait for conversion
  val = SPI.transfer(0x00);// read from sensor
  Serial.println(val); // display reading on serial monitor
  // disable Slave
  digitalWrite(A0, HIGH);
}

delay (0.425);// wait for conversion

You can't delay a fraction of a millisecond. You can use delayMicroseconds though:

delayMicroseconds(425);

However, you don't need to sleep at all.

  The conversion clock for the part is internally generated so no
  external clock is required except when reading from and writing
  to the serial port. In normal mode, an internal clock oscillator
  runs the automatic conversion sequence. A conversion is initiated
  every 400 ms. At this time, the part wakes up and performs
  a temperature conversion. This temperature conversion typically
  takes 25 ms, at which time the part automatically shuts down.
  The result of the most recent temperature conversion is available
  in the serial output register at any time.

You have your chip select pin backwards:

  To ensure that the serial port is reset properly
  after power-up, the CE must be at a logic low before the
  first serial port access. The serial clock is active only when CE is
  high. For correct data synchronization, it is important that the
  CE be low when the serial port is not being accessed

So it should start LOW, and be set HIGH before you read, and back to LOW afterwards.

You need to read 2 bytes, not one, then combine them in the right way to make a proper 8-bit value:

digitalWrite(A0, HIGH);
uint8_t b1 = SPI.transfer(0x00);
uint8_t b2 = SPI.transfer(0x00);
digitalWrite(A0, LOW);

int8_t = (b1 << 1) | (b2 >> 7);

The reason for that is that the first bit of the first byte is a "leading zero" so you need to discard it, then add the first bit of the second byte as the last bit of your value, discarding the remainder of the second byte, since you specified only an 8-bit resolution in your question.


Problem Atmel Studio 7 with uploading I have a problem with the interworking between Atmel Studio 7 and Arduino IDE 1.6.10.

I recently upgraded from IDE 1.0 to 1.6.10 and I can no longer upload my code to the Arduino. Everything works including compiling and it does recognise my COM3 port. Atmel Studio is configured for no external programmer.

When I compile with the Arduino IDE it does upload the code. My question is what goes wrong here, what do I need to do solve it. Thanks for your help

This the message I have in the end:

Compiling 'GridMonintor_V1R1' for 'Arduino Nano w/ ATmega328' Binary sketch size: 12,268 bytes (used 40% of a 30,720 byte maximum) (22.20 secs)

Minimum Memory Usage: 774 bytes (38% of a 2048 byte maximum) Uploading to I/O board using 'COM3'

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

...Specify a programmer using the -c option and try again

For Arduino, the programmer switch must be -c arduino. The full arguments for avrdude, in the Atmel Studio 7 External Tools window, are:

-c arduino -p m328p -P COM3 -b 57600 -D -V -U flash:w:"$(TargetDir)$(TargetName).hex":a

See avrdude options.


How to write Arduino API code in VL53L1X? I'm trying write code for the VL53L1X on Arduino,  but I didn't get the VL53L1X registers. How to access them and how to measure the data in VL53L1X? Can anyone help me?

He's not asking about a VL53L1X Arduino. He's asking for code to support the VL53L1X (which is an ST distance sensor) that runs on an arduino.

ST have provided a library, but it's huge with many large buffers and doesn't run on an arduino as distributed. They've also forbidden anonymous distribution of a corrected version, presumably because they don't want to make it easy to run on 16-bit processors. It might run easily on a Teensy 3.

Sparkfun have just released a library. It's much smaller but, like the Polulu library for the  VL53L0X, it's full of magic numbers where they've stripped the structure out and just write the end result into the registers - so it will be difficult to get the best from the sensors.

https://github.com/sparkfun/SparkFun_VL53L1X_Arduino_Library/blob/master/src/SparkFun_VL53L1X_Arduino_Library.cpp

There is a good case for writing something halfway : without the overcomplicated code typical of ST's Cube environment but with a bit more content than Sparkfun's version.

It's a boring job unless you have something you need from it. Worthwhile only if you have a good case to support it on AVR. If you try to build the ST sources, look carefully at the maximum write size on I2C (135 bytes) and compile with maximum warnings enable (it will pick up several 16/32 bit wordsize errors, mostly critical).


How to create a simple TCP server with the analogRead value on Wemos D1 mini? I want to create a TCP server on the Wemos that serves the analogRead value of the connected potentiometer.

The code below is based on this example.
The Wemos connects to the Wi-Fi and i'm able to ping it,
but the problem is that I can't connect to the server.
Also I don't really understand why the length of the data has to be passed with the data (serverClients[i].write(sbuf, len);). Why can't the library figure that out?

#include <ESP8266WiFi.h>

//how many clients should be able to telnet to this ESP8266
#define MAX_SRV_CLIENTS 2
const char* ssid = "myWifi";
const char* password = "myPassword";

WiFiServer server(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];

unsigned long previousMillis = 0;
const long interval = 200;
void setup() {
  Serial.begin(115200);
  Serial.print("\nConnecting to "); Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
  if (i == 21) {
    Serial.print("Could not connect to"); Serial.println(ssid);
    while (1) delay(500);
  }
  server.setNoDelay(true);
  Serial.print(WiFi.localIP());
}

void loop() {
  unsigned long currentMillis = millis();
  uint8_t i;
  //check if there are any new clients
  if (server.hasClient()) {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //find free/disconnected spot
      if (!serverClients[i] || !serverClients[i].connected()) {
        if (serverClients[i]) serverClients[i].stop();
        serverClients[i] = server.available();
        continue;
      }
    }
    //no free/disconnected spot so reject
    WiFiClient serverClient = server.available();
    serverClient.stop();
  }

  //do every 200ms
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    int isensorValue = analogRead(A0); //analog read
    String sSensorValue = String(isensorValue); //int to string
    size_t len = sSensorValue.length();
    uint8_t sbuf[len];
    sSensorValue.getBytes(sbuf, len);
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        serverClients[i].write(sbuf, len);
        delay(1);
      }
    }

  }
}

So the problem was that I forgot the following line.
Thanks to @Johnny Mopp for pointing this out.

server.begin()

Correct code:

#include <ESP8266WiFi.h>

//how many clients should be able to telnet to this ESP8266
#define MAX_SRV_CLIENTS 2
const char* ssid = "myWifi";
const char* password = "myPassword";

WiFiServer server(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];

unsigned long previousMillis = 0;
const long interval = 200;
void setup() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
  if (i == 21) {
    Serial.print("Could not connect to"); Serial.println(ssid);
    while (1) delay(500);
  }
  server.begin();
  server.setNoDelay(true);
}

void loop() {
  unsigned long currentMillis = millis();
  uint8_t i;
  //check if there are any new clients
  if (server.hasClient()) {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //find free/disconnected spot
      if (!serverClients[i] || !serverClients[i].connected()) {
        if (serverClients[i]) serverClients[i].stop();
        serverClients[i] = server.available();
        continue;
      }
    }
    //no free/disconnected spot so reject
    WiFiClient serverClient = server.available();
    serverClient.stop();
  }

  //do every 200ms
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    int isensorValue = analogRead(A0);
    String sSensorValue = String(isensorValue) + "\n\r";
    size_t len = sSensorValue.length();
    uint8_t sbuf[len];
    sSensorValue.getBytes(sbuf, len);
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        serverClients[i].write(sbuf, len);
        delay(1);
      }
    }

  }
}


How to enable interrupt again after disabling it? I am not quite experienced with Arduino and Interrupts. Below I am trying to disable interrupt once it got detected and enable it again when I start loop again. But in below code I am not able to enable it.

int L = 2;
volatile int done0=0;
volatile unsigned long leftT=0;

void recordL()
{
  if(done0 == 0)
  {
      leftT=micros();
  }
  done0 = 1;
  detachInterrupt(0);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(L,INPUT);
  Serial.begin(9600);
  Serial.println("Start..");
}

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

  attachInterrupt(0,recordL,RISING);
  done0 = 0;

  while(!done0)
  {

  }

  Serial.println("Sound..");
  Serial.println(leftT);
  delay(1000);
  Serial.println("After Delay");
}

but I made small change in code. I shifted 'done0=0' above attachInterrupt() then it is working. Why is that happening? One more issue that I am facing here is when I enable it again one more saved value is coming. Does it store value when I have disabled it?

int L = 2;
volatile int done0=0;
volatile unsigned long leftT=0;

void recordL()
{
    if(done0 == 0)
    {
        leftT=micros();
    }
  done0 = 1;
  detachInterrupt(0);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(L,INPUT);
  Serial.begin(9600);
  Serial.println("Start..");
}

void loop() {
  // put your main code here, to run repeatedly:
  done0 = 0;
  attachInterrupt(0,recordL,RISING);

  while(!done0)
  {

  }

  Serial.println("Sound..");
  Serial.println(leftT);
  delay(1000);
  Serial.println("After Delay");
}

Output for 2nd case (Sound is coming only once but I am getting sound after delay also):

   Start..
   Sound..
   2873000
   After Delay
   Sound..
   3873528
   After Delay

Below I am trying to disable interrupt once it got detected and enable it again when I start loop again.

not sure why you want to do that but interrupts are DISABLED in isr by hardware (unless you explicitly enable it in isr) so what you are trying to do is done for you automagically.

  But in below code I am not able to enable it.

mostly it involves enabling the respective interrupt mask, unless you want to enable / disable all interrupts.


Weird Arduino math result I have a simple code, part of which contains the calculation 800/1000, which seems to return a value of zero for some reason (even though I store it in a float variable). When I replace the calculation with the expected result (0.8) the code works as expected, I just wonder why the calculation doesn't produce the same result.

A whole numbers like 800 or 1000 are integers, while a number like 800.4 is considered fractional and is treated as a float. Two integers divided gives an whole integer result, in your case 0. If one number in the division is an integer, and one is a float, the result is a float.