text:
arduino acclerometer with servo motor
I'm currently working on project to operate three motors while sending accelerometer value to computer via bluetooth module. I want the motor operation and value transmission to work seperatly. But when motors operate, the transmission stops. I used the ArduinoThread library, but since I don't understand all the usage, it still has some kind of delay. Plus, I want two of the motors work first(just once) and the other works after specific time(also just once). But the first setup of two motors and the latter doesn't work. Please check my code and give me some advice. Thank you!
#include <Wire.h>
#include <SoftwareSerial.h>
#include <Servo.h>
#include <Thread.h>

const int MPU_addr=0x68;  // MPU-6050 I2C address
int16_t AcX,AcY,AcZ,GyX,GyY,GyZ;

SoftwareSerial BTSerial(3,2);   // TX,RX

Servo servoMini;
Servo servoUp;
Servo servoDown;
int pinMini = 6;
int pinUp = 9;
int pinDown = 10;
int i = 1;
unsigned long tPrev, tNow = 0;

Thread myThread = Thread();

void readAcc(){
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers   // 14bit??

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  //AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  //AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  //GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  //GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  //GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  BTSerial.println(AcX);   // 16bit
  Serial.println(AcX);

  // delay(25);
}

void setup(){
  // I2C
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)

  // serial, bluetooth
  Serial.begin(9600);
  BTSerial.begin(9600);
  Serial.println("CLEARDATA");
  Serial.println("ONLY AcX");

  // servo
  servoMini.attach(pinMini);
  servoUp.attach(pinUp);
  servoDown.attach(pinDown);
  pinMode(pinMini, OUTPUT);
  pinMode(pinUp, OUTPUT);
  pinMode(pinDown, OUTPUT);
  servoMini.write(145);
  servoUp.write(180);
  servoDown.write(0);

  // Thread(MPU-6050)
  myThread.onRun(readAcc);
  myThread.setInterval(20);
}

void loop(){
  while(i == 1){
    tNow = millis();
    myThread.run();

    servoUp.attach(pinUp);
    servoDown.attach(pinDown);
    servoUp.write(60);
    servoDown.write(120);

  if((tNow - tPrev)>= 1000){
    servoMini.attach(pinMini);
    servoMini.write(180);
    i++;
  }
}

  servoMini.detach();
  myThread.run();
}

Your loop() function makes no sense to me. What is your intention with that code?

To read the value from an accellerometer (I²C bus) and process/use these readings to control the servo (bluetooth, probably in opposite direction?)

I think you'll probably have to look at DSP (digital signal processing). Perhaps something like this, but I haven't done this sort of things lately. You can indeed use a thread to read the values and store them in variables, another thread for dsp for delaying the signal, and a third to control the servo.

@Majenko I want two motors which is servoUp and servoDown to move first just once. And after 1seconds, the other motor to move once. So I used while(i ==1). Since need to check the value form the acclerometer, so I used myThread.run() again, but I'm not sure.

@Pieterjan The accelerometer and motor doesn't have meaningful connection. The value from sensor is sent to computer and modified for analysis seperately. I'm going to change the angle that motor moves and velocity of servomotor to check difference in acceleration.

Here's the final form of my project.
I've added motor detach function since it still shivers a bit.
#include <SoftwareSerial.h>
#include <Servo.h>

const int MPU_addr=0x68;  // MPU-6050 I2C address
int16_t AcX,AcY,AcZ,GyX,GyY,GyZ;

SoftwareSerial BTSerial(3, 2);  // TX, RX

Servo servoMini;
Servo servoUp;
Servo servoDown;

const byte pinMini = 6;
const byte pinUp = 9;
const byte pinDown = 10;

// Timings for each event.
const unsigned long ACC_INTERVAL = 50;
const unsigned long INTERVAL = 1000;
const unsigned long INTERVAL_FIN = 2000;
const unsigned long GRIPPER_INTERVAL = 2000;
const unsigned long GRIPPER_INTERVAL_FIN= 3000;
const unsigned long LED_INTERVAL = 250;

// Keep track of timestamps for each event.
unsigned long prev_led_timestamp;
unsigned long prev_acc_timestamp;
unsigned long servo_timestamp;
unsigned long servo_timestamp_fin;
unsigned long gripper_timestamp;
unsigned long gripper_timestamp_fin;

// Flags to indicate completion of "just once" events.
bool servo = false;
bool servo_fin = false;
bool gripper = false;
bool gripper_fin = false;

// State of blinking LED.
bool led_state = false;

void readAcc(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers   // 14bit??

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  //AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  //AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  //GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  //GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  //GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  BTSerial.println(AcX);   // 16bit
  //Serial.println(AcX);
}

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

  // For blink without delay.
  pinMode(LED_BUILTIN, OUTPUT);

  // I2C
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

  // servo
  servoMini.attach(pinMini);
  servoUp.attach(pinUp);
  servoDown.attach(pinDown);

  // Perform first move.
  servoMini.write(145);
  servoUp.write(180);
  servoDown.write(0);

  // Initialise all timestamps with the same value with a single call to millis().
  prev_led_timestamp =
  prev_acc_timestamp =
  servo_timestamp = servo_timestamp_fin =
  gripper_timestamp = gripper_timestamp_fin = millis();
}

void loop(){
  unsigned long current_timestamp = millis();

  // TASK 1: Read acc.
  if (current_timestamp - prev_acc_timestamp >= ACC_INTERVAL){
    // Read acc.
    readAcc();
    prev_acc_timestamp += ACC_INTERVAL;
  }

  // TASK 2: Just once.
  if (!servo && current_timestamp - servo_timestamp >= INTERVAL)  {
    //Serial.print("Running just once... ");
    servoUp.attach(pinUp);
    servoDown.attach(pinDown);
    servoUp.write(60);
    servoDown.write(120);
    // retract speed control
    servo = true;
    //Serial.println("Done.");
  }
  if (!servo_fin && current_timestamp - servo_timestamp_fin >= INTERVAL_FIN){
    servoUp.detach();
    servoDown.detach();
    servo_fin = true;
  }

  // TASK 3: Also just once.
  if (!gripper && current_timestamp - gripper_timestamp >= GRIPPER_INTERVAL)  {
    // Perform third move.
    //Serial.print("Running also just once... ");
    servoMini.write(180);
    gripper = true;
    //Serial.println("Done.");
  }
  if (!gripper_fin && current_timestamp - gripper_timestamp_fin >= GRIPPER_INTERVAL_FIN){
    servoMini.detach();
    gripper_fin = true;
  }

  // TASK 4: Blink without delay.
  if (current_timestamp - prev_led_timestamp >= LED_INTERVAL){
    // Toggle LED state.
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    prev_led_timestamp += LED_INTERVAL;
  }
}

I think you want something like Blink Without Delay, but with more tasks.
Here is my interpretation of your description which extends Blink Without Delay by adding three more tasks to:

read the accelerometer
perform "just once"
perform "also just once"

I've added several Serial.print() statements to give a running commentary on what's occurring for debug purposes.
#include <Wire.h>
#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial BTSerial(3, 2);  // TX, RX

Servo servoMini;
Servo servoUp;
Servo servoDown;

const byte pinMini = 6;
const byte pinUp = 9;
const byte pinDown = 10;

// Timings for each event.
const unsigned long READ_ACCELEROMETER_INTERVAL = 50;
const unsigned long JUST_ONCE_INTERVAL = 1000;
const unsigned long ALSO_JUST_ONCE_INTERVAL = 2000;
const unsigned long LED_BLINK_INTERVAL = 200;

// Keep track of timestamps for each event.
unsigned long previous_blink_timestamp;
unsigned long previous_accelerometer_timestamp ;
unsigned long just_once_timestamp;
unsigned long also_just_once_timestamp;

// Flags to indicate completion of "just once" events.
bool just_once = false;
bool also_just_once = false;

// State of blinking LED.
bool led_state = false;

void setup()
{
    Serial.begin(115200);
    Serial.println("\n\nAccelerometer with Servo Test\n");

    // For blink without delay.
    pinMode(LED_BUILTIN, OUTPUT);

    // servo
    servoMini.attach(pinMini);
    servoUp.attach(pinUp);
    servoDown.attach(pinDown);

    // Perform first move.
    servoMini.write(145);
    servoUp.write(180);
    servoDown.write(0);

    // Initialise all timestamps with the same value with a single call to millis().
    previous_blink_timestamp =
    previous_accelerometer_timestamp =
    just_once_timestamp =
    also_just_once_timestamp = millis();
}

void loop()
{
    unsigned long current_timestamp = millis();

    //
    // TASK 1: Read accelerometer.
    //
    if (current_timestamp - previous_accelerometer_timestamp >= READ_ACCELEROMETER_INTERVAL)
    {
        // Read accelerometer.
        Serial.print("Reading accelerometer... ");
        readAcc();
        previous_accelerometer_timestamp += READ_ACCELEROMETER_INTERVAL;
        Serial.println("Done.");
    }

    //
    // TASK 2: Just once.
    //
    if (!just_once && current_timestamp - just_once_timestamp >= JUST_ONCE_INTERVAL)
    {
        // Perform second move.
        Serial.print("Running just once... ");
        servoUp.write(60);
        servoDown.write(120);
        just_once = true;
        Serial.println("Done.");
    }

    //
    // TASK 3: Also just once.
    //
    if (!also_just_once && current_timestamp - also_just_once_timestamp >= ALSO_JUST_ONCE_INTERVAL)
    {
        // Perform third move.
        Serial.print("Running also just once... ");
        servoMini.write(180);
        also_just_once = true;
        Serial.println("Done.");
    }

    //
    // TASK 4: Blink without delay.
    //
    if (current_timestamp - previous_blink_timestamp >= LED_BLINK_INTERVAL)
    {
        // Toggle LED state.
        led_state = !led_state;
        digitalWrite(LED_BUILTIN, led_state);
        previous_blink_timestamp += LED_BLINK_INTERVAL;
    }
}

Wow! It's exactly what I wanted. I've never thought of using boolean type. Thank you very much! By the way, Can I ask you why you add the led blinking at the end?

@JohnCho, the LED blinking is not essential, but it's useful for debugging purposes to show that the MCU hasn't frozen - known as a heartbeat signal or sign of life signal. Plus I was building upon the Blink Without Delay example to show how to add concurrent non-blocking tasks.

Thank you! Now I have better understand of concurrent tasks. Sorry for late comment, by the way.


