text:
SD card readline reading batched lines?
So, I am trying to transmit float data, over UART, from my Arduino to another machine. The log of this data is really large, so I am forced to put it on an SD card, and read it into the Arduino line-by-line, then transmit that single line.
The issue is that my code seems to be "grabbing" ~65 lines (or more) at a time, transmitting them over UART, then stopping (or crashing) the Arduino.
My log looks like this (a small snippet of the several thousands of lines):
14.71927
14.71795
14.71787
14.71787
14.71787
14.71799
14.7175
14.71836
14.71746
14.71787
14.71923
14.71878
14.7184
14.71791
14.71893
14.7184
14.71746
14.71799
14.71746
14.71795
14.71874
14.71795
14.71878
14.71836
14.71881
14.72235
14.72781
14.72872
14.72917
14.72826
14.73188
14.73278
14.73595
14.73783
14.74227
14.74231
14.74363
14.74683
14.7495
14.75492
14.75899
14.76396
14.76807
14.77033
14.77161
14.77262
14.77978
14.78524
14.7884
14.78746
14.79695
14.80238
14.80652
14.80648
14.81055
14.81191
14.81865
14.82234
14.82095
14.81733
14.8286
14.82908
14.82999
14.82682
14.83673

And my code looks like this (I know it says 4Hz, but is at 1Hz, but that was to help "see" the "batch" grabbing and printing):

// Define our LED pins
#define greenLED    6
#define redLED      5

// Define our serial BAUD rate
#define BAUDrate    9600

// To read data from the SD card
#include <SD.h>

// To print data to an LCD panel
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd( 0x3F, 16, 2 );

void setup(){
    // Set LED pins as outputs
    pinMode( greenLED, OUTPUT );
    pinMode( redLED, OUTPUT );

    // LED output at start: GREEN = ON, RED = OFF
    digitalWrite( greenLED, HIGH );
    digitalWrite( redLED, LOW );

    // Begin wired comms with MSP board
    Serial.begin( BAUDrate );

    // Begin reading data from SD card
    SD.begin( 4 );                      // Need pin #4 for SD card bit-shifting
    File dataLog;                       // Store our data from the SD card
    dataLog = SD.open( "DATA.TXT", FILE_READ );
    String data = dataLog.readStringUntil( "\n" ); // Prime our data

    int i = 0;

    while( data != "" ){
        i++;
        Serial.print( i );
        Serial.print( "\t" );

        Serial.println( data );         // Send our data to MSP board
        lcdUpdate( data );              // Print our sent data to the LCD screen

        delay( 1000 );                   // Wait 1/4 of a second (4 Hz)

        data = dataLog.readStringUntil( "\n" );    // Reprime our data
    }

    // Close our data log to avoid corrupting SD card contents upon restart
    dataLog.close();

    // Switch our LEDs since we're finished streaming our data
    digitalWrite( greenLED, LOW );
    digitalWrite( redLED, HIGH );
}

void loop(){
}

// Prints the current data being sent over UART to an LCD screen
void lcdUpdate( String ourData ){
    lcd.setCursor( 0, 0 );
    lcd.print( " Sending data:  " );
    lcd.setCursor( 0, 1 );
    lcd.print( "    " );
    lcd.print( ourData );
    lcd.print( "    " );
}

Again, I want it to grab a single line, print it to the serial terminal, print it to the LCD, then grab a second line and repeat.  I'm not able to test the LCD (since I don't have one with me at the moment), but the serial terminal is giving me problems, so I'm assuming the LCD won't work, either.
I'm getting something, as a Serial Terminal output, along the lines of:
1       14.71927
14.71795
14.71787
14.71787
14.71787
14.71799
14.7175
14.71836
14.71746
14.71787
14.71923
14.71878
14.7184
14.71791
14.71893
14.7184
14.71746
14.71799
14.71746
14.71795
14.71874
14.71795
14.71878
14.71836
14.71881
14.72235
14.72781
14.72872
14.72917
14.72826
14.73188
14.73278
14.73595
14.73783
14.74227
14.74231
14.74363
14.74683
14.7495
14.75492
14.75899
14.76396
14.76807
14.77033
14.77161
14.77262
14.77978
14.78524
14.7884
14.78746
14.79695
14.80238
14.80652
14.80648
14.81055
14.81191
14.81865
14.82234
14.82095
14.81733
14.8286
14.82908
14.82999
14.82682
14.83

It seems to want to stop somewhere between the 65th and 69th element, randomly.  I'm assuming that it's running out of buffer space, since it's grabbing everything from the SD card, instead of a single line, one at a time.
This has become more evident with my i = 0 line, and that it isn't iterating for every line, just the once for the ~65 lines.
Am I reading the data in incorrectly, or am I parsing things incorrectly, or is what I'm trying to do simply not possible?

put a Serial.print("."); inside the loop() block

@jsotola It never even gets to the loop() block.  I did what you said, and it just kind of stops, which reaffirms my suspicions that it's grabbing the whole SD card contents and overflowing the buffer, then freezing.

Arduino's reference doesn't help with your readStringUntil call (see SD's documentation), but assuming it's the same as Stream's, it needs a character, not a string as a terminator.
Your output shows that your Arduino tried to read a line, but there were no line endings found - probably because of the '' vs. "". That's why your output starts with a 1 (i's value), and there no other line numbers after that, even though in your output clearly shows newlines.


text:
Using a Force Sensing Resistor and time input
So the code below measures how much force is exerted on the FSR. I would like to know what would I have to change in this code so that it can record for how long the FSR is being pressed for. So instead of "What force is exerted on the FSR?", I want to ask "How long is the FSR being pressed for?"
Any help will be most appreciated
#include<SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial bluetooth_port(0, 1); //ports for Rx and Tx
int flexSensorPin; // The flex sensor for pin 0

void setup()
{

  Serial.begin(9600); // Start the serial transmission
}

void loop()
{

  flexSensorPin = analogRead(A0); // Flex sensor pin
  Serial.print(flexSensorPin);
  Serial.println("EOL");

  delay(100);

}

check out the millis() function

you need to clarify your question ... is somewhere around 3 seconds an acceptable measurement of time?

When there's no "force" read the sensor value and then start counting, something like: if(sernsorReading != 0){start counting}

Use the analog comparator implemented in AVRs. this function, monitors two analog levels and generates interrupts if one of them goes higher or lower than the other as set. use this interrupt to record/stop counting. on AIN connects to FSR, and the other to a potentiometer to define a threshold. here are some links to get you going.
http://www.gammon.com.au/forum/?id=11916
https://github.com/tardate/LittleArduinoProjects/tree/master/playground/AnalogComparator

Thank you, I will definitely check these links out

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
ESP8266 still connects to wifi even after flashed with empty sketch
So, my wifi is a hotspot password protected. I was developing a program until I decided to comment the ssid and passwords from it, to prevent the ESP from connecting to the internet. But then it still connected. After some debugging, I decided to upload an empty sketch. It still connects to the hotspot!
What is going on?! How does it still know my SSID and password when loaded with an empty sketch!?

The Espressif esp8266 SDK remembers the SSID and password on flash to start connecting immediately after boot. The WiFi channel is stored in the RTC memory (cleared on power down)
You can control this with WiFi.persistent() and WiFi.setAutoConnect().

Thanks. That seems to be it!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Do comments occupy space in compiled C++ sketch? Arduino / NodeMCU
I tend to leave old code around as comments until I am sure that my current version is stable.  Just the way I like working.  I am concerned that I may be unnecessarily bloating up my sketches.
Do comments occupy space in an Arduino IDE compiled C++ sketch for Arduino (Nano, Uno)?  Is it correct to suppose that the behavior would be the same for NodeMCU?

you can determine that by compiling two identical sketches, one of which has a huge amount of comments

Not related to your question but... you should learn to use version control, and use comments for... commenting the code!

Unrelated, unhelpful, unasked for and... mistaken.  One is often wrong when guessing with little or no information to base one's assumptions upon.  I am talking about in between versions, as is clearly stated in the question.

What's unhelpful, unasked for and mistaken? Edgar's comment about source control is a very good suggestion. (Keeping your old code in the file as comments is superfluous if you use version control.)

The C/C++ processor (which processes only the #define & #include statements) is the first stage of the compilation process. It runs before the compiler does and strips out everything that isn't code. The compiler will never see your comments.

No.  Comments don’t take up any space.


text:
How can one reset Arduino Nano from NodeMCU?
If one connects the RESET pin on an Arduino Nano to a digital pin on a NodeMCU, will the NodeMCU be able to reset the Nano by setting said pin to LOW?

Yes, you can reset a 5 V Arduino with esp8266. I did it many times. The esp8266 doesn't have a problem with pull-up level current at 5 V.
On my picture io 0 of the esp-12F is wired to reset pin of Nano. The esp-12F runs WiFiLink firmware which can OTA upload sketch to ATmega328p and of course before flashing it must reset the ATmega.

Yes - grounding the reset pin over-rides the pullup resistor on the Atmega 328's reset pin. You may not be able to prevent the NodeMCU from resetting the Nano when it (NodeMCU) is reset, if that matters.

esp8266 doesn't set pins LOW at startup

Good to know - thanks.

that matters.  tks for the headsup, UPVOTED.

yes it can.
and to make this answer a little longer...

you don't need a level shifter as the pins are 5v tolerant. pullups aren't a problem
you may use an optocoupler for isolation :)

interesting, UPVOTED


text:
LowPower.idle isn't waiting
I am trying to have my Arduino wait in a low power idle state given by the LowPower library made by rocketscream on an Uno. However, when I try to have it wait for 8 seconds, it seems to not pause at all. Does anyone know how to make it so it waits the full 8 seconds before running the next line of code?
Here is the code:
#include "LowPower.h"

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

void loop() {
   delay(100);
   Serial.println("above");
   delay(100);

   LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_ON, SPI_OFF, USART0_OFF, TWI_OFF);

   delay(100);
   Serial.println("below");
}

I would expect this to print "above", then wait 8 seconds, then print "below",  then do it again. But what happens is it runs right through the LowPower.idle without doing anything and the output looks like:

1:12:14.547 -> above
21:12:14.746 -> below
21:12:14.845 -> above
21:12:15.044 -> below
21:12:15.144 -> above
21:12:15.376 -> below

...and so on.
If anyone has any ideas on how to make idle wait, that would be great.
Thanks!

Try putting cli(); before  LowPower.idle(...). I think timer0 (used for millis and delay) is interrupting your idle time.

Thank you for your response but that does not seem to change anything.

FYI, this issue was brought up nearly 3 years ago, with no response from the author:  https://github.com/rocketscream/Low-Power/issues/36

That is unfortunate, but thank you for this information!


text:
ESP8266 crashing with blue LED always on and without the word "w_flash" on startup
When using Arduino SoftwareSerial with ESP8266, the blue led turns always on every time I reset the circuit by power. The only way to take the ESP working again is reflashing with the SDK 2.2.1, AT Firmware.

Have tested AMS1117 and LM317 as Power supply;
I'm using level converter 3V3 <-> 5V;
Have choosen different pins on Arduino for TX and RX;
No problem when using Hardware Serial pins with no SoftwareSerial;
My application works fine. The problem arises when I power off and power on and using SoftwareSerial.

Have noted a difference on the startup of ESP8266 after it gets stuck.
Here is the original startup (at 74880bps), ESP working normally
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2592, room 16
tail 0
chksum 0xf3
load 0x3ffe8000, len 764, room 8
tail 4
chksum 0x92
load 0x3ffe82fc, len 676, room 4
tail 0
chksum 0x22
csum 0x22

2nd boot version : 1.7(5d6f877)
SPI Speed : 40MHz
SPI Mode : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 251
freq trace enable 1
rf[112] : 03
rf[113] : 00
rf[114] : 01
w_flash <-- check the presence of this word

SDK ver: 2.2.1(6ab97e9) compiled @ Jun  7 2018 13:59:14
phy ver: 1136_0, pp ver: 10.2

⸮⸮j⸮l <-- here ESP is ready for AT commands at 115200bps. This is the word "ready" at 115200

Now, when the problem arises
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2592, room 16
tail 0
chksum 0xf3
load 0x3ffe8000, len 764, room 8
tail 4
chksum 0x92
load 0x3ffe82fc, len 676, room 4
tail 0
chksum 0x22
csum 0x22

2nd boot version : 1.7(5d6f877)
SPI Speed : 40MHz
SPI Mode : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 251
freq trace enable 1
rf[112] : 03
rf[113] : 00
rf[114] : 01

SDK ver: 2.2.1(6ab97e9) compiled @ Jun  7 2018 13:59:14
phy ver: 1136_0, pp ver: 10.2

Someone knows what w_flash means?
EDIT
I solve the problem by creating my own firmware with arduino IDE for ESP8266. Seens to be some type of bug in AT firmware, maybe! Now I can pass more tasks for ESP8266, saving arduino memory or even removing the need for an arduino board.
Thanks to everyone who helped =]

SoftwareSerial at 115200 baud does not work.

cause: 2 is never good. your esp8266 is underpowered or has to high RF TX power enabled

@Majenko On Arduino, SoftwareSerial sends command to ESP to change to 19200 baud. Then runs SoftSerial.begin(19200)

@LeandroIP - SoftwareSerial won't be able to send the command reliably if it is set to 115200 to start with.  I suspect its your power supply, do your PSUs push out enough amp?  (can't remember what an ESP8266 requires)

Please note: 1. SoftwareSerial will not work at those high frequencies. And, please, be clear about your setup. Are you using SS on the arduino or on the esp? What pins? How are both circuits powered?


text:
speed motor test with IR sensor and PID algorithm
I'm trying to control motor speed (RPM) using an IR sensor , All I've done is to control it without PID algorithm . and it works . can someone help me with implantation with PID . I'm using Arduino Uno , L298n motor driver , IR sensor and LCD display .
here you can see the circuit :
Circuit
and also this is the code without PID algorithm :
#include<LiquidCrystal.h>
LiquidCrystal lcd(A5,A4,A3,A2,A1,A0);
#include <Stepper.h>
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
volatile byte REV;
unsigned long int rpm,RPM;
unsigned long st=0;
unsigned long time;
int ledPin = 13;
int led = 0,RPMlen , prevRPM;
int flag = 0;
int flag1=1;
#define bladesInFan 2
float radius=1.9685;   // inch
int preSteps=0;
float stepAngle= 360.0/(float)stepsPerRevolution;
float minSpeed=0;
float maxSpeed=280.0;
float minSteps=0;
float maxSteps=maxSpeed/stepAngle;

void setup()
{
  myStepper.setSpeed(60);
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16,2);
  lcd.print("Speedometer");
  delay(2000);
  attachInterrupt(0, RPMCount, RISING);
 }

  void loop()
  {
    readRPM();
    radius=((radius * 2.54)/100.0);  // convering in meter
    int Speed= ((float)RPM * 60.0 * (2.0 * 3.14 *
        radius)/1000.0);
    // RPM in 60 minute, diameter of tyre (2pi r) r is radius,
    1000 to convert in km
    int Steps=map(Speed, minSpeed,maxSpeed,minSteps,maxSteps);

    if(flag1)
    {
       Serial.print(Speed);
       Serial.println("Kmh");
       lcd.setCursor(0,0);
       lcd.print("RPM: ");
       lcd.print(RPM);
       lcd.print("           ");
       lcd.setCursor(0,1);
       lcd.print("Speed: ");
       lcd.print(Speed);
       lcd.print(" Km/h       ");
       flag1=0;
   }
   int currSteps=Steps;
   int steps= currSteps-preSteps;
   preSteps=currSteps;
   myStepper.step(steps);
}

 int readRPM()
 {
    if(REV >= 10 or millis()>=st+1000)                  //  IT
   WILL UPDATE AFETR EVERY 10 READINGS or 1 second in idle
    {
        if(flag==0)
           flag=1;
           rpm = (60/2)*(1000/(millis() - time))*REV/bladesInFan;
           time = millis();
           REV = 0;
           int x= rpm;
           while(x!=0)
           {
              x = x/10;
              RPMlen++;
            }
            Serial.println(rpm,DEC);
            RPM=rpm;
            delay(500);
            st=millis();
            flag1=1;
           }
        }

void RPMCount()
 {
   REV++;
   if (led == LOW)
 {
   led = HIGH;
 }
  else
 {
    led = LOW;
  }
 digitalWrite(ledPin, led);
}

here is the source
thanks

What exactly is your problem with incorporating a PID controller? There is even a PID library for Arduino, which does the main work for you

@chrisl im a newbie and i dont know how to combine the PID code with the code above

@masut do you know what a pid controller is?

@SimSon yes three parameters proportional–integral–derivative  a control loop machine


text:
NRF24L01+ changing configuration after startListening
I have been trying to get two Arduino UNO talk to each other via NRF24L01's with TMRH20's NRF24 library. I tried many tutorials and examples and none of them worked. Most of them prints some error messages that's due to radio.write returning false.
After some troubleshooting I saw something weird. I set up the configuration (e.g. data rate) and when I call startListening it seems to be changed back.
This code:
void setup() {

    Serial.begin(9600);
    printf_begin();

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.printDetails();
    Serial.println();

    radio.startListening();
    radio.printDetails();
}

Outputs:
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0x4141417852
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x20 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x27
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 250KBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x02
RF_SETUP     = 0x0f
CONFIG       = 0x08
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 2MBPS
Model        = nRF24L01+
CRC Length   = 8 bits
PA Power     = PA_MAX

You can see that the address was set up correctly before startListening (0x4141417852) but after it reverted back to what I assume is the default value (0xc2c2c2c2c2). Data rate has also changed.
Is this normal?
The other Arduino UNO doesn't have startListening or stopListening, but if I print the configuration after openWritingPipe I see the correct configuration.

The first thing that comes to my mind is that you are powering the nrf24L01 directly from the 3V3 pin of your Arduino Uno. DO NOT do this.
The 3V3 pin does not provide enough current for the nrf24L01. This renders the module completely unstable. You can:

Use a decent capacitor across the VCC and GND on the module. (But I do not recommend going for that solution)
Use a separate 3V3 power source that is capable of handling the current spikes of the nrf24L01. But don't forget to connect its ground to the Ardino Uno aswell.
Use a power module that powers the nrf24L01 from Arduino Unos 5V rail.

Thanks, I'll try this :)

The built-in regulator might indeed be too bad, some people have measured 100mV noise which would seriously degrade how well the module works. The capacitor solution would probably give you at least some level of usability though.

This is so not true. You can absolutely power the nrf24l01 from the 3.3v out on the Arduino. I have a network of them running like this.

I ordered a power module and now they work nicely :) thanks


text:
Arduino Due as Triggered DMA SPI Slave is possible?
Is it possible for arduino Due to act as DMA-SPI-slave device which can exchange SPI data (uint16_t TX[10] and RX[10]) in triggered slave mode?
I have a setup in which time period is very short (~500uS/cycle). so I need to exchange data with another Microcontroller (acting as 'Master') within the mensioned time limit. Some other tasks are also to be processed. This is why I have to go for DMA and fast data transfer without intervension of processor. All the codes available are to be used in Master mode of SPI. Not a single one is in SLAVE mode.
I wrote a code but I cannot implement a transfer triggered by SPI hardware. Also how to implement data transfer complete Interrupt after all 10 datas(16bit) have been transferred and received?
Here is my initialization code:
    void DMAslaveBegin()
{
    // Configure the pins for SPI in peripheral mode
    PIO_Configure(
        g_APinDescription[PIN_SPI_MOSI].pPort,
        g_APinDescription[PIN_SPI_MOSI].ulPinType,
        g_APinDescription[PIN_SPI_MOSI].ulPin,
        g_APinDescription[PIN_SPI_MOSI].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_MISO].pPort,
        g_APinDescription[PIN_SPI_MISO].ulPinType,
        g_APinDescription[PIN_SPI_MISO].ulPin,
        g_APinDescription[PIN_SPI_MISO].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_SCK].pPort,
        g_APinDescription[PIN_SPI_SCK].ulPinType,
        g_APinDescription[PIN_SPI_SCK].ulPin,
        g_APinDescription[PIN_SPI_SCK].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_SS0].pPort,
        g_APinDescription[PIN_SPI_SS0].ulPinType,
        g_APinDescription[PIN_SPI_SS0].ulPin,
        g_APinDescription[PIN_SPI_SS0].ulPinConfiguration);
    //pmc_enable_periph_clk(ID_SPI0);
#if USE_SAM3X_DMAC
    pmc_enable_periph_clk(ID_DMAC);
    DMAC_Disable();
    DMAC->DMAC_GCFG = DMAC_GCFG_ARB_CFG_FIXED;  //Fixed priority arbiter
    DMAC_Enable();

#if USE_SAM3X_BUS_MATRIX_FIX    // not active here
    MATRIX->MATRIX_WPMR = 0x4d415400;
    MATRIX->MATRIX_MCFG[1] = 1;         //Single Access
    MATRIX->MATRIX_MCFG[2] = 1;         //Single Access
    MATRIX->MATRIX_SCFG[0] = 0x01000010;
    MATRIX->MATRIX_SCFG[1] = 0x01000010;
    MATRIX->MATRIX_SCFG[7] = 0x01000010;