text:
How do I make another action repeat inside a loop?
So, I've just started programming Arduino (and also in general), so I'm doing basic things, like switching on and off LED's.
I've made them light in a sequence and then turning them off (in the same sequence), and now I wanted to use 2 buttons, one to make them do the same thing as before (light and turning LED's off in sequence) repeatedly, and the other to turn them off.
The problem is that curently they only light up once, and not repeatedly, I think I would've needed another loop, but i found out that you can't use 2 of them.
Can anyone help me? here's the code
int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int LED4 = 5;
int LED5 = 6;
int buttonON = 7;
int buttonOFF = 8;

void setup()
{
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(buttonON, INPUT_PULLUP);
  pinMode(buttonOFF, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(buttonON)== LOW)
  {
    delay(300), digitalWrite(LED1, HIGH);
    delay(50), digitalWrite(LED2, HIGH);
    delay(50), digitalWrite(LED3, HIGH);
    delay(50), digitalWrite(LED4, HIGH);
    delay(50), digitalWrite(LED5, HIGH);
    delay(300), digitalWrite(LED1, LOW);
    delay(100), digitalWrite(LED2, LOW);
    delay(100), digitalWrite(LED3, LOW);
    delay(100), digitalWrite(LED4, LOW);
    delay(100), digitalWrite(LED5, LOW);
  }
 if (digitalRead(buttonOFF)== LOW)
 {
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);
  digitalWrite(LED4, LOW);
  digitalWrite(LED5, LOW);
 }
}

P.S. if anyone has other general tips I would really apreciate them

insert a layer of separation between the button press and the LED lighting ... use a flag variable .... if (digitalRead(buttonON)== LOW)  ledsON = true; .... then further down in the code if (ledsON) { / led lighting code } ... you can set/clear ledsON flag any number of times, so you could check the button after every led is lit ... that way you don't have to hold the button until the sequence is finished

good way of asking question ;) Nicely written, formatted +1

I take it you are new to programming?

yes, like i said, I've just started, and decided to start programming with Arduino

You have written your question beautifully.
In your case, according to your logic, the button has to be kept pressed, so that the LEDs are lit in the order you desire. The single loop() function is part of the Arduino sketch but it is never a limitation.
One way to solve your problem is to make the LED drive logic independent of the button press state.

Once you detect the button press, store the event in one variable.
Let us call it ButtonStatus.
So, soon after the keypress is detected, update the ButtonStatus variable to TRUE.
Your LED drive logic can check this variable value to decide whether to drive the LEDs or not
Soon after you detect another press of the second button, you can update the variable value to FALSE.
Here is the Arduino simulation output for your code and the code suggested by @cat

below is after adapting the solution from cat

The simulation links are here:
Original problem
solution 1
int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int LED4 = 5;
int LED5 = 6;
int buttonON = 7;
int buttonOFF = 8;
int ledEffectON;
void setup()
{
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(buttonON, INPUT_PULLUP);
  pinMode(buttonOFF, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(buttonON)== LOW)
      ledEffectON = true;

  if (digitalRead(buttonOFF)== LOW)
      ledEffectON = false;

  if(ledEffectON)
  {
    delay(300), digitalWrite(LED1, HIGH);
    delay(50), digitalWrite(LED2, HIGH);
    delay(50), digitalWrite(LED3, HIGH);
    delay(50), digitalWrite(LED4, HIGH);
    delay(50), digitalWrite(LED5, HIGH);
    delay(300), digitalWrite(LED1, LOW);
    delay(100), digitalWrite(LED2, LOW);
    delay(100), digitalWrite(LED3, LOW);
    delay(100), digitalWrite(LED4, LOW);
    delay(100), digitalWrite(LED5, LOW);
  }
}

Link to docs on Pushbuttons. Wokwi Arduino simulator simulates debounce by default - just like real-world switched. Debounce is a very important technique that you should consider adding to the code. To disable the "bounce" option, use the below trick!
{ "bounce": "0" }

Thanks, really apreciate the time you spent on explaining it

Very nice diagrams!

@Juraj brought in resistors. I have also updated the links referred to. Now you should see the current limiting resistors as well!

By using delay() it blocks the rest of the code. The programme needs to keep track of two buttons and update the lightshow at appropriate times, therefore a non-blocking style of coding is needed similar to the Blink Without Delay example where the delay() is replaced with a timer using millis() that is checked periodically. This allows other things to be checked periodically as well, e.g. the buttons.
Also the button contacts tend to bounce several times for several milliseconds when they change state sending a train of on/off pulses to the MCU, so they need to be debounced. You can find many debouncing algorithms online, but here's a simple debouncer that I put on GitHub.
void loop ()
{
  static bool doLightshow = false;

  static Debouncer buttonOn(buttonON);
  static Debouncer buttonOff(buttonOFF);

  buttonOn.Update();
  buttonOff.Update();

  if (buttonOn.Fall())
  {
    Serial.println("buttonOn falling edge.");
    doLightshow = true;
  }
  else if (buttonOff.Fall())
  {
    Serial.println("buttonOff falling edge.");
    doLightshow = false;
  }

  if (doLightshow)
  {
    // Do lightshow.
    . . .
  }
  else
  {
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, LOW);
    digitalWrite(LED4, LOW);
    digitalWrite(LED5, LOW);
  }
}

Due to the way you've neatly written your code, you can probably pick out a pattern in the lightshow.

State
Delay time
LED pin
LED state

0
300
LED1
HIGH

1
50
LED2
HIGH

2
50
LED3
HIGH

3
50
LED4
HIGH

4
50
LED5
HIGH

5
300
LED1
LOW

6
100
LED2
LOW

7
100
LED3
LOW

8
100
LED4
LOW

9
100
LED5
LOW

This lends itself well to creating a Finite State Machine that can be stored in an array of structures:
typedef struct LightshowData
{
  unsigned int delayTime;
  byte ledPin;
  bool ledState;
};

const byte numStates = 10;

const LightshowData lightshowData[numStates] =
{
  { 300, LED1, HIGH },
  {  50, LED2, HIGH },
  {  50, LED3, HIGH },
  {  50, LED4, HIGH },
  {  50, LED5, HIGH },
  { 300, LED1, LOW },
  { 100, LED2, LOW },
  { 100, LED3, LOW },
  { 100, LED4, LOW },
  { 100, LED5, LOW }
};

The state machine can now cycle through the array in a non-blocking manner:
    // Do lightshow.
    static byte state = 0;
    unsigned long currentTimestamp = millis();
    static unsigned long previousTimestamp = currentTimestamp;

    if (currentTimestamp - previousTimestamp >= lightshowData[state].delayTime)
    {
      previousTimestamp += lightshowData[state].delayTime;
      digitalWrite(lightshowData[state].ledPin, lightshowData[state].ledState);
      state = ++state % numStates;
      Serial.print("state = ");
      Serial.println(state);
    }

You may want to reset state to 0 after a negative edge on buttonOff, otherwise the lightshow will continue where it left off after being stopped and restarted.
Here's the Wokwi simulation of the lightshow with 250 Ω protection resistors for the LEDs.

Wokwi simulates button bounce by default to more accurately model the real world, so it's advisable to have some form of button debouncing.

thanks man, looks a bit difficult, but I'll certanly check it out

When the loop() function does not need any time ( avoid delay and nested time consuming loops ) your program logic is completely different from before, but more flexible and easier, once you got used to it.

You simply need to save the state of the LEDs in a new variable ...
void loop ()
{
  if (digitalRead(buttonON)== LOW)
      ledEffectON = true;

  if (digitalRead(buttonOFF)== LOW)
      ledEffectON = false;

  if(ledEffectON)
  {
    delay(300), digitalWrite(LED1, HIGH);
    delay(50), digitalWrite(LED2, HIGH);
    delay(50), digitalWrite(LED3, HIGH);
    delay(50), digitalWrite(LED4, HIGH);
    delay(50), digitalWrite(LED5, HIGH);
    delay(300), digitalWrite(LED1, LOW);
    delay(100), digitalWrite(LED2, LOW);
    delay(100), digitalWrite(LED3, LOW);
    delay(100), digitalWrite(LED4, LOW);
    delay(100), digitalWrite(LED5, LOW);
  }
}

https://wokwi.com/arduino/projects/304626706673566272 Wonderful solution!

Thanks for the short and simple answer

It's very seldom that  buttonOFF is checked. It needs to be pressed when LED5 goes LOW

is this not the same code as in ArduinoFan's answer?

source: Stack Exchange

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

sort: votes


text:
Arduino Zero not recognised as MIDI device via native USB port
I'm currently trying to get an Arduino Zero to show up as a native USB MIDI device in my DAW (ableton). No matter what I try, I cannot get it to show up as a device in Ableton. I have previously used an arduino DUE for a similar project, but cannot get this to work the same. Is there something I'm missing to get the Zero to show up as a native USB Device?
Below is the code have written. I had assumed that the MIDIUSB library takes care of the arduino being recognised as a USB device.
#include <MIDIUSB.h>

const byte CHANNEL = 1;
const byte OFFSET = 48;

void setup(){}

void loop()
{
    delay(100);
    sendNoteOn(CHANNEL, 50 + OFFSET, 127);
    delay(100);
    sendNoteOff(CHANNEL, 50 + OFFSET, 0);
}

void sendNoteOn(byte channel, byte pitch, byte velocity)
{
  midiEventPacket_t noteOn = {0x09, 0x90 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOn);
}

void sendNoteOff(byte channel, byte pitch, byte velocity)
{
  midiEventPacket_t noteOff = {0x08, 0x80 | channel, pitch, velocity};
  MidiUSB.sendMIDI(noteOff);
}

What OS and hardware are you using?

Windows 10 PC. Intel 6700k cpu.

what is windows detecting when you plug in your device?

Remove all of the Adafruit_Trellis stuff from your posted code.  If that doesn't make it work (and it may easily) the number of people here that can and are willing to replicate your problem skyrockets.

Check windows device manager and see if it is actually detecting a MIDI device or just a simple CDC/ACM one. If Windows detects it as MIDI then the problem is with your DAW not liking it. If Windows is not detecting it as MIDI the problem is your code or the MIDI library.

Thanks all for the comments. @jsotola, this is what found the solution for me. The device manager looked spooky so I tracked down the drivers on github and used them instead of relying on it all working automatically.

also, @timemage, I've removed all the irrelevent code for future people who come accross the same issue.

After extended trouble shooting and device manager fiddling, It turned out that Windows was auto installing the wrong (or partially wrong) drivers that made the native port not be recognised as a USB device. The device was detected as two different ports in the USB drivers, one of which had an error warning. I could still upload to it via either of the USB ports, just couldn't get it to be recognised as a MIDI device.
The solution was to:

completely uninstall the drivers from the device manager
uninstall the SAMD boards from the Arduino IDE
manually download the drivers from github
plug the arduino back in and install everything again as normal using those drivers