#endif  // USE_SAM3X_BUS_MATRIX_FIX
#endif  // USE_SAM3X_DMAC
    //  initialize SPI controller - Slave mode
    SPI.begin(_pin);
    SPI_Disable(SPI0);
    REG_SPI0_CR = SPI_CR_SWRST;     // reset SPI
    REG_SPI0_CR = SPI_CR_SPIEN;     // enable SPI
    REG_SPI0_MR = 0x10;              // DLYBCS=0, PCS=0, MODFDIS=1, PS=0, MSTR=0(slave)
    REG_SPI0_CSR = 0x80;            // DLYBCT=0, DLYBS=0, SCBR=0, 16 bit transfer, Mode 0/1
    REG_SPI0_IDR = ~SPI_IDR_RDRF;
    REG_SPI0_IER = SPI_IDR_RDRF;
    NVIC_EnableIRQ(SPI0_IRQn);
    SPI_Enable(SPI0);
}

Is this a valid condition for DMA?
How can I utilize SPI ISR handler like system in DMA for my code so that the complete transaction (simultaneous Transmit & Receive) becomes fully automatic without processor utilization?

It is more than likely possible.  However, we lowly Arduino users probably aren't knowledgeable enough about Atmel's SDK and the workings of the Due's MCU to give you the best answer. Your best source of information would probably be a dedicated Atmel ARM MCU forum. One that deals on a more professional level than Arduino.

Thanks. I'll post. but, does DMA callbacks on SPI interrupt?

What does the datasheet / SDK API manual say?

PDC can employ Handler, but I couldn't find DMA Handler for SPI slave mode. The datasheet DMAC section is also messy.

I don't think DMA really cares about what "mode" SPI is running in.

Looking at the datasheet though it only talks about dma in master mode, so maybe it cant...

Your point of view might be right about "DMA really cares about what "mode" SPI is running in".@Majenko. We are using SPI RX and TX Buffers as Source and Destination respectively. So, the SPI hardware is handling all data transfer and Interrupts; after this, DMA takes over for interaction with memory. The DMA and SPI both have a seperate clock and need to be activated seperately. This is the proof that two modules are seperate. Also, DMA is acting on behalf of processor, so it needs to be in master mode. Then, how we can enable and access "Chained buffer transmit complete" interrupt?

I think I have discovered a solution while searching:
https://github.com/avrxml/asf/blob/master/sam/drivers/spi/spi_dmac_slave_example/spi_dmac_slave_example.c It is an example for atmel's sam3X8EK. But the MCU cores are same. Though the code serves different purpose, we can manage to mold it in the direction we need. Only thing remained to do is to push an array through it.
Fellows, what do you think?


text:
Where do I get the wider arduino pro micro from?
I have a bunch of boards already fabricated for a game controller that uses the arduino pro micro. I ran out of the arduinos and ordered more. But the new ones are 0.6" wide from pin to pin, and my boards are 0.8". I got narrower pro micros. Now that I'm looking for it online they all seem to be the narrower ones. Same pinout, but they have a smaller version of the MEGA32U4. It also had a USB mini connector instead of USB micro, but for my purposes that doesn't really matter.
Does anyone know where I can get the older 0.8" width version?

It's open source. Make them yourself?

Thanks, and I could, but the point was to not have to remake my other boards. I've already updated the controller board to fit the new pro micro size. It would be easier to just make more of them than to build more pro micros. It has fewer components.

If you are going through the trouble of building a custom board, why integrate a development board, i.e. the micro; instead you should just make the boards to implement the AVR chip directly. This is what development boards are for; the micros probably cost 4x or more than the parts on them.

Micro PCB is narrower then Pro Micro PCB

Please add URL's to stuff you refers to!

Where do you live? ebay appear to have some wider ones (https://www.ebay.com/itm/New-Pro-Micro-ATmega32U4-5V-16MHz-Replace-ATmega328-Arduino-Pro-Mini-/191673953805)


text:
Frequency Doesn't increase when Button Is Pressed
I’m trying to output a frequency that can be increased and decreased by using 2 buttons.  I’m trying to first of all configure the first button (which increases the frequency). I’m trying to also add button denouncing to not get incorrect button states. I’ve commented out anything that relates to button 2.
#include <TimerOne.h>
//Button States
boolean buttonState = LOW;
//boolean buttonState2 = LOW;

 boolean oldbutton1state = LOW;
//boolean oldbutton2state = LOW;

boolean newbutton1state = LOW;
//boolean newbutton2state = LOW;

//Time period in ms (T)
int period = 1000;
//int period2 = 1000;
float period_float = 1000.0;

//Output pins
int sig_out = 9;
//int sig_out2 = 10;

//Input Pins
int button =2;
//int button2 =3;

void setup()
{
  Serial.begin(9600);
  pinMode(button,INPUT_PULLUP);
  //pinMode(button2,INPUT_PULLUP);
  pinMode(sig_out, OUTPUT);
  //pinMode(sig_out2, OUTPUT);
  Timer1.initialize(1000);
  Timer1.pwm(sig_out,512,period);
  //Timer1.pwm(sig_out2,512,period2);
 }

void loop()
{
   buttonState = digitalRead(button);
   //buttonState2 = digitalRead(button2);
   newbutton1state = debounceButton(buttonState);

    if ((newbutton1state != oldbutton1state) && (newbutton1state == HIGH))
 {
       oldbutton1state = newbutton1state;

     float freq_change = 100.0/1000000.0;
  Serial.println(freq_change);

  period_float = (period_float)/(1+(period_float*freq_change));
  Timer1.setPeriod(period_float);
  Serial.println(period_float);

  Timer1.pwm(9, 512);
  buttonState=LOW;
  Serial.print("Signal 1 Frequency: ");
  float freq = 1000000.0/(period_float);
  Serial.print(freq);
  Serial.println("Hz");

  delay(100);
   }
}

boolean debounceButton(boolean state)
{
  boolean stateNow = digitalRead(button);
  if(state!=stateNow)
  {
    delay(50);
    stateNow = digitalRead(button);
  }
  return stateNow;
}

The issue is, when I load the code onto the Arduino, a 1KHz signal is being outputted, but every time I press button, nothing happens. I just wanted to know if anyone could shed light onto this issue. I think it may be due to the debouncing function (that it doesn’t work properly).

Did you try using a debouncing library?

why do you compare to HIGH? you have INPUT_PULLUP. the input should be always HIGH unless the button grounds the pin

Should i compare to LOW?

how did you wire the buttons? do hey have pull-up or pull-down or do you want to use the internal pull-up?

I have used the pull up formation for the button. So one button pin to ground and a pull up resistor at the other pin

You should use INPUT_PULLUP mode, or add a pull-up resistor, but not both. (INPUT_PULLUP mode internally connects a weak pull-up resistor to the pin, so when you use that mode you don't need an external pull-up resistor. You could probably use both, but then you draw more current than you need to when the button is pressed.)

then pin is LOW if button is pushed


text:
HLW8032 UART sends random data ( Registers Overflow often)
I designed  my own version of smart socket just like the Sonoff with power metering chip HLW8032. And when I read the data in ESP-12F the data doesn't have a fixed format.
To troubleshoot the issue, I bought HLW8032 Breakout Board and analyzed the data sent by HLW8032, and I found the results are the same as the board I designed.
And that made me think that I may be reading the data from the Serial port the wrong way.
HLW8032 sends 24 Bytes on the serial and the format should be like this:
F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9C 2A 39 61 00 00 79
F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9D C2 9F 61 00 00 78

The data that I receive is in this format,
F2 5A 2 D3 70 6 BC D4 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FB EC 17 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FD 84 7D 61 0 1 38 F2 5A 2 D3 70 6 AA 59 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 2 D3 70 6 AA 59 0 3D 4F
4 98 B4 4D E1 80 FE FF 1 61 0 1 38 F2 5A 1 61 0 1 38 F2 5A 2 D3
70 6 AA 59 0 3D 4F 4 98 B4 4D E1 80 FE FF F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FE FF 1 61 0 1 38 F2 5A 2 D3 70 6 AA 59 38 F2 5A 2 D3 70 6 AA 59
0 3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 4F 4 98 B4 4D E1 80 10 1B
D4 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0 3D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 13 4E 9E 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 14 E8 3 61 0 1 39 E1 80 16 82 67 61 0 1 39
F2 5A 2 D3 70 6 AA 59 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0

We can see that the registers overflows again and again.
The code that I use to read the data is:
#include <SoftwareSerial.h>
#define BAUD_RATE 4800

SoftwareSerial swSer(13, 12);

void setup()
{
  Serial.begin(BAUD_RATE);
  swSer.begin(BAUD_RATE);
}

byte data[24];
void loop()
{
  if (swSer.available() > 0) {
    int a = swSer.readBytes(data, 24);
    yield();
  }

  // Display
  for (int i=0;i<24;i++)
  {
    Serial.print(data[i],HEX);
    Serial.print(" ");
  }
  Serial.println();
}

Schematic:

I feel that there is no issue in my hardware design, and the issue seems to be in the sketch.

What can be the possible problem with my setup?

How do I make the output of HLW8032 Stable with no overflow of registers?

Is there any library someone can recommend me to read the data from HLW8032 on SoftwareSerial?
Note: After some troubleshooting I found that delay() cause the problem to be more worse. And won't receive a stream of Bytes whose first byte , second nibble is F like F2, F4, as from the datasheet , first four bits are 1s by default.

It could be that the data is being sent too rapidly (each byte too close together) for SoftwareSerial to be able to cope with it. The only cure would be to not use software serial, but to use an Arduino with the resources you need to connect the device properly

@Majenko Yes, But as the required Baud rate for HLW8032 is 4800bps, and that is quite low. I searched about better alternatives to SoftwareSerial, and found there is AltSoftSerial and I read someone said as to be better than SoftwareSerial for lower baud rates. I gave it a try and the result is the same. Since the chip I'm using is ESP8266 and it only have one HardwareSerial, and I'm using that for Debug logs.

The ESP8266 has two hardware UARTs, not one. Although, you may find that the RX pin isn't exposed on whatever board you have - or if it is, it's not labelled as it.

I would never recommend using any form of SoftwareSerial ever. If you can't do it in hardware on your chosen board / platform, then you are using the wrong board / platform.

Use the Serial1 object in the same way that you would use the Serial object.

error: 'Serial1' was not declared in this scope. (PlatformIO)

@Majenko and due to limitations of the ESP8266, only UART 0 is capable of receiving data.

Well that's [expletive deleted] then isn't it? Upgrade to an ESP32 then.  The ESP8266's peripheral offerings have always been sadly lacking.

which version of the esp8266 boards package do you use? what pins do you use for SoftwareSerial? what esp8266 module do you have? Serial1 must be available. you don't need receive data for debug prints

@Juraj     I'm not using any board(like NodeMCU , Wesmos D1 etc). I'm using my own board which has an ESP-12F module. I use GPIO13 and GPIO12 for the SoftwareSerial.     Serial1 isn't available. I need debug prints , since it's  the first Rev  of the board that I designed, and I must debug and see everything.

@Juraj   But for understanding and troubleshooting the Issue , I got an Arduino UNO board and HLW8032 Breakout board ,  and it has the same result as my board. I've been using SoftwareSerial for quite many applications even receiving data from RS232 port, I never been in any trouble,

@Majenko   An esp8266 SoC has two hardware UARTs , UART 0, and UART 1.                           UART 1 is not capable of receiving data. That's why Serial1 is not defined for esp8266 based boards. That's where I'll follow your advice and Upgrade to and ESP32

https://arduino-esp8266.readthedocs.io/en/latest/reference.html?highlight=serial1#serial

@Juraj Thanks you so much!! That's too comprehensive information. I gave it a try and see  the results.

@Majenko   It is not an issue of SoftwareSerial. I tested the HLW8032 on the Hardware Serial of Arduino Mega using that code and the results are the same that is the registers overflows. Then I used an HLW8032 Library which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different. It's annoying me why it's making issues using readBytes() with me.

First of all I swaped UART0 to GPIO15 (TX) and GPIO13 (RX), (Luckily the Tx of HLW8032 is connected to GPIO13 in my hardware design and This is the UART0 RX pin after swap). Then I analyzed the data coming and the results were the same as of that SoftwareSerial i.e the registers overflows.
Then I used an HLW8032 Library (Which I've forked and will make changes for improvements) which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different.
So in short my issue resolved using two things:

I swaped UART0 to GPIO15 and GPIO13 using Serial.swap()
Used a library for the HLW8032

Thanks to @Juraj who provided the useful link about Serial Swap in ESP8266.

Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0 back to GPIO1 and GPIO3.

#include "HLW8032.h"

HLW8032 HL;

void setup()
{
    HL.begin(Serial,4);
    Serial.begin(4800);
    Serial.swap();
}

unsigned int V;
void loop()
{
    HL.SerialReadLoop();

    if(HL.SerialRead == 1)
    {
    V = HL.GetVol();
    }
}

With this I can't print and see my debug prints on  GPIO1 (TX) and GPIO3 (RX), but at least without changing a bit in the hardware, my design works fine.


text:
No known conversion for argument 1 from 'Object*' to 'int*'
I'm terrible with pointers and need help passing an object to a library I'm writing. I'm getting the error no known conversion for argument 1 from 'LCDMenuItem*' to 'int*' when I try to compile. How do I pass a pointer to an object to a function?
LCDMenu.h
class LCDMenu {
    public:
    bool addItem(LCDMenuItem &item);
    private:
    LCDMenuItem *menuItems[MAX_ITEMS];
    uint8_t itemCount;
};

class LCDMenuItem {
    public:
    LCDMenuItem(char *name);
    bool setFunction(void (*function)(void));
    private:
    bool callFunction() const;
    void (*_function)(void);
    char *name;
};

LCDMenu.cpp
bool LCDMenu::addItem(LCDMenuItem &item) {
    menuItems[itemCount] = &item;
    ...
}

MySketch.ino
LCDMenuItem menuItem("Menu Option");
void setup() {
    menu.addItem(menuItem);
}

When trying to compile

bool addItem(LCDMenuItem *item);
     ^

no known conversion for argument 1 from 'LCDMenuItem*' to 'int*'

what is menuItem and where is bool addItem(LCDMenuItem *item);?

Edited. Do you mean menuItems? its an array of LCDMenuItem's addItem() is in LCDMenu.cpp

menu.addItem(menuItem); menuItem. do you have the classes in that order in .h file?

Oh, sorry. added that to MySketch.ino. I just reordered the classes putting LCDMenuItem first, didn't help.

and bool addItem(LCDMenuItem *item); reported by compiler is where?

i dont have one :) doesnt bool addItem(LCDMenuItem &item) let you pass the object like im trying to do? (obviously not)

it does. it is passing by reference and it is ok. something else is wrong.

do you have some other function called addItem in your sketch?

I don't think so. But i just got it to compile in a new sketch so now I'll track down what is causing that.


text:
How to get a hex file for Samd21 from .ino file
Can you generate a .hex file from an .ino file for the Atsamd21-zero?
I can generate a .bin file but not a .hex file.

what do you want to do with a hex file?

I want to combine the bootloader which is in .hex with the Samd21 file which is in .elf or .bin format.

and then what? bin is uploaded

in platform.txt build.preferred_out_format=bin

You can also manually do it with a arm-none-eabi-objcopy call (this tool is somewhere in your arduino IDE tool folder for the SAMD21 platform) if you do arm-none-eabi-objcopy -O ihex input.bin output.hex


text:
EEPROM: managing address mapping between firmware versions
Is there a common way to handle changes in the mapping between eeprom addresses and variables between firmware versions? It's not about the eeprom memory to survive the update, but to be(come) compatible with future sketches with a possibly different set of variables.
To make it clearer consider the following fictional scenario:
A coffee machine has been programmed to measure water_temperature and the firmware is supposed to stop heating within a temperature_hysteresis
 below set_temperature. set_temperature is a persistent parameter that has been individually optimized be the user and must therefore survive any firmware update. As a configuration parameter also temperature_hysteresis is stored in the eeprom.
Now the manufacturer decides to update his machine with a PID-controller, making the parameter temperature_hysteresis obsolete while he introduces some new parameters for the controller's gains (pid_gains). How can he manage that the firmware keeps values that haven't been touched by the update (like set_temperature) while the additional parameter pid_gains is added.
I assume that obsolete parameters should be removed as there could be more updates with new parameters in the future. That's why simply incrementing the eeprom address and ignoring deprecated addresses probably won't work.
On the other hand, when re-using old addresses I wonder how a fragmentation of the eeprom can be avoided.
I came up with the idea of putting all configuration data into a json in the eeprom and to handle the problem a layer above by parsing the json for configuration data. But anyhow, that feels so wrong and might be too complicate.
Does anyone have experience with this kind of problem and knows how this routine is commonly implemented?

There's lots of ways you could handle this.
Two thoughts right off the top of my head:

Have a "Version" identifier in the EEPROM.

The firmware then needs to know the EEPROM layout of all versions up to the current one. It can then read the EEPROM from the old version and write back a new format for the current version.

Have each entry in the EEPROM tagged with a "meaning".

This is not too different to your JSON idea (which you are right is horrible), but instead of lots of words you just use a simple number to identify the meaning of the value it is associated with.  Assuming that each stored value is an 8-bit byte (though it doesn't have to be), you could allocate "1" as "set_temperature", "2" as "temperature_hysteresis", "3" as "pid_gains", etc, Then the EEPROM might contain the bytes 1,96,2,5 and the firmware would know that the second byte is the set_temperature because it has a 1 in the first byte.
You can think of it as a "key / value" pair, but both the key and the value are just numbers.
To find the temperature_hysteresis you just scan through all the even EEPROM entries until you find 2, then read the next entry. If you don't find a 2 then you use the default value.
Your firmware can then choose to either update an existing cell that is tagged with the right type (scan for type, update next cell), or it could erase all the values and replace them with just the ones it cares about - the choice is yours.
Any values that your firmware no longer cares about will be ignored, and potentially erased.

Thanks for your immediate answer! I don't know if I have fully undestood your first solution, but it sounds like I could still run out of memory after a limited number of updates. But the idea is to do all previous changes in eeprom mapping one after another until the latest version (in case that one has missed some updates in the meantime), isn't it?

your second solution is quite clear in general, but I wonder how to handle datatypes of different size. Do I have to store the size of each value after its "key"-byte or how would you do that?

You could infer the data type from the key.

Yes, wrapping a routine around it to achieve this is another story, but at least that's no mystery to me. Thx

I also have things like look-up tables (not entirely predictable size/structure) that need to be stored. What are the disadvantages of using my json approach in spiffs? I mean, it's in the flash anyway...

Seems straight forward to me: having a config.json and a config_updated.json (which gets updated via ota) and at the very first boot the firmware merges those files.

Looks to me like almost unavoidable that the newer firmware will need at least some understanding of what the old versions stored in the EEPROM. In such a situation, solution 1 seems like the most straightforward.


text:
5xWS2812B in parallel works fine in ESPHome but not in C code?
Facing a weird issue, that is probably something pretty simple, but I've went through ESPHome's code on Github and can't figure out.
I've wired up 5 WS2812B controllers on an ESP8266 (Wemos D1 R1), going from D1 to D5, controlling only 7 LEDs each.
I have the following code in ESPHome:
light:
  - platform: fastled_clockless
    chipset: WS2812B
    pin: D1
    num_leds: 7
    rgb_order: GRB
    name: "Heat #1"

  - platform: fastled_clockless
    chipset: WS2812B
    pin: D2
    num_leds: 7
    rgb_order: GRB
    name: "Heat #2"

  - repeat this 5 times, only thing changing is D1 through D5 and the name

In ESPHome, it works fine, I can control all 5 controllers no problem, both with the HTTP server and the Home Assistant API. I had done that in ESPHome to test the hardware build, since I had ESPHome already setup and it was easy.
I want to setup some Arduino code so that I don't need to depend on ESPHome (this will be a standalone project, that broadcasts an AP and has custom logic).
I have the following sample copied from FastLED's multiple controller example:
#include "FastLED.h"

#define NUM_LEDS_PER_STRIP 7
CRGB leds0[NUM_LEDS_PER_STRIP];
CRGB leds1[NUM_LEDS_PER_STRIP];
CRGB leds2[NUM_LEDS_PER_STRIP];
CRGB leds3[NUM_LEDS_PER_STRIP];
CRGB leds4[NUM_LEDS_PER_STRIP];

void setup() {
    FastLED.addLeds<WS2812B, D1, GRB>(leds0, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<WS2812B, D2, GRB>(leds1, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<WS2812B, D3, GRB>(leds2, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<WS2812B, D4, GRB>(leds3, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<WS2812B, D5, GRB>(leds4, NUM_LEDS_PER_STRIP);
}

void loop() {
    for(int i = 0; i < NUM_LEDS_PER_STRIP; i++) {
        leds0[i] = CRGB::Red;
        leds1[i] = CRGB::Red;
        leds2[i] = CRGB::Red;
        leds3[i] = CRGB::Red;
        leds4[i] = CRGB::Red;
        FastLED.show();
        leds0[i] = CRGB::Black;
        leds1[i] = CRGB::Black;
        leds2[i] = CRGB::Black;
        leds3[i] = CRGB::Black;
        leds4[i] = CRGB::Black;
        delay(100);
    }
}

With this one, I can only control 3 lights: D1, D2 and D5. I've attached a picture of what it looks like. The other 2 just stays white.
https://i.stack.imgur.com/zIrkR.jpg
I'm most likely missing something simple that ESPHome is doing that I am not. It's a long shot, but anyone has a clue?

is it on the same esp8266 module.board?

Same board, yep. I should specify that it's a Wemos D1 R1 dev kit. I don't even disconnect anything, just keep USB plugged in, flash another firmware.

are D pins the same pins?  D1 R1 has different D pins to io pins mapping then R2 or NodeMcu (which have the same) R1: https://github.com/esp8266/Arduino/blob/8dd068eb40b4214f0ba81413d8888ae825e1d0f4/variants/d1/pins_arduino.h#L38 R2 https://github.com/esp8266/Arduino/blob/8dd068eb40b4214f0ba81413d8888ae825e1d0f4/variants/d1_mini/pins_arduino.h#L37. what board did you select in Tools menu?

@Juraj, that was totally it! Looks like my board is a d1_mini variant! Odd as it gets detected as a D1 R1.

so there is a big difference how the mini and the R1/R2 look like. the R2 and mini have the same pin mapping.


text:
Timer 1 Arduino - Create 2 Timers
I’m trying to output 2 separate frequencies using 2 output pins from an Arduino using the Timer 1 library. A snippet of the code is show below.
void setup()
{
 Serial.begin(9600);
 pinMode(button,INPUT_PULLUP);
 pinMode(button2,INPUT_PULLUP);
 pinMode(sig_out, OUTPUT);
 pinMode(sig_out2, OUTPUT);
Timer1.initialize(1000);
Timer1.pwm(sig_out,512,period);
Timer1.pwm(sig_out2,512,period2);
}

The issue is the way I’ve wrote this makes sense as I’ve initialised 2 outputs and 2 inputs but the ‘period’ is getting overwritten as there’s 1 timer and I’m not sure how to stop this. I was thinking about storing them in variables (like 'T1=' 'T2=') but it would still use the same timer.
I just wanted to know if there’s a way to use 2 timers so the Arduino outputs the frequencies separately.

This is not normally how timers work. You can sometimes do some tricks though. Are the periods you want 1. reasonably slow (a few KHz) and/or 2. mathematically related to each other in a simple way (e.g. one is double the other, or 2/3 the other etc.)

Also: Do you realise that a timer is usually a physical bit of hardware inside the chip, so you can't create more of them in software. The chips used in arduinos usually have three hardware timers though, so you could use one of the others?

@Jack B How would I use the other ones?

Normally, with these chips, you configure timers by writing to registers e.g. TCCR1A=0x01;. TimerOne looks like an Arduino-specific library which tries to make it simpler, but I'm not familiar with it. So you options are either to learn how to use the timer control registers directly, or find an Arduino library to do it. I see that there is a TimerThree library, but it doesn't support all boards.

The Timer1 library only supports... Timer 1! So you only have one
hardware timer available. If you are using an Arduino Uno or anything
similar, you have a couple of other timers. However, unlike
Timer 1, which is a 16-bit timer, the others are 8-bit only. This
means they are very limited in the range and precision of the
frequencies they can generate. If you have an Arduino Mega, then you
have a few other 16-bit timers available. You may want to search for a
library called Timer3, which should work just like Timer1, while using
the 16-bit Timer 3.
If you don't find any suitable library, you may still be able to
generate your two signals using only Timer 1. Here is the trick:

set both PWM outputs to “toggle on compare match”
enable both compare match interrupts
in each of these ISRs, advance the compare match register by half a
period of the corresponding signal.

For doing this you will need to dig into the low-level details of how a
timer actually works. I recommend you start by reading the
Timers and counters tutorial by Nick Gammon.
Take the time to read and
study this. It's not a topic you will be able to master in just a
couple of hours.


text:
When GPS can't see satellites, how can I continue to tick off a smooth-ish time?
I'm getting 10 updates/sec from my GPS unit (The MTK3339 used in the Adafruit breakout board), and using it to update a clock display. This works well enough, though there's one minor problem that I'd like to solve and one major one that I have to solve.
The minor issue first; I don't get an update every 100ms. I get one roughly every 100ms... plus or minus about 20-30ms. If a late and an early update arrive back-to-back right when the display goes from n to n+1 seconds, it's noticeable that it's not ticking at a regular cadence. It's not fatal, but the arythmic stutter of it is deeply painful to watch.
The major issue is - what do I do when the GPS can't find a signal? Maybe the device is driving through a tunnel for a minute or there's some other sky obstruction. I still want the clock to update in a best-guess sort of way.
You can't just update the seconds display and then, 1000 (arduino-measured) milliseconds later, update the clock if a new message hasn't arrived. 1000 real-world milliseconds can be anywhere from 700 - 1400ms measured by an arduino, depending on the board and the quality of the crystal. Worse yet, the discrepancy is far from consistent within a single crystal. Seeing the processor speed up and slow down by several percent over the course of a few minutes isn't uncommon.
So what I'd like is a mechanism that will constantly smooth the received (GPS) time to give a best-estimate of current actual time. I'm okay with it being a second or two off (at most) from real time, as long as the cadence feels like actual seconds, and a loss of GPS for a few minutes can be quickly corrected when the signal is re-acquired.
I'm somewhat aware of (strikethrough)DIP(/strikethrough) PID methods, but I'm not sure how to apply them here. It seems that someone must have solved the problem for the sake of syncing internet time, so I shouldn't be reinventing a solution.

why not use the Time library?

Re “[one true second] can be anywhere from 700 - 1400ms measured by an arduino”: Either your Arduino is physically broken, or you are doing something terribly wrong in your code.

Many things can interfere with accurate Arduino time counting; without context it's impossible to know why you're seeing such results--that's pretty far off of anything I've seen on pretty much any Arduino or clone. Why not add an RTC?

What you want, namely something to “smooth the received (GPS) time”,
is called a GPS disciplined oscillator. Obviously, you are not
after the high accuracy of commercial GPSDOs, but the working principle
of what you are describing is essentially the same.

what do I do when the GPS can't find a signal?

In GPSDO lingo, this is called the “holdover” state. At this point you
rely solely on your local oscillator (here, millis() or micros()),
and steer it to correct for is natural drift, as determined while the
GPS reception was good. Or you can go fancy, measure the chip
temperature, and apply a temperature compensation.

I'm somewhat aware of DIP methods, but I'm not sure how to apply them
  here

I guess you mean “PID”.
You apply this to the phase of the oscillator. If the local oscillator
is ahead of the GPS (positive phase error), you lower its frequency. For
example, you could increment the seconds count every 1,000,100
microseconds (as measured by micros()), instead of every 1,000,000.
This will make your clock a little bit slow, and resynchronize it with
the GPS. Conversely, if your clock is behind the GPS, you slightly
increase its frequency to make it run faster.
In other words, the error value of your PID is the phase error of your
clock, and the control variable is the frequency adjustment. By
applying the PID technique this way, you are building what is known as a
phase-locked loop, or PLL. This is the standard way of
implementing a GPSDO.

It seems that someone must have solved the problem for the sake of
  syncing internet time

Sure, but NTP implementations can be quite complex, as they have to deal
with multiple servers having different round-trip delays and different
levels of trust. I am not aware of any Arduino library that does
anything similar. You may search for “time synchronization” or “PLL”. If
you don't find any, you can pick a PID library and apply it to your
oscillator.
A couple of final remarks:

You wrote “speed up and slow down by several percent over the course
of a few minutes isn't uncommon”. This shows there is something
awfully wrong with either your Arduino or your code. Over a few
minutes, you expect frequency variations of the order of one part
per million on an Arduino clocked off a ceramic resonator, and a few
parts per billion if yours is clocked off a crystal. See this
experimental study on the stability of an Arduino clock.
This stability problem is the very first thing you should investigate
and fix.
Many GPS modules have the option to give you a 1PPS (one pulse per
second) signal. If you can use this signal, you may get a quite
accurate measurement of your phase error. Relying on the NMEA
sentences will give you lots of jitter, which you would then have to
compensate for by setting the time constant of the PLL to a very long
value.

An accuracy of 700-1400 ms seems like a big issue on your side. Usually it's like +- 10-20 ms. Are you able to provide your code? Or at least important parts of it? Is it possible that you used the delay function?
If so, you should definitely read into the millis function, and how to use it as a timer. This will significantly improve the "accuracy". Because upon calling the delay function, the chip not only waits a given amount of seconds. The chip also calls the yield function. This one is mostly used to make sure that all background work is done before continuing.
What also might me a problem is every type of modification of the chip clock. I've seen some code where people modify the frequency of the PWM-signal. This also affects the clock in every other way.

A ceramic resonator (like, e.g., on the Uno) is usually something like 0.1% off (1 ms per second). Worst case 0.5% off. A crystal is way better.

You can't just update the seconds display and then, 1000
  (arduino-measured) milliseconds later, update the clock if a new
  message hasn't arrived.

Why not? I'd do just that:

Maintain an in-memory clock
Update whenever a GPS message arrives
Every 1000ms (by millis), tick the clock if a message hadn't arrived, and in any case, update the display.

Something like:
SimpleTimer Timers;
unsigned long MyClock_sec = 0;
bool clockIsTicked = false;

void setup()
{
   Timers.setInterval(10L,  GpsCallback);     // if msg, upd MyClock & set flag
   Timers.setInterval(1000, DisplayCallback); // if no flag, ++MyClock; upd display
}

void loop(){
   Timers.run();
}

void GpsCallback(void){
   // if gps message {
   //    MyClock = <<GPS_TIME>>;
   //    ++clockIsTicked;
   // }
}

void DisplayCallback(void){
   if( !clockIsTicked )
      ++MyClock;

   // update the display
   clockIsTicked = false;
}

(Not compiled or tested - consider it a pseudo-code outline).


text:
Nodemcu single server with 2 clients
I am trying to connect my nodemcu server with 2 nodemcu clients. One client is connected and it works perfectly. I am unable to configure what to do for the other client to be connected and share data through server.
Server Code
/*
Geekstips.com
IoT project - Communication between two ESP8266 - Talk with Each Other
ESP8266 Arduino code example
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
// IoT platform Credentials
String apiKey = "PBD5LAJC4BSV3OKC";
const char* logServer = "api.thingspeak.com";

// Internet router credentials
const char* ssid = "Dhamaal";
const char* password = "03334204224";

ESP8266WebServer server(80);
WiFiClient client;
char * ssid_ap = "ESP_AP";
char * password_ap = "123456789";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_AP);
  setupAccessPoint();
}
// Handling the / root web page from my server
void handle_index() {
  server.send(200, "text/plain", "Get the f**k out from my server!");
}

// Handling the /feed page from my server
void handle_feed() {
  String t = server.arg("temp");
  String h = server.arg("hum");
  String s = server.arg("moi");

  server.send(200, "text/plain", "This is response to client");
  setupStMode(t, h, s);
}

void setupAccessPoint(){
  Serial.println("** SETUP ACCESS POINT **");
  Serial.println("- disconnect from any other modes");
  WiFi.disconnect();
  Serial.println("- start ap with SID: "+ String(ssid));
  WiFi.softAP(ssid_ap, password_ap);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("- AP IP address is :");
  Serial.print(myIP);
  setupServer();
}

void setupServer(){
  Serial.println("** SETUP SERVER **");
  Serial.println("- starting server :");
  server.on("/", handle_index);
  server.on("/feed", handle_feed);
  server.begin();
};

void setupStMode(String t, String v, String m){
  Serial.println("** SETUP STATION MODE **");
  Serial.println("- disconnect from any other modes");
  WiFi.disconnect();
  Serial.println();
  Serial.println("- connecting to Home Router SID: **********");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.println("- succesfully connected");
  Serial.println("- starting client");

  WiFiClient client;

  Serial.println("- connecting to Database server: " + String(logServer));
  if (client.connect(logServer, 80)) {
    Serial.println("- succesfully connected");
    String postStr = apiKey;
    postStr += "&field1=";
    postStr += String(t);
    postStr += "&field2=";
    postStr += String(v);
    postStr += "&field3=";
    postStr += String(m);
    postStr += "\r\n\r\n";
    Serial.println("- sending data...");
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(postStr.length());
    client.print("\n\n");
    client.print(postStr);
  }
  client.stop();
  //Serial.println("- stopping the client");
  /// If your ESP does not respond you can just
  // reset after each request sending
  //Serial.println("- trying reset");
  //ESP.reset();

}

void loop() {
  server.handleClient();
}

and my client code is
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define DHTPIN 0

// AP Wi-Fi credentials
const char* ssid = "ESP_AP";
const char* password = "123456789";

// Local ESP web-server address
String serverHost = "http://192.168.4.1/feed";
String data;
// DEEP_SLEEP Timeout interval
int sleepInterval = 1;
// DEEP_SLEEP Timeout interval when connecting to AP fails
int failConnectRetryInterval = 2;
int counter = 0;
float s;
float h;
float t;
// Static network configuration
IPAddress ip(192, 168, 4, 4);
IPAddress gateway(192, 168, 4, 1);
IPAddress subnet(255, 255, 255, 0);

DHT dht(DHTPIN, DHT11);
WiFiClient client;

void setup() {
  ESP.eraseConfig();
  WiFi.persistent(false);
  Serial.begin(115200);
  Serial.setTimeout(2000);
  Serial.println();
  Serial.println("**************************");
  Serial.println("**************************");
  Serial.println("******** BEGIN ***********");
  Serial.println("- start sensors");
  dht.begin();
  delay(500);
  Serial.println("- set ESP STA mode");
  WiFi.mode(WIFI_STA);
  Serial.println("- connecting to wifi");
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);
  Serial.println("");
  while (WiFi.status() != WL_CONNECTED) {
    if(counter > 20){
       Serial.println("- can't connect, going to sleep");
       //hibernate(failConnectRetryInterval);
    }
    delay(500);
    Serial.print(".");
    counter++;
  }

  Serial.println("- wifi connected");
  Serial.println("- read DHT sensor");
  readDHTSensor();
  Serial.println("- build DATA stream string");
  buildDataStream();
  Serial.println("- send GET request");
  sendHttpRequest();
  Serial.println();
  Serial.println("- got back to sleep");
  Serial.println("**************************");
  Serial.println("**************************");
  hibernate(sleepInterval);
}

void sendHttpRequest() {
  HTTPClient http;
  http.begin(serverHost);
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  http.POST(data);
  http.writeToStream(&Serial);
  http.end();
}

void readDHTSensor() {
  delay(200);
   s = analogRead(A0);
  h = dht.readHumidity();
  t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    t = 0.00;
    h = 0.00;
  }
  Serial.println("- temperature read : "+String(t));
  Serial.println("- humidity read : "+String(h));
  Serial.println("- moisture read : "+String(s));
}

void buildDataStream() {
  data = "temp=";
  data += String(t);
  data += "&hum=";
  data += String(h);
  data += "&moi=";
  data += String(s);
  Serial.println("- data stream: "+data);
}

 void hibernate(int pInterval) {
  WiFi.disconnect();
  ESP.deepSleep(120e6);
  delay(100);
}

void loop() {

}

Kindly help me to change my code so it can be connected with server.

and where is the problem? set a different IP for the other client and that is all

I am confused for that how server will understand that data coming from which ip? i want to send data of both clients on different thingspeak channel.

send some id as parameter

and what changes must be reflected on server?

read the additional parameter


text:
Attiny85: how to rotate the servo continuously with a press of a button?
I'm trying to use two Bluetooth commands in my code:
one is press off a button "1" the servo should do its routine without stop
second one press of the a button "2" servo should stop.
What am I getting with my code is button 1 pressed servo is executing the routine only once and then I need to press again. But I want the routine to loop until I'll stop it.
I'm adding here the code:
  #include <SoftSerial.h>
#include <TinyPinChange.h>
#include <SoftRcPulseOut.h>
#define SERVO_PIN         0

#define REFRESH_PERIOD_MS 4

#define NOW               1

int pos = 0;

SoftRcPulseOut myservo;

SoftSerial mySerial(2, 3); // RX, TX
void setup()
{
 // Open serial communications and wait for port to open:
  mySerial.begin(9600);
  pinMode(greenPin, OUTPUT);
  myservo.attach(SERVO_PIN);

}

void loop() // run over and over
{
  char c = mySerial.read();
  if(c == '1')  selfservo();
  if (c == '2') selfservo2();
}

ok the selfservo() is:
void selfservo()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(REFRESH_PERIOD_MS);        // waits 20ms for refresh period
    SoftRcPulseOut::refresh(NOW);    // generates the servo pulse Now
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(REFRESH_PERIOD_MS);        // waits 20ms for for refresh period
    SoftRcPulseOut::refresh(NOW);    // generates the servo pulse Now
  }
}

and selfservo2() is:
void selfservo2()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree

  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {

  }
}

look at your code ... it says if the button IS pressed then move the servo .... change it to if the button WAS pressed then move the servo ... you do that by "remembering" if the button was pressed

@jsotola tell me more please! how should it look like?

separate the receive data function from the act on the data function  .... define a flag variable such as bool move; ... the received data makes the move variable true or false ... do this at the beginning of the loop() block .... later in the loop() block, perform actions depending on the value of move, not on the value of received data ...... it is basically a simple state machine with two states

That's precisely how I would have described it: you need a variable that indicates whether or not the servo should be rotating, toggled by the button(s). (Two buttons seems overkill, but there may be a specific UX need for this.)


text:
Motor is vibrating in one direction
When I test this program, the motor starts vibrating when proxy1 is low and proxy2 is high. The displayed text also goes wrong.

#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,4,5,6,7);

int ir1=22;
int ir2=26;

int led1=23;

int motor=24;
int motor2=25;

int proxy1=0;
int proxy2=0;

void setup() {
  pinMode(ir1,INPUT);
  pinMode(ir2,INPUT);

  pinMode(led1,OUTPUT);

  pinMode(motor2,OUTPUT);
  pinMode(motor,OUTPUT);
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Everything Is In");
  lcd.setCursor(0,1);
  lcd.println("Order...........");

}
void loop(){
  proxy1=digitalRead(ir1);
  proxy2=digitalRead(ir2);
if((proxy1==LOW)&&(proxy2==HIGH))
{
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Rule Violated!");
  digitalWrite(led1,HIGH);
  digitalWrite(motor2,HIGH);
  digitalWrite(motor,LOW);

}
if((proxy1==LOW)&&(proxy2==LOW)) {
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Everything Is In");
  lcd.setCursor(0,1);
  lcd.print("Order");
  digitalWrite(led1,LOW);
  digitalWrite(motor2,LOW);
  digitalWrite(motor,HIGH);
  delay(2000);
  digitalWrite(motor2,LOW);
  digitalWrite(motor,LOW);
}
else
{
  lcd.setCursor(0,0);
  lcd.clear();
  lcd.println("Everything Is In");
  lcd.setCursor(0,1);
  lcd.print("Order");
  digitalWrite(led1,LOW);
  digitalWrite(motor2,LOW);
  digitalWrite(motor,LOW);
}
}

reverse the wires on the motor and test again ... also, please ask a question

Sounds like EMI


text:
Uploading Firmware to Atmega1284p using ESP8266 with AVRISP as programmer
I am trying to flash a new Firmware to my Ender 3 Pro.
I am using the ESP8266 as an ISP via AVRISP over Wifi.
I have a 10mF capacitor between the ground and reset of the ESP8266
I followed this thread: ESP8266 as ISP program for ATMega16
When uploading I get the following output on console:
C:\Users\Chry>"I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/bin/avrdude" -C "I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/etc/avrdude.conf"
-v -V -p atmega1284p -c arduino -P net:192.168.178.59:328 -b 115200 -D -U flash:w:C:\Users\Chry\AppData\Local\Temp\arduino_build_166520/TH3DUF_R2.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : net:192.168.178.59:328
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_drain(): read error: Falscher Parameter.

avrdude: ser_drain(): read error: Falscher Parameter.

avrdude: ser_drain(): read error: Falscher Parameter.

         AVR Part                      : ATmega1284P
         Chip Erase delay              : 55000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10   128    0 no       4096    8      0  9000  9000 0xff 0xff
           flash         65    10   256    0 yes    131072  256    512  4500  4500 0xff 0xff
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
         Hardware Version: 4744608
         Firmware Version: 0.2
         Topcard         : STK502
         Vtarget         : 1.8 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10

avrdude done.  Thank you.

I can't seem to get it to work. Does anyone have any ideas?
I tried programming it directly:
I use the standard Arduino ISP sketch on my ESP8266 and try to upload that way. Directly connected the ESP8266 to my computer. I get sync-problems now: avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x61
The Board in the arduino IDE is set to Sanguino 1284p and the programmer is set to Arduino as ISP.

I have a 10mF capacitor between the ground and reset of the ESP8266. I'll edit that info in the question as well.

found this ... https://github.com/arduino/Arduino/issues/730

That goes beyond my understanding. I changed plans though. I use the standard Arduino ISP sketch on my ESP8266 and try to upload that way. Directly connected the ESP8266 to my computer. I get sync-problems now: avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x61

you are not alone https://github.com/esp8266/Arduino/issues/6517#issuecomment-531480035 I will try it today. I tested it in Jan 2018 and it worked then

https://github.com/esp8266/Arduino/issues/6519#issuecomment-531551733

10milliFarad, or 10microFarad?  0.1microFarad is generally used when you are trying to create a Reset pulse for serial downloads. For programming via the SPI pins - SCK, MOSI, MISO - Reset is controlled directly.

I assume that you have to wrap the directory in the option -U flash:w:C:\Users\Chry\AppData\Local\Temp\arduino_build_166520/TH3DUF_R2.ino.hex:i with "s. I don't promise that it'll work with that change, but C:\Users... will definitely confuse the parser due to the :!


text:
How to make procedures triggered remotely
I am installing lights in a model train and there are multiple prototypical lighting procedures that need to be activated. The lights are connected as follows:
Headlight Top - Pin 1
Headlight Bottom - Pin 2
Front Right Marker - Pin 3
Front Left Marker - Pin 4
Rear Right Marker - Pin 5
Rear Left Marker - Pin 6
Rear Left Headlight - Pin 7
Rear Right Headlight - Pin 8
Front Right Ditch Light - Pin 9
Front Left Ditch Light - Pin 10
I would like to simply address a forward procedure which would turn on pins 1, 2, 3, 4, 5, 6, 9, and 10. This is the lighting configuration when the loco is shifted into the forward gear. For reverse, pins 3, 4, 5, 6, 7, and 8 would be activated. There will be a few others too but those are the primary procedures. Is there a way I could set up a variable which names all those pins at once? Or is there some other way I could name a forwards or backwards lighting procedure with a single short name such as "Procedure 2"? I am using Arduino IDE.

perhaps an array and a loop? (dont have the Arduino IDE atm, so sorry about any typos)
int lights[] = {1, 2, 3, 4, 5, 9, 10};
int count = 7;//because there are 7 items in the array
//

main(){
    for (int i = 0; i < count; i++){
         digitalWrite(lights[i], HIGH);
         delay(1000);
    }
}

EDIT: still no IDE, but here is a little more depth.
forward(true) = forward lights on
forward(false) = forward lights off
reverse(true) = reverse lights on
reverse(false) = reverse lights off
void forward(bool state){
    int lights[] = {1, 2, 3, 4, 5, 6, 9, 10};
    int count = sizeof(lights) / sizeof(lights[0]);

    for (int i = 0; i < count; i++){
        switch (state){

            case true: //turn on
                digitalWrite(lights[i], HIGH);
                break;

            case false: //turn off
                digitalWrite(lights[i], LOW);
                break;
        }
        //delay(1000); //optional delay between lights?
    }
}

void reverse(bool state){
    int lights[] = {3, 4, 5, 6, 7, 8};
    int count = sizeof(lights) / sizeof(lights[0]);

    for (int i = 0; i < count; i++){
        switch (state){

            case true: //turn on
                digitalWrite(lights[i], HIGH);
                break;

            case false: //turn off
                digitalWrite(lights[i], LOW);
                break;
        }
        //delay(1000); //optional delay between lights?
    }
}

I would like to simply address a forward procedure which would turn on
  pins 1, 2, 3, 4, 5, 6, 9, and 10.

And what about pins 7 and 8? You didn't say what to do with them in the
forward procedure. Should they be turned off? Should they stay in
whatever state they were before? I know it is kind of obvious to you,
but it doesn't hurt being specific, for the benefit of those lacking the
required background. Lacking a complete specification, we are left to
making assumptions.
kei, in his answer, assumed that any pin you did not mention should be
left alone, in whatever state it was before. In this answer I will
instead assume that you want to always control the 10 pins, turning
each of them either on or off.
With this assumption, the obvious solution is to have, for each
procedure, an array of 10 “states” (either HIGH or LOW), and loop
through the array setting each pin to its appropriate state:
for (int i = 0; i < LED_COUNT; i++)
    digitalWrite(led_pins[i], pattern[i]);

Here, pattern[i] is the state associated to led_pin[i] in this
specific procedure. Now, since all these pins are consecutive, you don't
need the led_pins array, and you can replace led_pins[i] by
i + FIRST_LED_PIN (i.e. i+1).
This way you can implement as many procedures as you want, each one
being defined as a simple 10-number array. I would add a single
function to activate any procedure. This function would take as an
argument a pointer to the light pattern you want to apply:
const uint8_t FIRST_LED_PIN = 1;
const int LED_COUNT = 10;
const uint8_t formward_pattern[LED_COUNT] = {
    HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW,  LOW,  HIGH, HIGH
};
const uint8_t reverse_pattern[LED_COUNT] = {
    LOW,  LOW,  HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW,  LOW
};

void set_led_pattern(const uint8_t *pattern)
{
    for (int i = 0; i < LED_COUNT; i++)
        digitalWrite(i + FIRST_LED_PIN, pattern[i]);
}

With this in place, you can set the light pattern of the forward
procedure by issuing the single statement:
set_led_pattern(formward_pattern);

and for the reverse procedure:
set_led_pattern(reverse_pattern);


text:
How to remove the 5 second boot delay on Digispark PRO (Attiny167)
I know there’s already a solution for removing the 5 seconds boot delay on Digispark (Attiny85), by writing a new bootloader someone already did to the Digispark. And to write code to it, you need to ground one pin.
This delay exists so the Attiny85, when powered on, waits for USB programming. Only after 5 seconds it will run the code written to it..
But I can’t find information on how to remove this 5 second delay on the Attiny167 - Digispark PRO.
Could the same modified bootloader of the Attiny85 be burned on the 167?
Or is there any other way to do it?
Thanks a lot!

I don't see the delay in the code, only in the command line util. What bootloader are you using?

@DaveNewton I’m using the stock bootloader. The firmware of the Digispark Pro is 2.2. Everytime it powers on the internal led flashes for 5-6 seconds and only then any code written to it is executed. I’d like to power up the Digispark PRO and any code be executed imediatelly. Every Digispark PRO behaves this way, as far as I know. I don’t know if the correct name is delay, but when powered on, the board waits for this 5 seconds to check if any code is about to be written through the USB port. If not, it executes de code that was already uploaded to it.


text:
Arduino Uno + Sim808 GPS dont work with GSM
I am trying to get GPS data and pass it through GSM (Http Get Request). The GPS codes part works fine alone, also HTTPRequest part lonely. But when i use them together , the module don't get GPS data to send with GSM!
I've commented parts for more understanding.
//Include Libraries
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

//Define module connect pins
#define PIN_TX    12
#define PIN_RX    13
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

//store response from website
char buffer[256];

//store Http request
char datas[83];

//store GPS latitude
float lat;

//store GPS longitude
float lon;

//store GPS latitude as text
char la[8];

//store GPS longitude as text
char lo[8];

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

//Temporary for prevent of connection error from network! added now
  delay(2000);
  sim808.close();
  sim808.disconnect();
  sim808.detachGPS();
  delay(2000);

  while(!sim808.init()) {
      Serial.print("Sim808 init error\r\n");
    }
    Serial.println("Sim808 init success");

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");
 while(!sim808.join(F("mcinet"))) {
      Serial.println("join network error");
  }
  Serial.println("join network success");

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //*********** Establish a TCP connection ************
  while(!sim808.connect(TCP,"332b8a09.ngrok.io", 80)) {
      Serial.println("Connect error");
  }

}

//this function get latitude and longitude and put them in variable (datas) for http request

void http(float loni, float lati){
    dtostrf(lati, 6, 6, la);
    dtostrf(loni, 6, 6, lo);

    strcpy(datas,"GET /index.php?lat=");
    strcat(datas, la);
    strcat(datas, "&long=");
    strcat(datas, lo);
    strcat(datas," HTTP/1.1\r\nHost: 332b8a09.ngrok.io\r\n\r\n\r\n\r\n");
}

void loop() {
    if(sim808.getGPS()) {
//get GPS data
    lat = sim808.GPSdata.lat;
    lon = sim808.GPSdata.lon;

//send GPS data to http function for put them into http request
    http(lat,lon);

    //*********** Send a GET request *****************
    Serial.println("waiting to fetch...");
    sim808.send(datas, sizeof(datas));
    while (true) {
        int ret = sim808.recv(buffer, sizeof(buffer)-1);
        buffer[ret] = '\0';
        Serial.print("Recv: ");
        Serial.print(ret);
        Serial.print(" bytes: ");
        Serial.println(buffer);
        break;
      }
    }
    delay(3000);
    Serial.println("Another Attemp...");
}

I Use sim808 EVB-V.3.2.4 module and Arduino Uno.
And this is the serial prints of program:
Sim808 init success
Open the GPS power success
join network success
IP Address is
102.168.24.54
Another Attemp...
Another Attemp...
Another Attemp...
Another Attemp...
Another Attemp...
.
.
.
And goes on Infinity Another Attemp...

I must get printed string : "waiting to fetch..." and some other strings before each "Another Attemp..."

thanks. i will do that and will comment the result

well, any of that ways not worked! the gps lat long is 00.00000

start with the GPS example code ... make sure that it works as expected ... then add the GSM code in sections ... test after each addition ... start by adding all of the declarations before setup() .... then add program lines to setup() one at a time .... that should reveal what causes your code to break

Omg this is continuing on not working! step by step, but fail!

what are you doing? .... you don't continue adding code when it fails .... you try to figure out why the added code made it fail ... so, what made the GPS example code fail?


text:
VS2019CE/VisualMicro project won't compile without specific reference
I have a small project to test a Sparkfun MPU9250 breakout board.  'Class_MPU9250BasicAHRS_t3.h', 'MPU9250BasicAHRS_t3.h' and 'Class_MPU9250BasicAHRS_t3.cpp' are all in the local project folder. Compile fails with an 'undefined reference' error at any reference to the Class_MPU9250BasicAHRS myIMU object  unless I add 'Class_MPU9250BasicAHRS_t3.cpp' to the project as a 'Source File' in the Solution Explorer window.
Why is this?  I thought the compiler was smart enough to look for a .cpp file with the same name as an #include'd header file.
TIA,
Code attached:
/*
    Name:       Teensy_MPU9250_Test.ino
    Created:    9/15/2019 11:46:10 AM
    Author:     FRANKWIN10\Frank
*/

/*  All this program does is display heading values from a Sparkfun MPU9250
    breakout board at the default (0x68) I2C address
*/

#include "Class_MPU9250BasicAHRS_t3.h" //extracted all #defines from MPU9250BasicAHRS_t3.ino
#include <i2c_t3.h>
#include <elapsedMillis.h>

elapsedMillis sinceLastPrint;
Class_MPU9250BasicAHRS myIMU;

int pulsePin = LED_BUILTIN;//04/10/18 added per-step pulse pin parameter
bool bFirstTime = true;
const long MSEC_PER_PRINT = 100;

void setup()
{
    Serial.begin(115200);
    delay(3000); //delay required to wait for Serial object creation
    //Wire.begin();

    pinMode(LED_BUILTIN, OUTPUT);
    Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, 400000);
    Wire.setDefaultTimeout(200000); // 200ms

    //IMU init & test
    Serial.println("Starting program...");
    Serial.println("Initializing 9250 IMU...");
    myIMU.init9250IMU();
    Serial.println("Done...");
}

void loop()
{
    float hdg_deg = myIMU.GetIMUHeadingDeg();
    if (bFirstTime)
    {
        bFirstTime = false;
        Serial.printf("Msec\tHdg\n");
    }

    if (sinceLastPrint > MSEC_PER_PRINT)
    {
        Serial.printf("%lu\t%4.2f\n", millis(), hdg_deg);
        sinceLastPrint -= MSEC_PER_PRINT;
    }
}

it is probably by design, so that you could have files in the same folder that would not be processed by the compiler .... useful if you are testing different versions of the same file

Hmm, hadn't thought of that angle....


text:
Arduino error in code Stack smashing protect failure!
I get the error when I compiled my code below. I am making an application to read temperature on board ttgo esp32 oled lora
stack smashing protect failure!

abort() was called at PC 0x400da3e8 on core 1

Backtrace: 0x4008b8f4:0x3ffb1ec0 0x4008bb21:0x3ffb1ee0 0x400da3e8:0x3ffb1f00 0x400d0f69:0x3ffb1f20 0x400d0f73:0x3ffb1f50 0x400d366e:0x3ffb1f70 0x400d12f7:0x3ffb1f90 0x400d68a9:0x3ffb1fb0 0x40087a71:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 188777542, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1100
load:0x40078000,len:9344
load:0x40080400,len:6348
entry 0x400806a8
Node v0.2
Trigger Temps
Read Temps = 25.50
Read Temps = 25.50
Send Temp: 25.50
Packet queued
238190: EV_TXCOMPLETE (includes waiting for RX windows)

Code is in => https://github.com/Mangulomx/ds18b20_lora1/blob/master/ds18b20_1_lora.ino

why are you using the arduino-uno tag?

when I compiled my code below - a) there is no code below, and b) that doesn't look like a compilation error, more like a runtime error


text:
How to control 30 stepper motors using Arduino?
To prototype my project, I'm going to use an Arduino. I need to control 30 step motors.
4 of these step motors should always be ready to work, no matter other motors are working or not. But the other 26 motors never work in the same time (only one or none of these 26 step motors work at the same time).
So I'm looking for a fast and cheap way to prototype my machine and I need your advice.
I think a CNC Shield or 4 EasyDriver can do the job for controlling those 4 step motors (those motors which need to be ready to work at any moment of time).
But for the other 26 step motors (which can be controlled one by one) is there a way to avoid using 26 EasyDrivers or stacking several other shields? Is there a way to control those 26 step motors using a single driver?
Thanks.

@jsotola, Thanks for reply. There is no need to stay in holding position. When one of those 26 step motors are rotated for n steps, we can safely turn the motor off until the next time we need it. So we can use the driver for another motor.

this question is not really about the Arduino, but about stepping motor drivers and should be moved to https://electronics.stackexchange.com/questions

https://forum.arduino.cc/index.php?topic=123547.0, https://reprap.org/forum/read.php?2,196989, https://electronics.stackexchange.com/questions/266213/multiplexing-h-bridge-stepper-control, etc. Personally... meh. You can get a cheap stepper controller for like $1-1.5 w/o even trying, and it'll be easier to multiplex the control signals rather than the driver output.

Have a microcontroller + driver per motor and network them all together to a master controller.


text:
Is it possible to write URLs to RFID tags with the RC522? If so, how?
I've been trying to research to answer this question for a long time, but could not figure out the answer. I know how to code like bytes of information, but not URLs. More specifically, when you code information into a MiFare RFID tag with the RC522 device, each byte goes into separate byte blocks of a sector. They are not combined, meaning the link cannot be read. How do you overcome this and is this even possible?

http://asciitable.com/

that makes sense now ... why is it that your question does not say that? .... edit your question and delete the comments


text:
74HC595 not working properly
I've used the following code to light 8 yellow leds sequentially but it only runs as it's supposed to be on Proteus. However in my breadboard the 8 leds keeps blinking all together, the resistors used are 220 ohms. Also when i'm trying to change the value of the variable "leds" to be for example 0x0F, it doesn't light, I've read in the Arduino shiftout tutorial that 0.1F capacitor on the latch pin will even the flickers so now I'm really confused.
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

byte leds = 0;

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

void loop()
{
  leds = 0;
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(100);
  }
}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);

}

The delay after "updateShiftRegister" is only 100ms? This means that within a second all LED's get updated. This would make them appear like blinking?
Also; did you try the 0.1F capacitor?

what does blinking all together mean?

SOLVED!
 i've tried many solutions to make it work but it just didn't and here are the solutions i tried
a) to use  0.1µf or 10µf between VCC and ground pin of the 74hc595 .
b) to set the clockPin and dataPin zero before sending data .
c) replacing the resistors from 220 ohm to 470 .
however,  i connected pin13 of the 74HC595 to an arduino pin and drive it to zero so the 8 output are ready to go then digitalWrite(out_enable_Pin, HIGH) ,send data as shown in the following code then digitalWrite(out_enable_Pin, LOW) again .
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int out_enable_Pin=13;
int resetPin=5;
char leds = 0;

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