It now works like a charm.

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


text:
Arduino Nano I2C OLED display 0.96 inches 128x64 pixels
I have a strange issue while trying to run the hello world code on an arduino nano connected to an OLED display.
This is the code I used:
    #include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

void setup() {

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Address 0x3C for 128x32

  display.display();
  delay(2000);

  display.clearDisplay();      //this line to clear previous logo
  display.setTextColor(WHITE); //without this no display
  display.print("Hello World!");//your TEXT here
  display.display();            //to shows or update your TEXT
}

void loop() {

 }

But I get this on the display.

Any idea what I could be missing?
Thanks !

Do you have the product link of your display?

I had this display laying around for a while, unfortunately I can't find the product link.

Is the driver IC SSD1306? Can you see that at the back of the display?

Not sure where can I see that, I added a picture with the back.

Why are you using Adafruit_SSD1306 library? It is possible that the display driver is not SSD1306. Also, from your second picture, it looks like the address is 0x78. In the code, you are using 0x3C. Also, show us how did you connect the display with Arduino Nano.

Also, check if the display I2C pins have pull-ups.

@Fahad This doesn't look like an I2C problem, but rather something with the font handling (note that the "H" and "W" are correct, but the rest of the letters are somewhat off (L=E, S=L, etc.) I'd try reinstalling the library.

Good point. I have seen other people said sometimes Chinese manufactured display have the address 0x7A but works with 0x3C. But the pull-up can be a problem. If there is no pull-up, the floating state can generate garbage data.

0x7A is 0x3C << 1 which is correct. I2C addresses are 7 bits and the 8th bit (rightmost) is use as a R/W flag. So you shift the I2C address one to the left and then add a 1 or 0 to the left for read/write operation (I forget which way around it is). The Arduino library does that for you, so you need to provide the "unshifted" address of 0x3C.

Mystery solved :)
After some more reading it appears that the display driver is actually SH1106, so after using the right library I got the display working.


text:
'for loop' seems to change the execution of pow()
The first time, pow() works.  But inside of a 'for loop', or again afterwards, it doesn't behave !?  (I'm using a Chinese Pro Mini with Arduino 1.8.16)
EDIT
To clarify what I am asking, my question is: "Why does pow() only give the correct answer the first time?"
uint8_t places;
uint8_t temp8;
uint32_t n;

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

void loop() {
  places  = 5U;

  n = pow( 10, places);
  Serial.println(n);

  Serial.println("\nHERE'S THE SAME CODE INSIDE OF A 'FOR LOOP'\n");

  for (temp8 = 0; temp8 < places; temp8++)  {
    n = pow( 10, places);
    Serial.println(n);
  }

  Serial.println("\nNOW THE EXACT SAME CODE AS BEFORE GIVES A DIFFERENT RESULT\n");

  n = pow( 10, places);
  Serial.println(n);

  while(1){}
}

Here's what the serial monitor shows:

100000
HERE'S THE SAME CODE INSIDE OF A 'FOR LOOP'
99999
99999
99999
99999
99999
NOW THE EXACT SAME CODE AS BEFORE GIVES A DIFFERENT RESULT
99999

This seems like a case of a confused compiler. More specifically, a
confused optimizer.
On the first occurrence of pow(10, places), the compiler noticed that
places must be equal to 5, and so replaced the expression with its
value. If you disassemble the compiled code, you will notice it calls
Serial.println(100000);

On the following occurrences, the compiler did not notice that places
can not be anything other than 5, so it did not optimize-out the call to
pow(), and got the result 99999.9765625. This is 3 ULPs less than
the exact result, and is consistent with the accuracy you can expect
from pow(). Converting to an integer implicitly rounds towards zero,
hence the printed result: 99999.

What is ULPs?  My search came back with Ultra Low Power, but that's probably not what you were talking about.  I don't understand where the error is coming from, nothing really changed, and the calculation is seemingly very simple.  What can I do to make my sketch run properly?  Did I ask a low quality question?  I put a good deal of effort into it and felt that the result was to the best of my ability.  Perhaps this isn't the place for someone with my skills to be posting.  I feel like I have made a nuisance of myself and do not wish to do so again, Your candid thoughts would be appreciated.

@TRS-80: ULP = Unit in the last place. To get the correct result, write (or search for) an integer power function, or use round(pow(...)).

Great!  That fixed my problem, thanks very much!  You were extremely helpful with the programming aspect,  I guess I must have been violating boundaries by asking for etiquette advice.  Sorry.


text:
esp based smart light system over alexa malfunctioning
i made a home automation system using esp 32 and 8 channel relay but within 2 or 3 months my relay automatically turns off after sending the signal to it through esp32 but if i connect directly without esp32 it functions absolutely fine. that means that my relay if fine but what must be the possible reason for this malfunctioning.
this is my code
#include <ESP8266WiFi.h>
#include <Espalexa.h>
Espalexa espalexa;

// define the GPIO connected with Relays and switches
#define RelayPin1 5  //D23
#define RelayPin2 4  //D22
#define RelayPin3 0  //D21
#define RelayPin4 2  //D19
#define RelayPin5 14  //D18
#define RelayPin6 12  //D5
#define RelayPin7 13  //D25
#define RelayPin8 15  //D26

#define SwitchPin1 3  //D13
#define SwitchPin2 1  //D12
#define SwitchPin3 10  //D14
#define SwitchPin4 9  //D27
#define SwitchPin5 8  //D33
#define SwitchPin6 11  //D32
#define SwitchPin7 7  //D15
#define SwitchPin8 6   //D4

bool oldStateSwitch_1;
bool oldStateSwitch_2;
bool oldStateSwitch_3;
bool oldStateSwitch_4;
bool oldStateSwitch_5;
bool oldStateSwitch_6;
bool oldStateSwitch_7;
bool oldStateSwitch_8;

#define wifiLed    16   //D2

// WiFi Credentials
const char* ssid = "akkikisu";
const char* password = "anirudh@123";

// device names
String Device_1_Name = "a1";
String Device_2_Name = "a2";
String Device_3_Name = "a3";
String Device_4_Name = "a4";
String Device_5_Name = "a5";
String Device_6_Name = "a6";
String Device_7_Name = "a7";
String Device_8_Name = "a8";

// prototypes
boolean connectWifi();

//callback functions
void firstLightChanged(uint8_t brightness);
void secondLightChanged(uint8_t brightness);
void thirdLightChanged(uint8_t brightness);
void fourthLightChanged(uint8_t brightness);
void fifthLightChanged(uint8_t brightness);
void sixthLightChanged(uint8_t brightness);
void senventhLightChanged(uint8_t brightness);
void eighthLightChanged(uint8_t brightness);

boolean wifiConnected = false;

//our callback functions
void firstLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin1, LOW);
      Serial.println("Device1 ON");
    }
  else
  {
    digitalWrite(RelayPin1, HIGH);
    Serial.println("Device1 OFF");
  }
}

void secondLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin2, LOW);
      Serial.println("Device2 ON");
    }
  else
  {
    digitalWrite(RelayPin2, HIGH);
    Serial.println("Device2 OFF");
  }
}

void thirdLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin3, LOW);
      Serial.println("Device3 ON");
    }
  else
  {
    digitalWrite(RelayPin3, HIGH);
    Serial.println("Device3 OFF");
  }
}

void fourthLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin4, LOW);
      Serial.println("Device4 ON");
    }
  else
  {
    digitalWrite(RelayPin4, HIGH);
    Serial.println("Device4 OFF");
  }
}

void fifthLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin5, LOW);
      Serial.println("Device5 ON");
    }
  else
  {
    digitalWrite(RelayPin5, HIGH);
    Serial.println("Device1 OFF");
  }
}

void sixthLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin6, LOW);
      Serial.println("Device6 ON");
    }
  else
  {
    digitalWrite(RelayPin6, HIGH);
    Serial.println("Device6 OFF");
  }
}

void seventhLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin7, LOW);
      Serial.println("Device7 ON");
    }
  else
  {
    digitalWrite(RelayPin7, HIGH);
    Serial.println("Device7 OFF");
  }
}

void eighthLightChanged(uint8_t brightness)
{
  //Control the device
  if (brightness == 255)
    {
      digitalWrite(RelayPin8, LOW);
      Serial.println("Device8 ON");
    }
  else
  {
    digitalWrite(RelayPin8, HIGH);
    Serial.println("Device8 OFF");
  }
}

// connect to wifi – returns true if successful or false if not
boolean connectWifi()
{
  boolean state = true;
  int i = 0;

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  Serial.println("Connecting to WiFi");

  // Wait for connection
  Serial.print("Connecting...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    if (i > 20) {
      state = false; break;
    }
    i++;
  }
  Serial.println("");
  if (state) {
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.println("Connection failed.");
  }
  return state;
}

void addDevices(){
  // Define your devices here.
  espalexa.addDevice(Device_1_Name, firstLightChanged); //simplest definition, default state off
  espalexa.addDevice(Device_2_Name, secondLightChanged);
  espalexa.addDevice(Device_3_Name, thirdLightChanged);
  espalexa.addDevice(Device_4_Name, fourthLightChanged);
  espalexa.addDevice(Device_5_Name, fifthLightChanged);
  espalexa.addDevice(Device_6_Name, sixthLightChanged);
  espalexa.addDevice(Device_7_Name, seventhLightChanged);
  espalexa.addDevice(Device_8_Name, eighthLightChanged);

  espalexa.begin();
}

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

  pinMode(RelayPin1, OUTPUT);
  pinMode(RelayPin2, OUTPUT);
  pinMode(RelayPin3, OUTPUT);
  pinMode(RelayPin4, OUTPUT);
  pinMode(RelayPin5, OUTPUT);
  pinMode(RelayPin6, OUTPUT);
  pinMode(RelayPin7, OUTPUT);
  pinMode(RelayPin8, OUTPUT);

  pinMode(wifiLed, OUTPUT);

  pinMode(SwitchPin1, INPUT_PULLUP);
  pinMode(SwitchPin2, INPUT_PULLUP);
  pinMode(SwitchPin3, INPUT_PULLUP);
  pinMode(SwitchPin4, INPUT_PULLUP);
  pinMode(SwitchPin5, INPUT_PULLUP);
  pinMode(SwitchPin6, INPUT_PULLUP);
  pinMode(SwitchPin7, INPUT_PULLUP);
  pinMode(SwitchPin8, INPUT_PULLUP);

  //During Starting all Relays should TURN OFF
  digitalWrite(RelayPin1, HIGH);
  digitalWrite(RelayPin2, HIGH);
  digitalWrite(RelayPin3, HIGH);
  digitalWrite(RelayPin4, HIGH);
  digitalWrite(RelayPin5, HIGH);
  digitalWrite(RelayPin6, HIGH);
  digitalWrite(RelayPin7, HIGH);
  digitalWrite(RelayPin8, HIGH);

  oldStateSwitch_1 = ! digitalRead( SwitchPin1 ) ;  // note inverted
  oldStateSwitch_2 = ! digitalRead( SwitchPin2 ) ;  // note inverted
  oldStateSwitch_3 = ! digitalRead( SwitchPin3 ) ;  // note inverted
  oldStateSwitch_4 = ! digitalRead( SwitchPin4 ) ;  // note inverted
  oldStateSwitch_5 = ! digitalRead( SwitchPin5 ) ;  // note inverted
  oldStateSwitch_6 = ! digitalRead( SwitchPin6 ) ;  // note inverted
  oldStateSwitch_7 = ! digitalRead( SwitchPin7 ) ;  // note inverted
  oldStateSwitch_8 = ! digitalRead( SwitchPin8 ) ;  // note inverted

    // repeat for seitched 2 to 8

  // Initialise wifi connection
  wifiConnected = connectWifi();

  if (wifiConnected)
  {
    addDevices();
  }
  else
  {
    Serial.println("Cannot connect to WiFi. So in Manual Mode");
    delay(1000);
  }
}