void loop()
{
  digitalWrite(out_enable_Pin, LOW);
  digitalWrite(resetPin, HIGH);

  for (int i = 0; i <255; i++)
  {
    leds=i;
    updateShiftRegister();
    delay(1000);
  }
}

void updateShiftRegister()
{
    digitalWrite(out_enable_Pin, HIGH);
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, MSBFIRST, leds);
   digitalWrite(out_enable_Pin, LOW);
   digitalWrite(latchPin, HIGH);
}


text:
Arduino ESP8266 communication
I saw two peculiar things while googling this subjects.

Sometimes Tx and Rx are connected directly despite the fact, that it works on different voltages, sometimes resistor dividor is used, sometimes it goes through resistor. Why no consensus? What are differences?
Why contributors are so stubborn to use software UART? Is there any reason I can't understand, that should stop me from using built in UART?

Sometimes Tx and Rx are connected directly despite the fact, that it works on different voltages, sometimes resistor dividor is used, sometimes it goes through resistor. Why no consensus? What are differences?

There is some uncertainty as to whether the ESP8266 has 5V tolerant inputs or not.  This uncertainty stems from differences in an early Chinese datasheet translated by the community, and the current English datasheet.  It's better to err on the side of caution though and translate your 5V signal from the Arduino to a 3.3V one with either a proper logic level translator or a resistive divider (note that the latter can limit the maximum baud rate you can use).
You can read more here:

https://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/

Why contributors are so stubborn to use software UART? Is there any reason I can't understand, that should stop me from using built in UART?

Bad information begets bad information. People copy poor quality examples and tutorials and pass that bad knowledge on to others1.
Many Arduino boards only have one hardware UART port, and that is shared with the USB connection to the PC.  It is hard to reliably use that UART for other serial communication, since doing so will break your ability to upload code while your hardware is connected.  So it's simpler in that case to use SoftwareSerial (or one of the better implementations).
However, I would never advocate using SoftwareSerial unless you absolutely have to.  It barely functions at 115200 baud (one of the common default ESP8266 baud rates).  If you have a convenient hardware UART then really you must use it, for the sake of your sanity if nothing else.

1: Even worse though are the examples where people use SoftwareSerial to communicate over the pins of a hardware UART... that's just plain stupid...


text:
Camera VC0706 send image save to pc
i'm working on project now,
i need to save picture from camera VC0706 serial camera in specific folder on my PC, i found a tutorial (indonesian tutorial), thath give me code to use the camera, but they not tell me how to save the picture,
basically i need this image show on android phone, but i don't have money to buy a paid web server that can store image, so i want to use local webserver (PhpMyadmin using Xammpp) and call the image from htdoc folder, so i can show the image on android phoe
here is the code
 #include <Adafruit_VC0706.h>