void loop()
{
   if (WiFi.status() != WL_CONNECTED)
  {
    //Serial.print("WiFi Not Connected ");
    digitalWrite(wifiLed, LOW); //Turn off WiFi LED
  }
  else
  {
    //Serial.print("WiFi Connected  ");
    digitalWrite(wifiLed, HIGH);
    //Manual Switch Control
    //WiFi Control
    if (wifiConnected){
      espalexa.loop();
      delay(1);
    }
    else {
      wifiConnected = connectWifi(); // Initialise wifi connection
      if(wifiConnected){
      addDevices();
      }
    }
  }

//main code

static uint32_t lastSwitchTest = 0 ;  // static initialised once only

      if ( millis() - lastSwitchTest > 250 ) {  // every 250ms
      lastSwitchTest = millis() ;

      // switch 1

      bool stateSwitch_1 = digitalRead( SwitchPin1 ) ;
      if (  oldStateSwitch_1 != stateSwitch_1 ) {
         oldStateSwitch_1 = stateSwitch_1 ;
         Serial.println("Switch 1 changed");
         EspalexaDevice* d1 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_1 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d1->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin1, HIGH);
         }
         else { // switch on
            Serial.println("Switch 1 on");
            d1->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin1, LOW);
         }
      }

      // switch 2

      bool stateSwitch_2 = digitalRead( SwitchPin2 ) ;
      if ( oldStateSwitch_2 != stateSwitch_2 ) {
         oldStateSwitch_2 = stateSwitch_2 ;
         Serial.println("Switch 2 changed");
         EspalexaDevice* d2 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_2 == HIGH )  {  // HIGH = off
            Serial.println("Switch 2 off");
            d2->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin2, HIGH);
         }
         else { // switch on
            Serial.println("Switch 2 on");
            d2->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin2, LOW);
         }
      }

      // switch 3

      bool stateSwitch_3 = digitalRead( SwitchPin3 ) ;
      if ( oldStateSwitch_3 != stateSwitch_3 ) {
         oldStateSwitch_3 = stateSwitch_3 ;
         Serial.println("Switch 3 changed");
         EspalexaDevice* d3 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_3 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d3->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin3, HIGH);
         }
         else { // switch on
            Serial.println("Switch 3 on");
            d3->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin3, LOW);
         }
      }
      // switch 4

      bool stateSwitch_4 = digitalRead( SwitchPin4 ) ;
      if ( oldStateSwitch_4 != stateSwitch_4 ) {
         oldStateSwitch_4 = stateSwitch_4 ;
         Serial.println("Switch 4 changed");
         EspalexaDevice* d4 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_4 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d4->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin4, HIGH);
         }
         else { // switch on
            Serial.println("Switch 4 on");
            d4->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin4, LOW);
         }
      }
      // switch 5

      bool stateSwitch_5 = digitalRead( SwitchPin5 ) ;
      if ( oldStateSwitch_5 != stateSwitch_5 ) {
         oldStateSwitch_5 = stateSwitch_5 ;
         Serial.println("Switch 5 changed");
         EspalexaDevice* d5 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_5 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d5->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin5, HIGH);
         }
         else { // switch on
            Serial.println("Switch 5 on");
            d5->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin5, LOW);
         }
      }
      // switch 6

      bool stateSwitch_6 = digitalRead( SwitchPin6 ) ;
      if ( oldStateSwitch_6 != stateSwitch_6 ) {
         oldStateSwitch_6 = stateSwitch_6 ;
         Serial.println("Switch 6 changed");
         EspalexaDevice* d6 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_6 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d6->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin6, HIGH);
         }
         else { // switch on
            Serial.println("Switch 6 on");
            d6->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin6, LOW);
         }
      }
      // switch 7

      bool stateSwitch_7 = digitalRead( SwitchPin7 ) ;
      if ( oldStateSwitch_7 != stateSwitch_7 ) {
         oldStateSwitch_7 = stateSwitch_7 ;
         Serial.println("Switch 7 changed");
         EspalexaDevice* d7 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_7 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d7->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin7, HIGH);
         }
         else { // switch on
            Serial.println("Switch 7 on");
            d7->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin7, LOW);
         }
      }
      // switch 8

      bool stateSwitch_8 = digitalRead( SwitchPin8 ) ;
      if ( oldStateSwitch_8 != stateSwitch_8 ) {
         oldStateSwitch_8 = stateSwitch_8 ;
         Serial.println("Switch 8 changed");
         EspalexaDevice* d8 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_8 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d8->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin8, HIGH);
         }
         else { // switch on
            Serial.println("Switch 8 on");
            d8->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin8, LOW);
         }
      }

      // switch 2 to 8
      // just copy/paste/adjust using switch 1 as a template

    } // if ( millis
} // loop()

Every 2 or 3 months you get a spurious triggering of your relay module which you attribute to a software problem on the esp32. Is that correct? If so, it could be a bad handling of the millis() rollover somewhere in your code or a library. This rollover occurs every 49 days.

@6v6gt and how can i rectify my problem

I'd suspect the button library acebutton.h . It appears to use 16bit datatypes for holding timings, probably derived from millis(), for button debouncing etc. 32 bit integers would be more appropriate. Using another library may solve this. But you have to conduct a long term test.

which library can i use . and can you tell me the appropriate code for that

Let's get the problem description right before looking deeper for a solution. When you say that it works without the ESP32, do you mean that you are able to connect the 8 channel relay module directly to the Alexa? You said this spurious behaviour happens within 2 or 3 months. Is it possible that it happens regularly every 49 days? Are you using push buttons or toggle type switches for the manual relay control?
Is it so that you will only know you have a working solution after testing over a 2 to 3 month period?

https://iotcircuithub.com/esp32-alexa-home-automation-system/ so here you can find all the detals

OK. From the project link, it is clear that the buttons are in fact toggle type switches. Please answer the remaining questions I've asked before. Also, if you press the reset button on the ESP32 do you get the same effect that you say appears after 2-3 months, that is spurious switching of the relays? The button library adds an unnecessary complexity and the code can be restructured to eliminate it. It is not certain that that would solve the problem, though. A memory leak may also give similar effects.

yes after pressing the reset button also i face the same issue. and yes i think it may be occuring within 49 days of time and one more big probem is that i can re program my board as i broke the micro usb pin

You are using the following project as a code base: https://iotcircuithub.com/esp32-alexa-home-automation-system/
You appear to have confirmed that the same problem symptoms appear when the ESP32 is reset, that is that some lights are in the wrong state at system start. A reset can be caused by such things as a system reset following a power outage, a crash or simply pressing the reset button on the device.
You are using a button handling library AceButton.h in combination with latched switches. The problem here is that the button handling library is intended for momentory push-to-make buttons and assumes that the switch is in the "un-pushed" state at system start. This may not reflect the position of the latched switches where some could be in the on position and others in the off position. This could result in missed events on system start.
Anyway, you do not need a button library. Especially for toggle type switches, like you are using, where it is necessary only to read the switch say every 250ms and test if the state has been changed since the last reading. No other debouncing is required.
In setup() you'd read each switch and store the inverse of its current state in a variable, say oldStateSwitch_1. It is necessary to store the inverse of the state to trigger a first time switch state change action in the loop().
Something like . . .
void setup() {
    . . .

    oldStateSwitch_1 = ! digitalRead( switchPin1 ) ;  // note inverted
    // repeat for seitched 2 to 8
    . . .

}

In the loop(), you'd do something like . . .
void loop() {

. . .
. . .

    static uint32_t lastSwitchTest = 0 ;  // static initialised once only

    if ( millis() - lastSwitchTest > 250 ) {  // every 250ms
      lastSwitchTest = millis() ;

      // switch 1

      bool stateSwitch_1 = digitalRead( switchPin1 ) ;
      if ( oldStateSwitch_1 != stateSwitch_1 ) {
         oldStateSwitch_1 = stateSwitch_1 ;
         Serial.println("Switch 1 changed");
         EspalexaDevice* d1 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
         if ( stateSwitch_1 == HIGH )  {  // HIGH = off
            Serial.println("Switch 1 off");
            d1->setPercent(0); //set value "brightness" in percent
            digitalWrite(RelayPin1, HIGH);
         }
         else { // switch on
            Serial.println("Switch 1 on");
            d1->setPercent(100); //set value "brightness" in percent
            digitalWrite(RelayPin1, LOW);
         }
      }

      // switch 2 to 8
      // just copy/paste/adjust using switch 1 as a template

    } // if ( millis
} // loop()

All AceButton code should be deleted.

now again the same kind of thing is happening but this time the switches automatically go off and agfter some time they turn on if the board's blue light is on but sometimes that blue light goes off and the board is not able to connect to wifi now how do i resolve this

@RathoreBrothers   Spurious resetting of a micro controller together with WiFi connectivity problems are notoriously difficult to investigate. What happens when the system is running normally and (test a) you press the reset button on the esp32 and (test b) you switch off the WiFi router? Do you get similar symptoms to the ones you have described?

when i press reset the boards normally resets and i am able to access the lights and when i turn off the wifi then also i am able to access through switches but not over alexa but the thing is after a period of time the lights go off and on after some time

can you please reply

@RathoreBrothers If you press reset on the esp32, do the lights return to the state they were in before the reset?   Are the switches of the same type as illustrated in the project, that is they hold their position as either ON or OFF or are you using push buttons?
If the code you are using is not the same as in your original question, please  update the question with the new code. Have you looked through the comments in the project and video to see if other people have the same problem?