#include <SoftwareSerial.h>

// Software serial & camera instance
SoftwareSerial cameraconnection = SoftwareSerial(2,3); // RX, TX
Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

void setup() {

  Serial.begin(115200);
  Serial.println("Program Test Camera");

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Terbaca");
  } else {
    Serial.println("Camera Tidak Terbaca !!!");
    return;
  }

  // Set ukuran gambar
  cam.setImageSize(VC0706_640x480);   // Vga
  //cam.setImageSize(VC0706_320x240); // Qvga
  //cam.setImageSize(VC0706_160x120); // QQVGA
  // Tunggu 3 detik untuk capture
  Serial.println("Picture in 3 seconds ...");
  delay(3000);

  if (! cam.takePicture())
    Serial.println("Failed to capture!");
  else
    Serial.println("Capture Gambar OK ");
}

void loop() {
}

why don't you start with the example code that is included with the library?

@jsotola library of what?

The examples of the Adafruit_VC0706 library. It shows, how to save an image to a SD card. For sending it over wifi, you first need a wifi module. You can buy an ESP8266 module for that, though it might be a better idea to directly use an ESP instead of the Mega


text:
How to count the number of rising edges on DS3231 rtc?
I am using a DS3231 rtc and I would like to get millisecond accuracy from it so I decided to use the 32kHz generated clock from it. I wrote a code that would count the rising edges or falling edges using an interrupt with (RISING or FALLING parameters) but I get only zeros on my Serial board for the count.
Here is the code I am using :
#include <DS3231.h>
#include <RTClib.h>
#include <Wire.h>
#include "rtc.h"
#define InterruptPin 3