yes lights come back in their original state . no i am not using push buttons . the code is same as you suggested me previously and no i could  not find people with the problem may be no one has tried on this scale .

@RathoreBrothers if you paste in the full code into the question I can check that there are no basic errors in interpreting what I suggested, but I can't test it because I don't use Alexa. There are over 100 open issues with that espalexa library so opening an issue in its github repository may not bring a quick fix. Did the new code make the situation worse?

new code kind of made the situation worse as the lights turn off frequently but they again turn on automatically

can you please reply

@RathoreBrothers if you paste in the full code into the question I can check that there are no basic errors in interpreting what I suggested, but I can't test it because I don't use Alexa. Paste it in after your original code.

here you go i posted my renewed code


text:
Issue with input from weighing scale controlling a stepper motor based valve
Hello and thanks for any help in advanced.
What changes do I need to make to my code to get rid of the issue of the valve opening up again at end of cycle in "Auto" function.
Hardware:

Arduino Mega
Bi-polar Stepper Motor connected to Valve.
Weighing scale with TTL output.

Here is my code:
//Buttons
#include <mechButton.h> //Button Library
#define BTNa_PIN  10    //Button Pins
#define BTNb_PIN  6
mechButton aButton(BTNa_PIN);  // Set button to pin BTN_PIN.
mechButton bButton(BTNb_PIN);

//Stepper
#include <AccelStepper.h> //Stepper Library
#define dirPin 4          //Stepper Pins
#define stepPin 2
#define motorInterfaceType 1 //Interface set to driver
AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);// Create a new instance

//Analog inputs for setting Max and Min Distance
const int analogPin = A0;
const int analogPin2 =A1;

//Data types for Scale Reading for Optima OP900a
char inString[32];
float Input;
float Setpoint;
float fSetpoint;

//Setup
void setup() {

  Serial.begin(9600);           // Fire up our serial monitor for arduino and computer
  Serial3.begin(9600);          //Fire up Serial for Scale for input

  aButton.setCallback(Manual);    // Set up our callback. (Also calls hookup() for idling.)
  bButton.setCallback(Auto);
  stepper.setMaxSpeed(3500);      // Set the maximum speed and acceleration for stepper motor:
  stepper.setAcceleration(5000);

  Setpoint = 4.44;               // Auto parameters
  fSetpoint = (Setpoint*0.9);

}
// Main Loop
void loop() {
   bool abuttonState;
   bool bButtonState;

   idle();                      // Let all the idlers have time to do their thing.
   abuttonState = aButton.trueFalse();    // Have a look at what the current button state is.
   bButtonState = bButton.trueFalse();
}
//Sub Functions
void Manual(void) {
    int maxOpen = analogRead(analogPin);
    maxOpen = map(maxOpen, 0, 1023, 0,100);

   Serial.print("Manual ");
   if (aButton.trueFalse()) {
      stepper.moveTo(0);
      stepper.runToPosition();
   } else {
      stepper.moveTo(maxOpen*40);
      stepper.runToPosition();

   }
}

void Auto(void) {
    int maxOpen = analogRead(analogPin);
    int minOpen = analogRead(analogPin2);
    maxOpen = map(maxOpen, 0, 1023, 0,100);
    minOpen = map(minOpen, 0, 1023, 0,100);

   while (Input < Setpoint){
     readScale();
     if (Input >= fSetpoint && Input < Setpoint){
     stepper.runToNewPosition((minOpen*10)+400);  //Blocking function research work around...
     Serial.print("Min");Serial.print(",");       //debugging
     Serial.println(Input);                       //debugging
     }
     else if (Input < fSetpoint) {
     stepper.runToNewPosition(maxOpen*40);         //Blocking function research work around...
     Serial.print("Max");Serial.print(",");       //debugging
     Serial.println(Input);                       //debugging
     }
     else{
     stepper.runToNewPosition(0);                 //Blocking function research work around...
     Serial.print("Close");Serial.print(",");     //debugging
     Serial.println(Input);                       //debugging
     }
     }
}

void readScale(void){
    byte inChar = Serial3.readBytesUntil('\n', inString, 18); //Scale reading for input
    float scaleInput = atof(&inString[7]);
    Input = scaleInput;
  }

I keep getting this strange behavior at the end of the "Auto" function where I am getting false 0.00 from the scale that causes the valve to open and close fully at the end.
Max,0.01
Max,0.01
Max,0.01
Max,0.00
Max,0.00
Max,0.00
Max,0.00
Max,0.35
Max,0.42
Max,0.51
Max,0.60
Max,0.66
Max,0.69
Max,0.75
Max,0.83
Max,0.88
Max,0.93
Max,1.00
Max,1.05
Max,1.11
Max,1.16
Max,1.21
Max,1.26
Max,1.32
Max,1.38
Max,1.43
Max,1.48
Max,1.53
Max,1.59
Max,1.64
Max,1.68
Max,1.74
Max,1.80
Max,1.84
Max,1.89
Max,1.94
Max,1.99
Max,2.04
Max,2.09
Max,2.14
Max,2.18
Max,2.23
Max,2.27
Max,2.32
Max,2.37
Max,2.41
Max,2.45
Max,2.50
Max,2.55
Max,2.59
Max,2.62
Max,2.68
Max,2.72
Max,2.76
Max,2.81
Max,2.85
Max,2.88
Max,2.93
Max,2.97
Max,3.00
Max,3.04
Max,3.08
Max,3.13
Max,3.17
Max,3.20
Max,3.23
Max,3.27
Max,3.31
Max,3.35
Max,3.39
Max,3.42
Max,3.46
Max,3.50
Max,3.52
Max,3.55
Max,3.60
Max,3.63
Max,3.66
Max,3.69
Max,3.73
Max,3.77
Max,3.80
Max,3.83
Max,3.87
Max,3.91
Max,3.94
Max,3.95
Max,3.98
Min,4.03
Min,4.06
Min,4.09
Min,4.13
Max,0.00
Max,0.00
Min,4.35
MZ��r��j
Min,4.36
Close,4.46

Any suggestions are welcome.
Thanks

There are a few issues here:

Serial3.readBytesUntil() does not add a null character at the end of
the string. You have to do it yourself if you want a properly
terminated string.

You are attempting to read a float starting at the eight byte of the
string, even if you got less than eight bytes.

atof() does not report errors. If it fails to parse a float, it just
returns zero.

Just to see what may be going wrong, I suggest this version of
readScale() with verbose debug output:
void readScale(void) {
    byte inChar = Serial3.readBytesUntil('\n', inString, 18);
    inString[inChar] = '\0';  // terminate the string
    const char *start = &inString[7];  // where the number is expected
    char *end;  // where strtod() found it ends
    float scaleInput = strtod(start, &end);
    Serial.print("Scale -> \"");
    Serial.print(inString);
    Serial.print("\", parsed \"");
    *end = '\0';  // terminate the string after the number
    Serial.print(start);
    Serial.print("\" as ");
    Serial.println(scaleInput);
    Input = scaleInput;
}

That helped a lot!  The first time I hit the auto button it works perfectly.  But the more times I hit it the error keeps coming back.  Do you think this has something to do with buffer overflow?
stepper.runToNewPosition is blocking therefore it could be interrupting the serial3.readBytesUntil

Maybe. Or it could be the debug messages slowing down the code. Does the scale pause between messages? Does it help to set a higher baud rate on Serial?

the serial stalls for a good ~1s while moving to maxOpen.   I cranked the baud to 115200  no change.  I think using the accelstepper library always get me into trouble and in the end never use it.  Time to rewrite everything in millis().

Scale -> "US,NT,+  US,NT,+  ", parsed "" as 0.00
Scale -> " 4.34lb", parsed "" as 0.00
This is the serial error with your better parsing.

Do you think adding an if(Serial.available() > 0) would help?

If you don't want the Accelstepper library to block, then why don't you write your code non-blocking? The Accelstepper library is totally capable of that. Look the the examples which call the run() function regularily. That function is meant for non-blocking action

I know it is but the whole reason I was using the accelstepper library was for the ramping because the valve has significant static friction and ramping allows it to over come the issue and run at max speed without stalling.


text:
HC-05 Disconnects Underwater(predictably). How to make it reconnect by itself?
So I have an application where I send a Bluetooth module underwater(in a waterproof case). I have the Arduino+module sending my computer on-land a constant stream of numbers. Predictably, when the module goes underwater the stream cuts. I then need to remove the Arduino+module from the housing and reconnect/restart the connection.
Is there any way for the connection to start again by itself once above water. On my computer it says the Arduino and computer are connected the whole time. Maybe the code is just "pausing" on the serial.write() step?
Any advice would be appreciated.
#include <SoftwareSerial.h>
SoftwareSerial MegaloDon(10,11); //TX = 10, RX = 11, Ground = Ground, VCC = 5V
int BluetoothData;

unsigned long myTime = 0;
int givenHour;
int givenMin;
int givenSec;
int storeMin = 0;
int hour = 0;
int mins = 0;
int sec = 0;
int store = 0;
int count = 0;
int interval = 0;
int countToMin = 0;

void setup() { //time being set from recieving computer before being submerged in housing
  Serial.begin(9600);
  MegaloDon.begin(9600); //megalodon is the recieving computer
  MegaloDon.println("Bluetooth ON");
  Serial.println("start");
  Serial.flush();
  while (!Serial.available());
  givenHour = Serial.readStringUntil(',').toInt();
  givenMin = Serial.readStringUntil(',').toInt();
  givenSec = Serial.readStringUntil('.').toInt();
  MegaloDon.println(String(givenHour) + " : " + String(givenMin) + " : " + String(givenSec));

}

//min --> 3,600,000
void loop() {
  while(!MegaloDon.available()){ //Megalodon is the recieving computer
  myTime = millis();
  sec = givenSec + (myTime/1000);
  if (sec < 60){
    MegaloDon.println(String(givenHour) + " : " + String(givenMin) + " : " + String(sec));
  }
  if (sec >= 60){
    store = (sec % 60);
     if (sec % 60 == 0){
       count = count + 1;
       if(count%52 == 0 || count > 52){
        countToMin = count/52;
        mins = givenMin + countToMin;
        hour = givenHour;
        if(mins%60 ==0){
          mins = 0;
          hour = givenHour + countToMin;
        }
        if(mins )
        if(mins > 60){
          mins = mins%60;
        }
       }
     }
    MegaloDon.println(String(hour) + " : " + String(mins) + " : " + String(store)); //send to onshore computer step
  }
  }
}