volatile long lcnt = 0;

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  Serial.begin(74880); // init serial port
  pinMode(InterruptPin, INPUT_PULLUP);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
  attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
}
void loop() {
  unsigned long a=millis();
  if (a<1000){
  Serial.println(lcnt);
  }
}

void fcnt(){
  lcnt+=1;
}

I just want to check how many rising edges I have in 1s. What is strange is that this code used to work and now it doesn't ^^'... I don't know if I changed something by mistake or deleted something useful.
Can somebody help me to resolve this little problem ?
Thanks a lot for your time !

try disabling the pullup resistor on the input pin

I'm not sure why you're getting 0 as such, but your interrupt and variable methodology leaves a lot to be desired (probably the cause of the "tutorials" you followed).
My primary concern is that you are using a 32-bit "long" variable in an interrupt, and referencing that directly outside the interrupt.  The Arduino is an 8-bit system, which means that all accesses to that variable take many instructions to arrange (splitting it down into 4 8-bit values, manipulating it, recombining it, etc).  Because of this no operations on that variable are "atomic".
You need to make them atomic.  If you don't then it's perfectly possible for the interrupt to trigger and modify the value in the middle of you doing something with that value.
The simplest way of making it atomic is to disable interrupts, then copy the value to another variable and/or modify it, and enable interrupts again.
Here's an example that I would consider stable:
#include <DS3231.h>
#include <RTClib.h>
#include <Wire.h>
#include "rtc.h"
#define InterruptPin 3

volatile uint32_t lcnt = 0;

RTC_DS3231 rtc;

void setup() {
  Wire.begin();
  Serial.begin(74880); // init serial port
  pinMode(InterruptPin, INPUT_PULLUP);
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
  attachInterrupt(digitalPinToInterrupt(InterruptPin), fcnt, FALLING);
}

void loop() {
  static uint32_t ts = millis();
  uint32_t a = millis();
  if (a - ts >= 1000) {
    ts = a;
    noInterrupts();
    uint32_t currentCount = icnt;
    icnt = 0;
    interrupts();
    Serial.println(currentCount);
  }
}

void fcnt(){
  lcnt+=1;
}

That should print the number of pulses over successive 1 second periods.

Thank you for your answer, I uploaded your code and I still get only zeros each second on my screen...

@JamesONeil Then you should triple check your wiring.

I already use one interrupt from the ds3231 for the alarm on the pin SQW to wake up my arduino and it works fine so the problem can come only from the pin of the 32kHz clock. I double checked my wiring and nothing wrong there...

I used the same code as yours and simply changed the datatype from uint32_t to unsigned long and it started working. May be you can try the same.