//to use, plug the USB in, run arduino code with COM6, then run the python code, then open the TeraTerm COM8 port, unplug the USB

Based on the code you have shown us, I believe you may be correct when you say "Maybe the code is just "pausing" on the serial.write() step?".

@VE7JRO Thanks so much for the response. I updated my question with the relevant code snippet and my "serial.write()" is "println". I don't know that there is much of a difference but was wondering if you had any ideas on how to fix the issue.

Perhaps you could share your entire sketch with us?

@VE7JRO Will do. Thank you.


text:
Can Arduino go in and out of Sleep or Deep Sleep Automatically?
I am wondering if an Arduino Uno can go in and out of deep sleep automatically with some sort of cue such as a certain time. In my case I have a small light connected to my Arduino Uno as well as a DS1302 clock module which is being powered via a phone charger but overnight the light will be off and I do not want the Arduino idling overnight. So can it be programmed to turn on/off based on the time being read from the clock which would be the same time as the light turning on? I have seen many videos of entering/exiting deep sleep but they all require a manual input such as a button. If not possible are there any other power saving options out there?

Does this answer your question? What are (or how do I use) the power saving options of the Arduino to extend battery life?

The Arduino goes into deep sleep when you tell it to. It wakes up when it gets an interrupt. What that interrupt is is (pretty much) up to you.
If you are using an RTC most will have an alarm function that will trigger an IO pin which can be used as an input (like a button) to the Arduino. Or you can use a timer (the watchdog is common for that) to wake up periodically and check the time, then go back to sleep again.
The datasheet for the MCU on your chosen Arduino will tell you all you need to know about sleep modes and what interrupts can be used to wake from which modes.


text:
Why After instancing TinyGPS , serial stop working?
I have GSM shield (and Arduino UNO) works fine with this code :
#include <GPRS_Shield_Arduino.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <Suli.h>

#define PIN_TX    7
#define PIN_RX    8
#define BAUDRATE  9600

#define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;

char phone[16];
char datetime[24];

GPRS gprsTest(PIN_TX,PIN_RX,BAUDRATE);//RX,TX,PWR,BaudRate

void setup() {
  Serial.begin(9600);
  while(0 != gprsTest.init()) {
      delay(1000);
      Serial.print("init error\r\n");
  }
  delay(3000);
  Serial.println("Init Success, please send SMS message to me!");
}

void loop() {
   messageIndex = gprsTest.isSMSunread();
   if (messageIndex > 0) { //At least, there is one UNREAD SMS
      gprsTest.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);
      //In order not to full SIM Memory, is better to delete it
      gprsTest.deleteSMS(messageIndex);
      Serial.print("From number: ");
      Serial.println(phone);
      Serial.print("Datetime: ");
      Serial.println(datetime);
      Serial.print("Recieved Message: ");
      Serial.println(message);
      String msassages = message;
        if(msassages == "Hello"){
          gprsTest.sendSMS(phone,"hello to you");
        }
   }
}

After adding #include <TinyGPS.h> ;  it works fine too but after adding TinyGPS gps; (and nothing else) to the code header, everything stop working and i can't see anything in terminal and the program stop sending SMS back. I should mention , TinyGPS works fine individually.
Why this happen ?

Check how much memory if free. Is there memory enough for the TinyGPS as well? Reduce memory usage by using F() for all string literals. Reduce the buffer size, etc.

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


text:
How to access serial terminal through USBASP?
I have an Arduino Pro Mini that I use with a USBASP to program. These are actually a clone Pro Mini and a clone USBASP I'm using.
With this configuration, is it possible for me to access the serial port on the Arduino, through the USBASP, using the IDE serial terminal? If so, this would alleviate another connection to the computer for debugging. How to do this?

From the USBASP documentation:

Planned: serial interface to target (e.g. for debugging).

..and further on..

Firmware:
  The firmware dosn't support USB Suspend Mode. A bidirectional serial
  interface to slave exists in hardware but the firmware doesn't support it yet.

Keep in mind, that's from 2011, so it's possible someone has built an updated version of the firmware with that functionality. You'd have to do some searching (I'm not familiar with any such firmware).
For now, your best bet is just getting a TTL serial-USB converter (they're cheap) and connecting it directly to the Pro Mini.

I've searched in google and found a project in Atmel Community that supports serial with USBasp here. They called it USBASP-tty. I've not tested it yet but i think it will work. There are basically three requirements for it :

On the PC side, it uses a different software to capture the serial data from the usbasp.
It needs the conventionally bought usbasp programmers to have the two serial connections (image: PDO and PD1 connected with the ISCP header) to work. If those aren't already made, you have to rewire the pins. Normally these connections aren't made and the ICSP pins are connected to ground.
The firmware of your usbasp programmer must be updated to the provided firmware using another programmer.

Note that the LC Tech USBasp follows the schematic exactly and has the pins connected, but the Baite EvUSBasp does not.

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


text:
Possible to "inline" PROGMEM strings into a structure array initialization?
I have the following structure:
struct inst_t {
    const char *s1;
    const char *s2;
};

I'd like to initialize a constant array of this structure like this where all the strings are PROGMEM'ed:
const char START[] PROGMEM = "START";
const char ATZ[] PROGMEM = "ATZ";
const char ATE0[] PROGMEM = "ATE0";
const char OK[] PROGMEM = "OK";

static inst_t insts[] = {
    { START,      NULL },
    { ATZ,        OK },
    { ATE0,       OK }
};

You can see there is a lot of duplication here though. Is there anyway way I can inline the PROGMEM strings directly into this array initialization without separately declaring each string as being in PROGMEM?

If the strings are similar size you can, like this:
const int NUMBER_OF_ELEMENTS = 10;

typedef struct {
   char description [12];
} descriptionType;

const descriptionType descriptions [NUMBER_OF_ELEMENTS] PROGMEM = {
 { "Furnace on" },
 { "Furnace off" },
 { "Set clock" },
 { "Pump on" },
 { "Pump off" },
 { "Password:" },
 { "Accepted" },
 { "Rejected" },
 { "Fault" },
 { "Service rqd" },
 };

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
    // make a copy of the current one
    descriptionType oneItem;
    memcpy_P (&oneItem, &descriptions [i], sizeof oneItem);

    Serial.println (oneItem.description);
    }   // end of for loop

  }  // end of setup

void loop () { }

This is a bit wasteful of program memory, because you need to allow for the largest string (your example had them all similar sizes) but what you save is not needing a two-byte pointer for each string, so if they are all similar lengths, it will take about the same memory.
See my page about PROGMEM.


text:
Arduino development vs nRF51 development
Originally I had an idea to develop an Arduino-compatible project using an ATmega328P, some sensors and the nRF51822 as the BLE radio. As I progressed, I realized that if I relaxed the Arduino-compatible requirement, I could actually do away with the ATmega328P and write the application directly on the nRF51822 as it is a more capable MCU (32-bit, more memory, faster, has SPI, I2C and TTL serial, etc.) I'm not familiar with writing native applications for the nRF51822 but it seems much more complicated.
For someone that has experience in both platforms, can you please list some of the tradeoffs of developing using an ATmega328P for application + nRF51822 for radio and using the nRF51822 for both application and radio?

This sometimes even bothers me. That moment you realize that the "slave ethernet module" is running Linux on an 88Mhz x86 CPU with 256kb sram. And that you realize that your tiny MCU is the master (and 10x cheaper).

First, there are various ports of the Arduino environment to the NRF51822, but I'll leave that aside for the moment and address using Nordic's codebase or the mbed one.
Generally speaking, one of these paths will put you more in the current "real world" of professional level embedded development, in which the ARM cortex parts play a leading role.  You will have conventional multiple source file projects tied together by more ordinary means such as a Makefile or explicit IDE configuration, rather than the rather oddball way the Arduino IDE has evolved to do things.  The basic lower level APIs you will be writing against will be much more conventional - ie, your code will start in main() rather than setup() and loop(), you will generate debug messages with printf() or similarly styled member function on mbed, rather than Arduino type print()/println() (though of course you can use printf() on an Arduino with some setup).  This tends to make it a lot easier to port or share code between this and other embedded systems, or even between an embedded system and a phone or desktop communicating with or simulating it.  Of course you can treat an Arduino as a plain ATmega and do this with that as well, up to the limits of the CPU and its memories.
People tend to think of the mbed option as being an online "toy" for certain boards, but you can generally use others just by setting it for a board using the same MCU in a similar way.  And in most cases you can download a zipfile of a project with a Makefile in it that will drive arm-gcc or a few other compiler choices.  The NRF51822 does come in varieties with different onboard storage sizes, and this can sometimes require care and attention to the linker script - in a few cases a project that fits in the online build (apparently with the Keil compilation engine as its backed) will not build in the downloaded GCC configuration unless you adjust the linker script to reduce the stack size, or perhaps change compiler optimization levels.
Countering reasons you might end up keeping the ATmega would be if you need some of its I/O peripherals or its 5v I/O capability.  For example, the NRF51822 has limited hardware PWM capability compared to an ATmega so that must generally be done in software.
If you are really at home with "The Arduino Way" switching to anything more traditional may take some adjustment of thinking and habits.  On the other had, if you look at the benefits of Arduino being the variety of works-out-of-the-box, easily modified examples you can use to explore the possibility of a project, but often find yourself annoyed by the legacy of its countless quirks and atypical approaches in the longer run, then you'll probably find the adaptation to using the NRF51822 directly to have been worthwhile.

Thank you. In my application I'd like to attach at least a GPS, an IMU, a microSD adapter and perhaps temperature/barometric sensors. These take up all the UART, I2C and SPI interfaces. No need for PWM. Would this be a reasonable way to go to remove the need for an extra IC at the cost of more complicated development?

That seems like it should work, yes.  Much of your challenge will be in figuring out organized code to service the peripherals, and in how this integrates with the BLE or whatever other use you are making of the radio.


text:
How do you change the state of an image on a TFT display when the associated pin changes state?
I just recently resolved my problem on getting images to load on to my TFT display via the SD card. Thanks to UTFT_SdRaw!!! it's by far the easiest to use. For a novice like me, its been a real feat. Now translating the code, I am trying to turn on and off the image when the pin state changes:
Example:
When pin A2 on my MEGA goes high (+5vdc) I want my SD to spool up and load an image so here is my code snipit:
****myFiles.load(20, 55, 130, 130, "Power Medium.raw");****
So now when the pin state changes back to low (0vdc), how do I remove the image without clearing the entire screen? The image seems to stay frozen instead of disappearing when the pin voltage falls away.
Any ideas? I am stumped. Thanks in advance for any comments and suggestions that may help me over the hump.

It's quite silmple: just draw a box over the image the same colour as the background.
Either that or draw a different image over the top of the existing image.


text:
Arduino or Raspberry? Self Balancing robot
Here's another one, as you probably have seen before.
I'm finishing college, and I'd like, base of my subscription to be a self balancing robot that can send data to a screen. What kind of data? I am in the brain-storming zone with this question and so far I have:

Distance to other objects
Time, temperature, direction N-S-W-E, pressure (as in a car where you measure oil temp, tire pressure etc)
State of balance (as on y axix, a point going from -y to y where 0 is the balance point)
Any othet possible inte-[deleted]-resting thing you could get as a response from a little two-wheels robot
Remote control via wireless preferably

Now, the big question. Is arduino the best choice, or should I consider Raspberry Pi?
Thanks in advance!

This depends on the type of screen you want to interface. An Arduino UNO can with big effort interface a VGA signal with very low resolution and only few colors. Better are little screens (like small OLED screens or small LCD displays with integrated controller). Using a more capable Arduino (like the Mega) can extent the capabilities of your project. The RaspberryPi has of course big display capabilities (like 1080p over HDMI).
There is also another side to the problem: A self balancing robot needs to control its motors very fast (changing the direction fastly depending in sensor input). A RaspberryPi is in principle a computer, not a microcontroller. Programs in it don't have a garanteed time of execution, so especially under high load the program might have to wait for its turn, effectively destabilizing the robot. For these real time fast applications a simple microcontroller is fitted better.
Since you also want wireless control you might be interested in using an ESP (WLAN) as a microcontroller.
All in all you should use a microcontroller for driving the balancing logic and motor control. Depending in your needs you can either use only this microcontroller to do all the other things too or connect another board as a master (eg over I2C vor SPI) which tells the microcontroller what to do. For this a raspberryPi is good.
If you provide more information about the concrete target capabilities you might get a better answer. The scope of your project is too open for clear answers.

I agree that the scope of this issue is a bit wide, but I just found some boundaries regarding the main ideas of it, which are very helpful for furthure progress. I.ll keep brainstorming and will cone back into this topic and try to expose a more on-point idea.


text:
Upload to ESP32-C3 fails
I have built a custom circuit board using the ESP32-C3-MINI-1-H4 module (datasheet).
Here is a schematic:

I have the GND, Tx, and Rx lines hooked up to an Arduino Uno without the ATmega. The 3.3 V comes from an external power supply.
I have successfully put the chip into download mode (as shown from the serial output below).

ESP-ROM:esp32c3-api1-20210207
Build:Feb  7 2021
rst:0x1 (POWERON),boot:0x5 (DOWNLOAD(USB/UART0/1))
waiting for download

I attempted to upload an example sketch using the following settings (Arduino IDE).

I held down the reset button (S4) until the Rx light on the Uno started flashing.
It works about 5% of the time, but 95% of the time the TX light does not blink with the RX light and it ends in this:

A fatal error occurred: Failed to connect to ESP32-C3: No serial data received.

I'm not sure how that is possible, as the serial data appears on the oscilloscope, and it is clearly in download mode as shown by the serial output.
I have tried removing the voltage divider from the RX line, but that didn't help. Is there any way to make uploading more consistent?

"I held down the reset button(S4) until the Rx light on the uno started flashing", the correct sequence for putting the device into flash mode is to press and hold the FLASH button (io9) and press RESET(EN) once, then release(or hold) the FLASH button. BTW, read the Figure 7 of the datasheet on the reference design and the note below the diagram, you need a 1uF in parallel to your RESET switch otherwise your switch will bouncing during the reset.

// ESP32C3 USE DIO flash mode or it will not work !!!

The issue was with using the arduino as my USB to UART converter. Buying a CP2102 converter solved the issue.

You must be in flash mode DIO and watch the "USB CDC on boot" which must be on if you use native C3 usb and off if you use an external usb-serial converter.
You can upload OK in QIO mode but program wont start, that is EXACTLY what OP is asking.

Welcome to Arduino:SE  Please take a moment to read the Stack Exchange Expected behavior

This sounds like anecdotal evidence. Do you have any sources to back this up?


text:
What is the difference between Bluetooth module HC-05 and HC-42 for Arduino?
I am looking for differences between HC-05 and HC-42 Bluetooth modules for Arduino. I could not find an answer by searching google.
Both products have 6 pins and accept master and slave but I could not find further details on the differences.

It's different technology. the HC-05 uses the old Bluetooth 2.0 standard. The HC-42 in contrast uses BLE (Bluetooth Low Energy) in version 5.0.
So you have to decide what technology you want to use, either classic Bluetooth 2.0 or Bluetooth Low Energy 5.0.

Anecdotally, a few years ago I tried to use BLE and it had much less library support. Not sure how it is now.


text:
What is the equivalent of this old SPI code using the current SPI library?
I see some old library code that initializes SPI this way:
    SPI.begin();
    SPI.setClockDivider(2);

It does not use beginTransaction/endTransaction blocks, and setClockDivider is now deprecated. The current way to use SPI is to use transaction blocks where you pass the settings in.
What is the equivalent to this code using transaction blocks? Also, since the other settings (max speed, data order, data mode) aren't specified in the above code, there must be defaults. What are these defaults?

The default is:

Mode 0
MSBFIRST

Not sure on the default speed. But:
setClockDivider() sets a speed relative to the system clock. So it's impossible to say what speed that will be since it'll be different on 8MHz boards compared to 16MHz.
setClockDivider(2) would be the same as using F_CPU/2 as a speed.

I have example code here.
The code is:
#if SPI_HAS_TRANSACTION
  SPI.usingInterrupt (0);  // I am using external interrupt 0
  SPI.usingInterrupt (1);  // I am also using external interrupt 1
  SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock
#else
  SPI.setClockDivider(SPI_CLOCK_DIV8);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
#endif // SPI_HAS_TRANSACTION

digitalWrite (SS, LOW);        // assert Slave Select
byte foo = SPI.transfer (42);  // do a transfer
digitalWrite (SS, HIGH);       // de-assert Slave Select

#if SPI_HAS_TRANSACTION
  SPI.endTransaction ();   // allow external interrupts to fire now
#endif // SPI_HAS_TRANSACTION

The default setting for SPI is to use the system clock speed divided by four.


text:
Interrupts detach
I need to stop 1st interrupt from 2nd interrupt till 2nd interrup finish work... How can I do that?
Here is my 2nd interrupt:
void CHECK_IR(){
  detachInterrupt(0);
  if (irrecv.decode(&results)) {
    switch(results.value){
      case 16753245:
      Serial.println(results.value);
      if(level == 1){
       level = 1;

      }else {
        level = 1;
      }
      break;
      case 16724175:
      level = 1.6;
      break;
      case 16718055:
      level = 3;
      break;
      case 16743045:
      level = 5;
      break;
      case 16716015:
      level = 9.9;
      break;
    }
    irrecv.resume();
  }
}

1st interrupt:
void zero_crosss_int() {

   delayMicroseconds(level*1000);
  digitalWrite(AC_LOAD, HIGH);
    delayMicroseconds(100);
  digitalWrite(AC_LOAD, LOW);

}

Here I detachInterrupt(0); detach 1st interrupt, but it is not right because I need it to work again, so i need interrupt 1st to sleep till 2nd intrrupt finish switch statment. Any solution for this?

Please describe your design and what you want to achieve. You are asking for a solution to a problem that might just be a misunderstanding of how this works.

In my 1st interrupt I have delayMicroseconds it cause if switch never run... It is the problem. I added above 1st interupt..

You can re-attach the other interrupt at the end of your interrupt handler.

How? I tried but not working... Also is there any way to avoid delay?


text:
Reconstruct uint32_t from char array to RTC.set
I am currently experimenting with a Digistump ATTiny85. Since it has no Serial, I use the basic DigiUSB library for communication. The RTC library used is this one: https://github.com/JChristensen/DS3232RTC/. The DigiUSB library is from Digispark.
I attached a DS3232 via TWI to the Digistump, because I want to use this construct as a USB-Realtime-Clock.
Initially setting the time in the setup method works as follows
  RTC.set(1532341020);

But I am unable to transfer the time via the pseudo serial connection and set it remotely. What I've tried so far:

Using union with char and uint32_t. Althougt the char representation is correct (tried DigiUSB.println()), the uint32_t representation of this union is not what I need.
Tried to adapt to some shifting examples, but seriously got lost here. All examples where about 4 byte streams.
atoi and some other functions with no success.

Here is my current sketch
#include <DS3232RTC.h>
#include <DigiUSB.h>

//union ArrayToInteger {
//  char array[10];
//  uint32_t integer;
//};

unsigned char foo[10];
uint32_t num;

void setup() {
  RTC.begin();
  //RTC.set(1532341020);
  DigiUSB.begin();
}

void loop() {
  if (DigiUSB.available() >= 10) {
    for (int i=0; i<=10; i++) {
    foo[i] = DigiUSB.read();
  }
  RTC.set((uint32_t)foo);
  DigiUSB.delay(100);
  DigiUSB.refresh();
  //DigiUSB.println(_foo.array);
  DigiUSB.println(RTC.get());
} else {
  DigiUSB.refresh();
  DigiUSB.println(RTC.get());
  DigiUSB.refresh();
  DigiUSB.delay(1000);
  }
}

In the end I need the a char _foo 0123456789 represented as/converted to uint32_t num 0123456789
Kinda stuck here. Can anyone point me in the right direction ore provide an example?

add links to libraries. a number representation of time with RTC is 'Epoch' - seconds from 1.1.1970. what do you mean by "char representation"?

You may try atol(), but note that from Jan 19 2038 you will need to use strtoul() instead.

how do you send the epoch value?

@EdgarBonet atol errors invalid conversion from 'unsigned char*' to 'const char*'. Same with strtoul.

if (DigiUSB.available()) { time_t epoch = DigiUSB.parseInt(); RTC.set(epoch);}?

@Juraj DigiUSB does not support .parseInt.

Don't make foo unsigned.

@EdgarBonet Thanks. Already fixed that. But when I do RTC.set(atol(foo)) it does not set the time correctly.

Answering this question based on the help from above. It works with this code. Thank you all for the help. The clock does not reply the newly set time instantly, but after a few seconds.
#include <DS3232RTC.h>
#include <DigiUSB.h>
char foo[10];

void setup() {
  RTC.begin();
  DigiUSB.begin();
}

 void loop() {
   if (DigiUSB.available() >= 10) {
     for (int i=0; i<=10; i++) {
       foo[i] = DigiUSB.read();
   }
   RTC.set(atol(foo));
   DigiUSB.delay(100);
   DigiUSB.refresh();
   DigiUSB.println(RTC.get());
} else {
   DigiUSB.refresh();
   DigiUSB.println(RTC.get());
   DigiUSB.refresh();
   DigiUSB.delay(1000);
   }
}

There are several possible issues here:

can you send the number, as a string, from the PC to the ATtiny?
can you convert the string to an actual number?
can you give this number to the RTC?

The phrasing of your question sounds like your issue is with the
conversion. However that is easily handled with atol(). Here is a test
program I tried on my Uno:
void setup() {
    char time_string[] = "1532341020";
    uint32_t time_number = atol(time_string);

    Serial.begin(9600);
    Serial.print("string: \"");
    Serial.print(time_string);
    Serial.print("\", number = ");
    Serial.println(time_number);
}

The output is:
string: "1532341020", number = 1532341020

Indeed atol does the trick. For completeness, I answered by posting the working code. Thanks for input.


text:
Risks of ftdi_eeprom? - TX always high after flashing
I flashed an Arduino Nano compatible with ftdi_eeprom and the following config:

vendor_id=0x0403    # Vendor ID
product_id=0x6001   # Product ID

max_power=0     # Max. power consumption: value * 2 mA. Use 0 if self_powered = true.

###########
# Strings #
###########
manufacturer="FTDI"     # Manufacturer
product="Arduino Nano"  # Product
serial="arduino_1"      # Serial

###########
# Options #
###########
self_powered=false  # Turn this off for bus powered
remote_wakeup=false # Turn this on for remote wakeup feature
use_serial=true     # Use the serial number string

# Normally out don't have to change one of these flags
BM_type_chip=true       # Newer chips are all BM type
in_is_isochronous=false     # In Endpoint is Isochronous
out_is_isochronous=false    # Out Endpoint is Isochronous
suspend_pull_downs=false    # Enable suspend pull downs for lower power
change_usb_version=false    # Change USB Version
usb_version=0x0200      # Only used when change_usb_version is enabled

########
# Misc #
########

filename="eeprom.new"   # Filename, leave empty to skip file writing

My corresponfing udev rules work and I get /dev/arduino_1 after connecting.
However. After the flash, everything seems to work, But: The TX-LED is constantly on. Even, when the device is not sending. Why?
Update & solution
First, I removed this line, because it threw warning messages (outdated)
# BM_type_chip=true         # Newer chips are all BM type

Then I studied the schematics of the Nano and figured out, that RX and TX  LEDs are indeed connected to CBUS0 and CBUS1. So, I added two lines to my config
  cbus0=RXLED
  cbus1=TXLED

Which had the effect, that now both RX and TX where constantly on. So, I finally read the manual which says on page 11, that the commands in question need a trailing #. I updated my config again:
cbus0=RXLED#
cbus1=TXLED#

Extra:
Indeed, I had to install ftdi_eeprom to get the job done

 apt-get remove ftdi-eeprom
 apt-get install swig libusb-1.0-0-dev libconfuse-dev doxygen
 git clone https://github.com/legege/libftdi.git
 cd libftdi.git
 cmake .
 make
 make install
 ftdi_eeprom/ftdi_eeprom --flash-eeprom myconfig.conf

The ftdi_eeprom utility re-writes the entire EEPROM, not just the selected bits you have chosen.  That includes the "CBUS" pin configurations.
You need to check on the Nano's schematic which LED is connected to which CBUSx pin on the FTDI and set it accordingly.  You do that in your config using:
cbus0=TXLED
cbus1=RXLED

for example.
Possible settings for the CBUS pins are:

TXDEN
PWREN
RXLED
TXLED
TXRXLED
SLEEP
CLK48
CLK24
CLK12
CLK6
IO_MODE
BITBANG_WR
BITBANG_RD
SPECIAL

Except CBUS4 which only has the functions:

TXDEN
PWRON
RXLED
TXLED
TX_RX_LED
SLEEP
CLK48
CLK24
CLK12
CLK6

There is a chance that your pre-packages version of ftdi_eeprom doesn't support those settings, so you will need to download and compile the latest version from source from here: https://github.com/legege/libftdi
Also during testing I accidentally changed the VID of one of my boards thus rendering it unresponsive.  I did that by omitting the 0x from the VID and PID numbers.  Extreme care should be exercised using thin utility.  I have submitted a patch to allow the specification of a default VID for recovery from such situations.

I'll try that today and give a reply. Thanks very much so far


text:
Can this Motor shield support other arduino functions?
http://www.flipkart.com/grab-em-l293d-motor-driver-arduino-shield/p/itmehvzzpzj4wyby?pid=ETYEHVZZFFHRFMFG
I want to ask whether this shield will allow me to use the free pins of arduino for other functions?

Anything that's not connected to something on the shield can be wired to something else of your choice. The trick, though, is to know what is connected to where on the board. Is there a schematic?

@Majenko Schematic is what I was searching for but I could not find any, all i could dig up is this page,

Then all you can do is buy one and inspect it closely and follow tracks around. It looks to use a shift register it its core, so will be using very few pins.

@Majenko Alright thanks, the only problem is I have already spent 90 percent of my pocket money, so I wanted to double check anyways thanks, I shall order it

As Majenko said, most pins probably aren't used. The only problem is to access the unused pins. As the shield goes into the female headers on the UNO, those are no longer accessible. Looking at the board, they only added some throughholes for pins A0-A5.

@Gerben I got the shield delivered and actually it came with female header seaters on the top which can make it stackable. Thanks for the help though

Yes, this motor shield can allow other components to be used. You just have to make sure that the pins being used by the shield are not used by you for other tasks. Generally all shields are designed such that they do not hamper the productivity of arduino. What use would only a motor driver be? Therefore they ensure that they do not block other pins.


text:
Interrupt numbering
I'm using an Arduino Mega and four of its interrupts. Each interrupt is only used to start/stop a timer, depending if it's rising or falling, so effectively runs the same function. Does anyone know if theres a way to differentiate between which interrupt has been triggered? This way I can attach them all to the same ISR and just start/stop different timers.
Thanks,
Shaun

The only sure-fire way of knowing which interrupt triggered your ISR is to examine the GPIO pin that the interrupt is associated with.
You need to use CHANGE interrupts so that you can keep track of the state of the pins - both HIGH and LOW.  When you get an interrupt and read all the GPIO pins you have tied to the ISR you can then compare their values to the previously stored values. Any pins that have changed since the last ISR (or a pre-defined initial state) can be processed and handled accordingly.
Yes, it adds a certain amount of overhead to your code, and using digitalRead() may not be the most efficient way of doing it. Instead you may want to use direct port access to read the pin's state directly.

Thanks, I will have to look into direct port access as I haven't done this before.

Assuming that by "Mega" you mean the Mega 2560, see sections 15.2.4 and 15.2.5 of the 2/2014 datasheet referring to the External Interrupt Flags and Pin Change Interrupt flags:

When an edge or logic change on the INT7:0 pin triggers an interrupt
  request, INTF7:0 becomes set (one). If the I-bit in SREG and the
  corresponding interrupt enable bit, INT7:0 in EIMSK, are set (one),
  the MCU will jump to the interrupt vector. The flag is cleared when
  the interrupt routine is executed. Alternatively, the flag can be
  cleared by writing a logical one to it. These flags are always cleared
  when INT7:0 are configured as level interrupt.

It is not clear from the above when specifically "The flag is cleared when the interrupt routine is executed" happens. It wouldn't be much use if it happened on ISR entry so I'll take a guess that it happens on return from interrupt, in which case the flags would be available to read in the ISR. An experiment would be in order, here. These flag registers are known to the compiler as EIFR and PCIFR, respectively.

My reading of the datasheet (see section 7.8) makes me think the flags are cleared at ISR entry. Only the GIE is enabled during RETI (it specifically mentions it) and it reads like it's at the start of the ISR that the flag is cleared: "The first type is triggered by an event that sets the Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding Interrupt Flag.".

For the RETI it says: "A return from an interrupt handling routine takes five clock cycles. During these five clock cycles, the Program
Counter (three bytes) is popped back from the Stack, the Stack Pointer is incremented by three, and the I-bit in
SREG is set." - So yes, it is very very woolly in its wording, but I would lean towards the interrupt flags not being available to read in the ISR, which is a bit poor really. Personally I prefer the Microchip method where it is up to the user to manually clear the interrupt flag when it is finished with.

Thanks for the response, I'll test this method and post whether or not I can get it to work.

@Majenko: The only reason I hold out any hope at all that they'd be readable within the ISR is that someone designed those registers to be readable, which would be pointless if it is cleared during ISR vectoring (not to say it wasn't done that way!). The program would only ever be able to read zero.

You can read them outside an ISR when the interrupt is disabled. You can use it like a flag that is set by hardware which you can then check as and when you want. You get the notification but you don't have to respond immediately.


text:
Arduino IDE unable to see serial connection on OS X El Capitan
For some reason the Arduino IDE is unable to see my Arduino Uno even though it is connected. I have reinstalled the Arduino software, but no luck come of it. I connected the Arduino to my friends mac, who's could see it.. I am very confused and greatly appreciate any help.

Thanks,
Shaun

I ran into a similar problem years ago on an ATMega128 (before Arduino) and you just have to be aware of alternative functions for the port. In this case PD0 is Hardware Serial RX which is a receive pin.
Here's some relatively older code based around the same idea:

Yes, you can use the RX/TX pins as regular IO. Just don't call the Serial.begin() in your code, and make sure you call a pinMode() for them.

from: http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=b928292f91c78b57b5683484af0f635e&topic=12396.msg93239#msg93239
Another interesting post, fourth post: http://www.nerdkits.com/forum/thread/536/
where they disable the serial functionality once the code begins, downside (a above) you will lose serial comms, so it depends on how much you need them.
UCSR0B = 0;

I'm not sure how successful that would be in today's arduino, I know a lot (if not all) of the prior functionality is maintained, but I haven't used them in a long while.
The pin should become active again as the bootloader will automatically reenable it upon reset (although I haven't personally tested it). It will just make debugging that little bit harder if you need to.
As I mentioned in my comment, if you have another pin available to you, use that instead.

In case someone else has this problem..
Turns out, you can't be connect to pin D0 whilst using serial.

That's not entirely true, but in essence you're on the mark. May I suggest you have a read of the data sheet of the ship you're using. An aptly placed pull up/down resistor (I can't remember which off the top of my head) and using the pin in a particular orientation will also be 'ok'. A lot of external boards use jumpers for this exact reason to a) enable the pin to e used for serial programing/connection yet b) also used within the project. If you have another pin available for ease of use, yes, use that. But do and try and make your answers more complete