text:
How do I keep one function continued until a variable is completed?
The code's purpose is to change from one led to another if the LDR detects a certain level of light for a given time. Currently, since I cannot wait 5 minutes to complete one circuit, each LED should be on for 1000 ms. At one stage in the code, there are no LEDs on. The LEDs should not turn on until the LDR has sensed no light and then light levels necessary for the code to restart.
Here is the code;
const int buzzer=3;
const int ldr = A4;

void setup () {
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(buzzer, OUTPUT);
    pinMode(ldr, INPUT);
}

void loop() {
    int ldrStatus = analogRead(ldr);

    if (ldrStatus >= 300) {
        digitalWrite(13, HIGH);
        delay(1000);
    } else {
        noTone(buzzer);
        digitalWrite(13, LOW);
        digitalWrite(12, LOW);
    }

    if (ldrStatus >= 300) {
        digitalWrite(13, LOW);
        digitalWrite(12, HIGH);
        tone(buzzer, 100, 30);
        delay(1000);
        tone(buzzer, 100);
        digitalWrite(12, LOW);
        digitalWrite(13, LOW);
    } else {
        noTone(buzzer);
        digitalWrite(13, LOW);
        digitalWrite(12, LOW);
    }
}

I have realised that the purpose of my code is unclear. What happens is one LED turns on when the LDR senses light. If the light continues, then the buzzer will sound once and the LED will change to a different colour LED. If the LDR continues to detect light, then all LEDs will turn off and the buzzer will sound continuously. The only problem is that the code doesn't stop until the LDR has sensed a high enough decrease in light levels.

do you have two logins? ... you posted your question as Zoe Melck and you edited the question as Zoe .... please click the Flag button at bottom of your question and click moderator  intervention  and request to merge your accounts

It looks to me that Zoe and Zoe Melck are the same person. I suggest you follow the suggestion made by jsotola.

The description of what the program is supposed to do is very confused. I suspect it may not be very clear in your mind and, if you manage to explain it in clear and precise prose, you may be halfway through writing it in good code.

You have a couple of issues in your code.
Analog inputs are versatile and (most) can be used as digital inputs (ie. on/off). For this application you are after the analog value of the LDR, however this is not how you have implemented it. You are declaring the LDR pin as a digital pin by pinmode(ldr, INPUT). Delete this line altogether. For reference, see the analog read documentation.
Secondly you have two if statements that are the same.
if (ldrStatus>=300) {
  digitalWrite(13, HIGH);

and
if (ldrStatus>=300) {
  digitalWrite(13, LOW);

I suspect that one of them is supposed to be a less than < sign.
Both LEDS are off beause it is executing this section of code:
}else{
  noTone (buzzer);
  digitalWrite (13, LOW);
  digitalWrite (12, LOW);

}
I suggest you add Serial.println() lines (documentation here) to your code for debugging. Particularly helpful would be to add it in the if and else statements as well as adding Serial.println(ldrStatus) as follows:
int ldrStatus=analogRead(ldr);
Serial.println(ldrStatus);
if (ldrStatus>=300) {

Refer to this document on how to open your Serial Monitor in the Arduino Software (IDE).
Bonus Hint:
You can auto-format your code by using ctrl + T. See this article for more info.


text:
How to calibrate Mpu6050 using library?
I am using i2cdev library
Code:(i did not know this code is correct or not)
#include <Arduino.h>
#include <MPU6050.h>
#include <kalman.h>
#include <stdint.h>

#define ACCELLSB  2048
#define GYROLSB   16.4

#define CONSOLE
#define CALIBRATE

#ifdef  CALIBRATE
int16_t Accel_X_offset;
int16_t Accel_Y_offset;
int16_t Accel_Z_offset;

int16_t Gyro_X_offset;
int16_t Gyro_Y_offset;
int16_t Gyro_Z_offset;
#endif

MPU6050 mpu6050;

Kalman  AngleX;
Kalman  AngleY;

void setup()
{
   mpu6050.initialize();
   mpu6050.setFullScaleAccelRange(MPU6050_ACCEL_FS_16);
   mpu6050.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

   #ifdef CALIBRATE
   mpu6050.CalibrateAccel();
   mpu6050.CalibrateGyro();

   Accel_X_offset = mpu6050.getXAccelOffset();
   Accel_Y_offset = mpu6050.getYAccelOffset();
   Accel_Z_offset = mpu6050.getZAccelOffset();

   Gyro_X_offset  = mpu6050.getXGyroOffset();
   Gyro_Y_offset  = mpu6050.getYGyroOffset();
   Gyro_Z_offset  = mpu6050.getZGyroOffset();
   #endif

   int16_t AccelX, AccelY, AccelZ;
   int16_t GyroX, GyroY, GyroZ;

   mpu6050.getMotion6(&AccelX,&AccelY,&AccelZ,&GyroX,&GyroY,&GyroZ);

   // I am going to use this values in kalman filter
   #ifdef CALIBRATE
   AccelX -= Accel_X_offset;
   AccelY -= Accel_Y_offset;
   AccelZ -= Accel_Z_offset;

   GyroX  -= Gyro_X_offset;
   GyroY  -= Gyro_Y_offset;
   GyroZ  -= Gyro_Z_offset;
   #endif
}

void loop()
{

}

What is the correct way to calibrate mpu6050(Correct me what i am wrong or this is correct)?
Thanks.

I personally suggest you MPU6050_tockn library.https://github.com/tockn/MPU6050_tockn
If you use calcGyroOffsets() in setup(), it will calculate calibration of the gyroscope, and the value of the gyroscope will calibrated.
#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets();
}

If you use calcGyroOffsets(true) in setup(), you can see state of calculating calibration in serial monitor.
#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
}

Serial monitor:
Calculate gyro offsets
DO NOT MOVE MPU6050.....
Done!
X : 1.45
Y : 1.23
Z : -1.32
Program will start after 3 seconds

If you know offsets of gyroscope, you can set them by setGyroOffsets(), and you don't have to execute calcGyroOffsets(), so you can launch program quickly.
#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.setGyroOffsets(1.45, 1.23, -1.32);
}

But if want to do it with Kalman filter goto https://github.com/jarzebski/Arduino-KalmanFilter/blob/master/KalmanFilter_MPU6050/KalmanFilter_MPU6050.ino It will guide you.

Thanks for your response in MPU6050_tockn library complementary filter is used but i want to use kalman filter so can you explain how to calibrate using this library?

I just edited answer for that. But it is using KalmanFilter.h not kalman.h

source: Stack Exchange

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

sort: votes


text:
How send method POST with JSON? Arduino UNO R3 + SIM900
Why is the server side of php not loading any data from arduino? What did I do wrong?
  String reading="{\"latitude\": 12.983027,  \"longitude\": 80.2594}";
  mySerial.println("AT+HTTPINIT");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CID\",1");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"URL\",\"http://gerro.usermd.net/updateData.php\"");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CONTENT\", \"application/json\"");
  toSerial(1000);

  mySerial.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  toSerial(5000);

  mySerial.println(reading);
  toSerial(1000);

  mySerial.println("AT+HTTPACTION=1");
  toSerial(15000);

  mySerial.println("AT+HTTPREAD");
  toSerial(1000);

  mySerial.println("AT+HTTPTERM");
  toSerial(500);

Result:
AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","http://gerro.usermd.net/updateData.php"

OAT+HTTPPARA="CONTENT", "application/json"

OK
AT+HTTPDATA=46,100000

DOWNLOAD

OK
AT+HTTPACTION=1

OK

+HTTPACTION:1,200,55
AT+HTTPREAD

+HTTPREAD:55
array(0) {
}
array(0) {
}
nic ciekAT+HTTPTERM

OK

EDITING
void toSerial(int delay_ms)
  {
    delay(delay_ms);

    while(mySerial.available())
    {
       Serial.write(mySerial.read());
    }
  }

PHP
<?php
var_dump($_POST);
if (isset($_POST['latitude']) && isset($_POST['longitude']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
//code
} else {
echo 'nic';
}

What exactly does toSerial() do? Post all of it.

Check your server first, as far as I can tell, your server return an empty array even when I test it with Postman, so it has nothing to do with your arduino code. It is your php code that doesn't handle the POST request correctly.

@hcheung as it tests with postman it all works and returns data from $ _POST. I think you tested it badly. In the php file there is var_dump ($ _ POST) and hence the result array (0) {}

@TisteAndii I've already edited the post.

on the server php shows that it does not receive CONTENT-TYPE and CONTENT-LENGTH from arduino

Good luck then if you are saying you could get the correct Postman result while I can't even test it correctly. If my Postman test get the same result as your Arduino code, what does that tell you?

@hcheung maybe you haven't enabled the POST method

Trust me, I use Postman on daily basis...

@hcheung however you were right, it was wrong in the php file, instead of $ _POST you had to use file_get_contents("php://input") !

You had to change the php file:
var_dump($_POST);

to:
echo print_r(json_decode(file_get_contents("php://input")));

Thank you !

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


text:
NodeMCU Power Draw and charging Circuitry
I am planning to build a small wireless keyboard, around 5 buttons and 1 rotary encoder, that will connect via WiFi to my Spotify account. For this project, I was looking at the Node MCU for the board.
I could not find online how much of a battery I will need for this project. I read somewhere that it can draw up to 200mA, so, if I use 4 of these batteries and run them through a 3V3 regulator, i should have 20.000mAh, so it should be able to be powered on for at least 100 hours, right? But it will actually be more, as it does not draw 200mA consistently, right?
Should this work? Do you have any other suggestions? Maybe some different batteries?
Also, how should I go about to make it so that it can have an USB C port that can charge the batteries while it is still in use? Sorry if this question is stupid, this is my first real project.
I thought the easiest, cheapest and dumbest solution was to simply try and fit in a regular 28.000mAh power bank and charge the NodeMCU via USB. Is this a decent idea?

The average power draw would be very dependent on what your NodeMCU does. My experience is that, with the typical IoT applications I use them for (checking and responding to incoming messages, checking buttons or sensors, occasionally sending small amounts of data), the NodeMCU will typically not use more than about 15-20mA on average. This is without putting it in a sleep mode. Your application does not sound very different, unless it requires continuous Wifi traffic. My advice is to measure the power draw and base the battery capacity on that.

NodeMCU could take up to 180mA when connecting to WiFi, and the esp8266 operated at 3.0-3.6v. you need to make sure that the power supply could provide steady voltage at the sudden surge of current, in many of the early esp8266 dev board design, this was one of the problem that the sudden surge of the current cause voltage drop to below 3.0v even for very short period of time.

When selecting a voltage regulator for battery-powered application, you need to pay attention to quiescent current, the regular that you linked to has a quiescent current of 2-3mA, meaning that even your NodeMCU is in sleep mode, the regulator itself will drow 2-3mA.

The regulator that you referred to also has quite a big drop-out voltage (it requires 4.5v input to provide steady 3.3v output). This means that you need two batteries in serial, and this will complicate your charging circuit design. The best is to loop for LDO (Low Dropout) regulator that is designed for battery-power application, it typically have a dropout voltage of around 200-300mV.


text:
VLcd pin to ground?
I just bought an ERC12864-655 LCD screen.
On the datasheet it says that I need to connect the vlcd pin to GND.
However in this (page 8) datasheet it says that vlcd is the main power supply. As far as I know ground is no power supply. That doesn't make sense to me.
So what should I do with this pin?

It appears that the LCD is powered/switched by the chip, not directly powered externally. The 10K to ground would be a pulldown to keep pin 20 from floating when the LCD is not being powered, and the .33 uF cap would be for power filtering.
The datasheet pointed to by your second link is a quality-control document; not quite what most of us call a datasheet, but Note B on page 1 suggests more documentation is available on the manufacturer's website. Their interfacing description and demo code should help.

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


text:
How to analogRead() 2 separate pins simultanously?
I am trying to create a simple piano playback using a flex sensor, a proximity sensor and a piezo buzzer.
I want to have it so that when the flex sensor is triggered, a sound is played on the piezo buzzer. The tone it makes is dependent on the values received from the proximity sensor.
Here is my code:
int psrAnalogPin = 6;
int fsrAnalogPin = 10;
int speaker = 9;
int fsrReading;
int psrReading;

void setup(void) {
  Serial.begin(9600);
  // We'll send debugging information via the Serial monitor
  pinMode(speaker, OUTPUT);
}

void loop(void) {
  psrReading = analogRead(6);
  delay(10);
  psrReading = analogRead(6);
  delay(10);
  Serial.print("\n psr reading = ");
  Serial.println(psrReading);
  fsrReading = analogRead(10);
  delay(10);
  fsrReading = analogRead(10);
  delay(10);
  Serial.print("\n fsr reading : ");
  Serial.println(fsrReading);
  if(fsrReading < 980 && psrReading > 599){
    tone(9, 400, 1000);
  } else if (fsrReading < 980 && psrReading > 500){
    tone(9, 500, 1000);
  } else if (fsrReading < 980 && psrReading < 392){
    tone(9, 600, 1000);
  }
}

When I look at the serial monitor's output, the values output seem to be only reading from my flex sensor(fsrReading) and not my proximity sensor. If I only read the proximity sensor's value it works, but not both at the same time.
How can I get it so that it reads both values instead of just one?

Which board are you using?

You cannot take two analog readings simultaneously, but you can take them one after the other, just like you did. That being said, I see nothing wrong in your code. Are you sure you have no wiring problems?

You can try using Interrupts instead of polling the sensor values, as interrupt will only be activated during rising-edge or falling edge. More info on interrupts:

http://playground.arduino.cc/Code/Interrupts
https://gonium.net/md/2006/12/20/handling-external-interrupts-with-arduino/

This is not a full code but more of an explanation of the logic of your program.

when the flex sensor is triggered, a sound is played on the piezzo buzzer. The tone it makes is dependent the values received from the proximity sensor.

Follow this logic and try to code it:
1- read the flex sensor values
int val = analogRead(flexPin);

2- if it is triggered, THEN read the proximity sensor.
if(val > minimum) {
  int distance = analogRead(proximityPin); //this line depends on which proximity sensor you are using

3- play the sound accordingly to the proximity sensor (still in the if loop).
analogWrite(distance);

This logic should work fine. If you could include more info like board, flex sensor and proximity sensor, that could help.

authors: Андрій Красоткін

authors: พงศ์มร สุพะธีระ

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


text:
De-Auth "attacks" using Arduino?
I'm trying to use my Arduino and an ESP8266 to spam De-Auth "attacks". I am quoting attacks because I do not plan on using this for malicious or destructive purposes. I've heard that the ESP8266 supports monitor mode, but I haven't found any information about using it to spam De-Auth packets. I want to do something similar to the mdk3 command in Linux (mdk3  d).
If you need me to clarify anything, please just ask.
Thanks in advance!

you'll need version 2.0.0 (or earlier?) version of the arduino esp8266 stuff if  you want to compile something that can do this

This seems to be a question about the ESP8266 and not about an Arduino.

If you can transmit raw 802.11, take a look at the code for aircrack-ng, specifically aireplay-ng.c - this software is known to work on arm boards.

Check this GitHub repo, could be what you are looking for: https://github.com/spacehuhn/esp8266_deauther


text:
Problem with connecting pins on an Arduino board with an L239D shield
I have an L239D motor shield just like the Adafruit motor shield. I had a question in my mind. While making a robot, I could not connect my pins from various sensors in Arduino as the motor shield is already fitted on the board. So how can I connect my pins?
PS: I have the same board as shown in the picture

With solder and wire to the pins that aren't used by the motor shield? To a prototyping shield between the Arduino and the motor shield? To another Arduino and link the two together through some serial protocol or other? There's millions of ways. You don't have to limit yourself to just sticking bits of LEGO® together. Get creative.

You could use the 6 analog pins, as those are accessible in the bottom-right corner (you can use analog pins just like a digital pin). Second option if to remove the headers from the shield, and replace them with stacking headers

That's a common problem that has many solutions.
The cheapest way is to solder the wires directly as many comments said. Though this is quite dirty, it should work for you.
The more professional way is to use these Arduino stackable header. They can even let you have a shield on top of your shield. This is the best choice in my opinion.


text:
My RTC DS1307 isn't returning any information. It seems to be stuck in the isrunning() function. Does anyone have debugging tips?
I'm using an RTC DS1307 to keep track of time for long periods. It seems to be stuck in a function. I'm using the RTClib suggested by adafruit.
How can I get it unstuck and get values returned? Are there any debugging or troubleshooting tips that would be helpful?
Referencing this excerpt for the code I'm running.
void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) { //// **Where I think my code errors.**
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}

This is the example code modified slightly to increase logging, included with RTClib. It's for the DS1307.
Currently the output from the serial port is as follows:

RTC is found.

I changed the code to the below:
    // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {
      while (!Serial); // for Leonardo/Micro/Zero

      Serial.begin(9600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      } else {
        Serial.println("RTC is found.");
      }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      } else {
        Serial.println("RTC is RUNNING.");
      }
    }

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

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" (");
        Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
        Serial.print(") ");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();

        Serial.print(" since midnight 1/1/1970 = ");
        Serial.print(now.unixtime());
        Serial.print("s = ");
        Serial.print(now.unixtime() / 86400L);
        Serial.println("d");

        // calculate a date which is 7 days and 30 seconds into the future
        DateTime future (now + TimeSpan(7,12,30,6));

        Serial.print(" now + 7d + 30s: ");
        Serial.print(future.year(), DEC);
        Serial.print('/');
        Serial.print(future.month(), DEC);
        Serial.print('/');
        Serial.print(future.day(), DEC);
        Serial.print(' ');
        Serial.print(future.hour(), DEC);
        Serial.print(':');
        Serial.print(future.minute(), DEC);
        Serial.print(':');
        Serial.print(future.second(), DEC);
        Serial.println();

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

What is the serial output?

@dpw per your suggestion, I included the serial output. I also included full code to review.

Try changing the battery.

@Gerben I've checked the battery voltage multiple times. It has 2.98 volts under load and 2.98 off load. Is this acceptable?

That's just fine.

@Gerben looks like min voltage is 2v max is 3.5v according to this datasheet.

First thing I see is the Serial setup seems a bit backward:
  while (!Serial); // for Leonardo/Micro/Zero
  Serial.begin(57600);

First, begin Serial; then wait for it to become ready:
  Serial.begin(57600);
  while (!Serial); // for Leonardo/Micro/Zero

Next, is this while(1); inside the if statement:
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

Which says "if !rtc.begin(), then println and go into an infinite loop that does nothing".
Try:
while (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    //delay(500);  // depending on how fast you want this thing to retry/print
}

the final thing I see, is the next section of code appears like it might be "work code" but is in the setup() function and is missing any kind of a loop.  So it's going to run the if statement once, then setup() exits (and loop() starts getting called).
Either replace the "if" with a "while" and wait for "rtc.running()"
while (!rtc.running()); // Waiting for RTC to be running
// Set the clock time

or move it out of setup() and put it inside loop()
void loop() {
  if (! rtc.isrunning()) { //// **Where I think my code errors.**
    Serial.println("RTC is NOT running!");
    // Perhaps try and fix it?
  } else {
    // If the time hasn't been set; set it; then move on
  }
}

You make a good point that I'm asking about my program not responding, and I have all these loops that don't end and don't respond!
This is the example code that came with the library. I believe it worked before.

Wow, that was hard to figure out. My RTC DS1307 came with an extra pin. This tripped me up when wiring the circuitry. I was off by a pin on my breadboard. Thank you everyone for your help.
Specifically, I had the ground going to the empty pin, and the 5v line going to the ground. Perhaps the circuitry allowed some current to go from the ground up and triggered the "i am here" part of the circuitry.


text:
Accessing softwareserial.available in the arduino loop function always return 0 but in the setup function returns the available byte
I am working on an accident detection system using arduino, what i want to do is to store the recipient phonenumber received as an SMS in the arduino EEPROM, using Serial1.available() to check for bytes in the software serial within the loop() function always return 0, but using it in the setup() function work fine, i have tried my best to debug but am not getting, where could i be getting it wrong. the entire code is bellow:
#include<SoftwareSerial.h>
#include <EEPROM.h>
SoftwareSerial Serial1(2, 3); //make RX arduino line is pin 2, make TX arduino line is pin 3.
SoftwareSerial gps(10, 11);
#include<LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);

#define x A1
#define y A2
#define z A3

int xsample = 0;
int ysample = 0;
int zsample = 0;

#define samples 10

#define minVal -50
#define MaxVal 50

int i = 0, k = 0;
int  gps_status = 0;
float latitude = 0;
float logitude = 0;
String Speed = "";
String phoneNumber = "";
String gpsString = "";
char *test = "$GNRMC";

void initModule(String cmd, char *res, int t)
{
  while (1)
  {
    Serial.println(cmd);
    Serial1.println(cmd);
    delay(100);
    while (Serial1.available() > 0)
    {
      if (Serial1.find(res))
      {
        Serial.println(res);
        delay(t);
        return;
      }

      else
      {
        Serial.println("Error");
      }
    }
    delay(t);
  }
}

void writeString(char add, String data)
{
  int _size = data.length();
  int i;
  for (i = 0; i < _size; i++)
  {
    EEPROM.write(add + i, data[i]);
  }
  EEPROM.write(add + _size, '\0'); //Add termination null character for String Data

}

String read_String(char add)
{
  int i;
  char data[100]; //Max 100 Bytes
  int len = 0;
  unsigned char k;
  k = EEPROM.read(add);
  while (k != '\0' && len < 500) //Read until null character
  {
    k = EEPROM.read(add + len);
    data[len] = k;
    len++;
  }
  data[len] = '\0';
  delay(2000);
  return String(data);
}

void receive_store_phoneNumber() {
  String msg = Serial1.readString();
  Serial.println(msg);
  phoneNumber = msg.substring((msg.indexOf("***")) + 3);
  writeString(10, phoneNumber);
  lcd.clear();
  lcd.print("Phone num stored");
  delay(2000);
}

void setup()
{
  Serial1.begin(9600);
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Accident Alert  ");
  lcd.setCursor(0, 1);
  lcd.print("     System     ");
  delay(2000);
  lcd.clear();
  lcd.print("Initializing");
  lcd.setCursor(0, 1);
  lcd.print("Please Wait...");
  delay(1000);

  Serial.println("Initializing....");
  initModule("AT", "OK", 1000);
  initModule("ATE1", "OK", 1000);
  initModule("AT+CPIN?", "READY", 1000);
  initModule("AT+CMGF=1", "OK", 1000);
  initModule("AT+CNMI=1,2,0,0,0", "OK", 1000);
  initModule("AT+CMGDA=\"DEL ALL\"", "OK", 1000);
  delay(200);
  Serial.println("Initialized Successfully");
  lcd.clear();
  lcd.print("Initialized");
  lcd.setCursor(0, 1);
  lcd.print("Successfully");
  delay(2000);
  lcd.clear();
  lcd.print("Callibrating ");
  lcd.setCursor(0, 1);
  lcd.print("Acceleromiter");
  for (int i = 0; i < samples; i++)
  {
    xsample += analogRead(x);
    ysample += analogRead(y);
    zsample += analogRead(z);
  }

  xsample /= samples;
  ysample /= samples;
  zsample /= samples;

  Serial.println(xsample);
  Serial.println(ysample);
  Serial.println(zsample);
  delay(1000);

  lcd.clear();
  lcd.print("Waiting For GPS");
  lcd.setCursor(0, 1);
  lcd.print("     Signal    ");
  delay(2000);
  gps.begin(9600);
  get_gps();
  show_coordinate();
  delay(2000);
  lcd.clear();
  lcd.print("GPS is Ready");
  delay(1000);
  //  writeString(10, "+2348132450841");
  lcd.clear();
  lcd.print("System Ready");
  Serial.println("System Ready..");

}

void loop()
{
  if (Serial1.available() > 0) {
    receive_store_phoneNumber();
  }

  int value1 = analogRead(x);
  int value2 = analogRead(y);
  int value3 = analogRead(z);

  int xValue = xsample - value1;
  int yValue = ysample - value2;
  int zValue = zsample - value3;

  Serial.print("x=");
  Serial.println(xValue);
  Serial.print("y=");
  Serial.println(yValue);
  Serial.print("z=");
  Serial.println(zValue);

  if (xValue < minVal || xValue > MaxVal  || yValue < minVal || yValue > MaxVal  || zValue < minVal || zValue > MaxVal)
  {
    get_gps();
    show_coordinate();
    lcd.clear();
    lcd.print("Sending SMS ");
    Serial.println("Sending SMS");
    delay(1000);
    lcd.clear();
    lcd.print(read_String(10));
    Send();
    Serial.println("SMS Sent");
    delay(2000);
    lcd.clear();
    lcd.print("System Ready");
  }
}

void gpsEvent()
{
  gpsString = "";
  while (1)
  {
    while (gps.available() > 0)          //Serial incoming data from GPS
    {
      char inChar = (char)gps.read();
      gpsString += inChar;                   //store incoming data from GPS to temparary string str[]
      i++;
      //     Serial.println("88888888888888888888888888888888888888888888");
      //     Serial.println(inChar);

      if (i < 7)
      {
        if (gpsString[i - 1] != test[i - 1])    //check for right string
        {
          i = 0;
          gpsString = "";
        }
      }
      if (inChar == '\r')
      {
        if (i > 60)
        {
          gps_status = 1;
          break;
        }
        else
        {
          i = 0;
        }
      }
    }
    if (gps_status)
      break;
  }
}

void get_gps()
{
  lcd.clear();
  lcd.print("Getting GPS Data");
  lcd.setCursor(0, 1);
  lcd.print("Please Wait.....");
  gps_status = 0;
  int x = 0;
  while (gps_status == 0)
  {
    gpsEvent();
    int str_lenth = i;
    coordinate2dec();
    i = 0; x = 0;
    str_lenth = 0;
  }
}

void show_coordinate()
{
  lcd.clear();
  lcd.print("Lat:");
  lcd.print(latitude);
  lcd.setCursor(0, 1);
  lcd.print("Log:");
  lcd.print(logitude);
  Serial.print("Latitude:");
  Serial.println(latitude);
  Serial.print("Longitude:");
  Serial.println(logitude);
  Serial.print("Speed(in knots)=");
  Serial.println(Speed);
  delay(2000);
  lcd.clear();
  lcd.print("Speed(Knots):");
  lcd.setCursor(0, 1);
  lcd.print(Speed);
}

void coordinate2dec()
{
  String lat_degree = "";
  for (i = 20; i <= 21; i++)
    lat_degree += gpsString[i];

  String lat_minut = "";
  for (i = 22; i <= 28; i++)
    lat_minut += gpsString[i];

  String log_degree = "";
  for (i = 32; i <= 34; i++)
    log_degree += gpsString[i];

  String log_minut = "";
  for (i = 35; i <= 41; i++)
    log_minut += gpsString[i];

  Speed = "";
  for (i = 45; i < 48; i++)   //extract longitude from string
    Speed += gpsString[i];

  float minut = lat_minut.toFloat();
  minut = minut / 60;
  float degree = lat_degree.toFloat();
  latitude = degree + minut;

  minut = log_minut.toFloat();
  minut = minut / 60;
  degree = log_degree.toFloat();
  logitude = degree + minut;
}

void Send()
{
  Serial1.println("AT");
  delay(500);
  serialPrint();
  Serial1.println("AT+CMGF=1");
  delay(500);
  serialPrint();
  Serial1.print("AT+CMGS=");
  Serial1.print('"');
  Serial1.print(read_String(10));    //mobile no. for SMS alert
  Serial1.println('"');
  delay(500);
  serialPrint();
  Serial1.print("Latitude:");
  Serial1.println(latitude);
  delay(500);
  serialPrint();
  Serial1.print(" longitude:");
  Serial1.println(logitude);
  delay(500);
  serialPrint();
  Serial1.print(" Speed:");
  Serial1.print(Speed);
  Serial1.println("Knots");
  delay(500);
  serialPrint();
  Serial1.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=");
  Serial1.print(latitude, 6);
  Serial1.print("+");              //28.612953, 77.231545   //28.612953,77.2293563
  Serial1.print(logitude, 6);
  Serial1.write(26);
  delay(2000);
  serialPrint();
}

void serialPrint()
{
  while (Serial1.available() > 0)
  {
    Serial.print(Serial1.read());
  }
}

only one SoftwareSerial instance can listen. it is set with listen(). https://www.arduino.cc/en/Reference/SoftwareSerialListen

how do i implement that in my code, am so frustrated already, i need hints please

As Juraj stated in the comments, you have 2 instances of SoftwareSerial, but only one of them can listen to it's receive pin at the same time (this is because they rely on the same interrupts to sample the pin). When you call gps.listen(), you set the gps interface to listen on it's receive pin. Serial1 (the second SoftwareSerial instance) will then no longer listen and thus will not receive anything. When you call Serial1.listen() it will be vice versa.
So you need to decide, on which interface you want to listen. For example you could try listening to the GPS all the time, and only switch to the other interface, if you want to send or receive an SMS (since the SIM module seems to be only controlled via AT commands, it will not send data spontaneously).
Or, as an alternative, you could switch to a bigger Arduino, which has more hardware serial interfaces, like the Arduino Mega. It has 4 hardware Serial interfaces and all of them are listening at the same time, since it is implemented in hardware, not in software.

I commented because I was sure this is a duplicate, but I had no time to search for it


text:
sro4m-2 waterproof ultrasonic sensor
I bought this waterproof ultrasonic sensor about 5 of them with the part number SR04M-2 Written on the PCB silkscreen Which is different from the usual SR04t-0.2, they are just not working, I don't know if its using a different communication protocol or its faulty because no output is coming out of the sensor at all.
if anyone out there has ever came across this type and was able to walk his/her way around it should help

compare the datasheets for the two devices ... which part of your question is about the Arduino?

Am using arduino to communicate with the sensor and its not working

there is no information about the arduino in your post ... actually, there is no question being asked ... please add relevant information, such as the sensor datasheet, the connection diagram, the arduino sketch, the description of the expected behavior and the observed  behavior, and the question that you want answered

I had exactly the same problem. The oscilloscope showed that the output is returned 500us after the digitalWrite(trigPin, HIGH), so changing the delay between trigger and pulseIn from 10us to 500us - delayMicroseconds(500), solved the problem for me.

I found this code for the SRF05 and it works for the SRO4M-2 as well.
Good Luck!
const unsigned int TRIG_PIN=13; //RX
const unsigned int ECHO_PIN=12;  TX
const unsigned int BAUD_RATE=9600;

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(BAUD_RATE);
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  const unsigned long duration= pulseIn(ECHO_PIN, HIGH);
  int distance= duration/29/2;
  if(duration==0){
    Serial.println("Warning: no pulse from sensor");
  } else {
    Serial.print("distance to nearest object:");
    Serial.println(distance);
    Serial.println(" cm");
  }
  delay(100);
}

RX = trig and TX = Echo  this is counter intuitive but it works. The manufacturer did not bother to indicate trig and echo on the PCB. I discovered this on link : https://bitbucket.org/teckel12/arduino-new-ping/issues/40/aj-sr04m-board.  When I switch RX & TX as indicated in the pics it worked


text:
Newbie trying to interface MLX90614 with Arduino Due
Im a newbie and Im trying to interface the temperature sensor mlx90614 to the arduino due using i2c bus. After a lot of digging I found this code which works,but it works only on the sda(20),scl(21) pins. I want to change this to SCL1 and SDA1 near the Aref and gnd pins. How do i modify this code? Thanks
#include <Arduino.h>
#include <include/twi.h>

#define ADDR      0x5A

//EEPROM 32x16
#define TO_MAX    0x00
#define TO_MIN    0x01
#define PWM_CTRL  0x02

//RAM 32x16
#define RAW_IR_1  0x04
#define RAW_IR_2  0x05
#define TA        0x06
#define TOBJ_1    0x07
#define TOBJ_2    0x08

#define SYNC_PIN  2

static const uint32_t TWI_CLOCK = 100000;
static const uint32_t RECV_TIMEOUT = 100000;
static const uint32_t XMIT_TIMEOUT = 100000;

Twi *pTwi = WIRE_INTERFACE;

static void Wire_Init(void) {
  pmc_enable_periph_clk(WIRE_INTERFACE_ID);
  PIO_Configure(
  g_APinDescription[PIN_WIRE_SDA].pPort,
  g_APinDescription[PIN_WIRE_SDA].ulPinType,
  g_APinDescription[PIN_WIRE_SDA].ulPin,
  g_APinDescription[PIN_WIRE_SDA].ulPinConfiguration);
  PIO_Configure(
  g_APinDescription[PIN_WIRE_SCL].pPort,
  g_APinDescription[PIN_WIRE_SCL].ulPinType,
  g_APinDescription[PIN_WIRE_SCL].ulPin,
  g_APinDescription[PIN_WIRE_SCL].ulPinConfiguration);

  NVIC_DisableIRQ(TWI1_IRQn);
  NVIC_ClearPendingIRQ(TWI1_IRQn);
  NVIC_SetPriority(TWI1_IRQn, 0);
  NVIC_EnableIRQ(TWI1_IRQn);
}

static void Wire1_Init(void) {
    pmc_enable_periph_clk(WIRE1_INTERFACE_ID);
  PIO_Configure(
      g_APinDescription[PIN_WIRE1_SDA].pPort,
      g_APinDescription[PIN_WIRE1_SDA].ulPinType,
      g_APinDescription[PIN_WIRE1_SDA].ulPin,
      g_APinDescription[PIN_WIRE1_SDA].ulPinConfiguration);
  PIO_Configure(
      g_APinDescription[PIN_WIRE1_SCL].pPort,
      g_APinDescription[PIN_WIRE1_SCL].ulPinType,
      g_APinDescription[PIN_WIRE1_SCL].ulPin,
      g_APinDescription[PIN_WIRE1_SCL].ulPinConfiguration);

  NVIC_DisableIRQ(TWI0_IRQn);
  NVIC_ClearPendingIRQ(TWI0_IRQn);
  NVIC_SetPriority(TWI0_IRQn, 0);
  NVIC_EnableIRQ(TWI0_IRQn);
}

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

  pinMode(SYNC_PIN, OUTPUT);
  digitalWrite(SYNC_PIN, LOW);

  Wire_Init();
  // Disable PDC channel
  pTwi->TWI_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS;
  TWI_ConfigureMaster(pTwi, TWI_CLOCK, VARIANT_MCK);
}

void loop() {
  uint16_t tempUK;
  float tempK;
  uint8_t hB, lB, pec;

  digitalWrite(SYNC_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(SYNC_PIN, LOW);

  TWI_StartRead(pTwi, ADDR, TOBJ_1, 1);

  lB = readByte();
  hB = readByte();

  //last read
  TWI_SendSTOPCondition(pTwi);
  pec = readByte();

  while (!TWI_TransferComplete(pTwi))
    ;
  //TWI_WaitTransferComplete(pTwi, RECV_TIMEOUT);

  tempUK = (hB << 8) | lB;
  if(tempUK & (1 << 16))
  {
    Serial.print("Error !");
    Serial.println(tempK);
  }
  else
  {
    tempK = ((float)tempUK * 2) / 100 ;
    //Serial.print("Temp UK: ");
    //Serial.print(tempUK);
    Serial.print(" C: ");
    Serial.println(tempK - 273.15);
  }
  //Serial.print(hB, HEX);
  //Serial.print(" : ");
  //Serial.print(lB, HEX);
  //Serial.print(" : ");
  //Serial.println(pec, HEX);

  delay(2000);
}

uint8_t readByte() {
  //TWI_WaitByteReceived(pTwi, RECV_TIMEOUT);
  while (!TWI_ByteReceived(pTwi))
    ;
  return TWI_ReadByte(pTwi);
}

static inline bool TWI_WaitTransferComplete(Twi *_twi, uint32_t _timeout) {
  while (!TWI_TransferComplete(_twi)) {
    if (TWI_FailedAcknowledge(_twi))
      return false;
    if (--_timeout == 0)
      return false;
  }
  return true;
}

static inline bool TWI_WaitByteReceived(Twi *_twi, uint32_t _timeout) {
  while (!TWI_ByteReceived(_twi)) {
    if (TWI_FailedAcknowledge(_twi))
      return false;
    if (--_timeout == 0)
      return false;
  }
  return true;
}

static inline bool TWI_FailedAcknowledge(Twi *pTwi) {
  return pTwi->TWI_SR & TWI_SR_NACK;
}


text:
Newbie Using Brown Out detector on Arduino Due for saving variables to eeprom?
Hi I'm a newbie and working on a project with Arduino Due(Atmel3X8E).I want to try and save the important variables to the eeprom during a power outage,using the brown out detector.Is it possible to do this?
Thank you.

What is your power source?

We plan on using the ac mains 220v 50hz stepped down to 12v.

Okay, that is good - see my answer for the details

Not a good idea - if the power goes down when you writing to EEPROM, your EEPROM data will be corrupted. The brown-out detector goal is to shut off the MCU, before it goes mad due to low power voltage.
The solution of this issue - use some huge capacitors (about 4700 mkF) - like a small UPS device.

When external power goes off, you well get enough time and power to store your bytes safely.
How it works
When +5V is okay, the capacitor is charged on, and the light diode (pins 1-2) inside of PC817 is on, so the transistor part of PC817 (pins 3-4) is open, and POWER_GOOD signal is LOW.
When power goes off, capacitor starts to discharge and give power to the right part of scheme. The Schottky diode acts as a valve, that stops the power to go to the left part. The another diode, which is inside of PC817 now goes off, and the transistor goes to close - POWER_GOOD signal goes to HIGH level and your program may start save data to EEPROM.
Why the optocoupler?
We need to investigate about internal AVR chip circuit. It has couple of diodes on each pin:

So, when we connect PIN directly to power, +5V, and connect AVR's VCC to +5V over the Schottky diode, we've got two diodes in parallel! This situation is very bad, because they may compete, which will conduct the current - and, in some cases, internal (which is weak), chip diode wins. All controller power current start flow thru this weak diode, heats it up and toasts the chip! Not very good.

I have the same circuit but without the U1 for a "solar power" display. Just connecting the 5V to an interrupt pin. Your solution is more elegant (but why an optocoupler and not just a mosfet?), but it could be more simple.

@Adriano - updated my answer

I think you could still use a simple transistor instead of an opto-coupler as per Adriano's comment. Or even just put a resistor in series with the pin. You have a resistor there already!

I think the gbg's circuit will fail in many situations. It will cause interrupt only when the power source voltage is quite low. If there is no considerable load before the diode filtering caps of the power source will likely hold enough charge and the "5V" will be falling slowly. Arduino will drain the the backup capacitor before it gets "power bad" interrupt.
Since OP is using 12V power supply a simple brownout detector giving warning when this source drops under some reasonable value (i.e. 9V) is the best way. A Zener diode and transistor (or the optocoupler) should be enough because the value of the threshold is not critical.

I suggest to add an example circuit.

But we can directly connect the optocoupler to the AC mains (with corresponding resistor and diode, of course). And change firmware to detect pulses of 50/60Hz instead of HIGH level

Connection to mains makes the circuit more dangerous. OP is a newbie after all.

An alternative solution to this is to use an "EERAM". This is an EEPROM with an SRAM buffer in front of it. A large capacitor is used to provide power while the contents of the SRAM are stored in the EEPROM.
It sounds complex, but it's simple since they are made as a dedicated chip. One good example is the 47C16 from Microchip. The EEPROM backup is completely transparent to the user, and you can use it just like an I2C connected SRAM chip (so no worries about wearing out the EEPROM by writing too often).
It's a chip I love so much that I made a breakout of the 3.3V version 47L16 (since I work mainly with 3.3V devices), and a library to support it.

I use FRAM for this. It's always write a byte if it was received, much faster and safety. Additionally you can use chain like approach to save data blocks in EEPROM for controlling of the data integrity. Try to use mosfet instead of diode and optocoupler when it powered from battery.


text:
How to shift binary into a shift register (serial in, parallel out) sequentially
I'm trying to make a continuity tester at work where I connect the input and output of a harness into a test fixture powered by an Arduino. This tester tests whether the position of the connects are pinned correctly.
Here is the diagram of my initial idea:

From one end of the connector (the output in the diagram), I want to shift in a binary that is in the power of 2. For instance, shifting in 0001, check for continuity by reading the 75HC165 (parallel in, serial out), then clear the register and then shift in 0010, and then 0100 and so on. For a correctly pinned harness, the write and read binary subtraction will be zero.
Here is my loop that attempts to perform the above:
void loop() {
  for (int i = 1; i < 4; i++) {
    reset_SIPO_register();
    shift_SIPO(pow(2,i));
    delay(2000);
    shift_SIPO(0x00));
    check_continuity(); // not implemented yet
  }
}

void reset_SIPO_register() {
  digitalWrite(reset_pin, LOW);
  digitalWrite(reset_pin, HIGH);
}

void shift_SIPO(int sequence) {
  digitalWrite(latch_pin, LOW);
  shiftOut(data_pin, clock_pin, MSBFIRST, sequence);
  digitalWrite(latch_pin, HIGH);
}

I am testing this concept on a breadboard with LEDs and the above kind of works. However, the LED is lit up one at a time and they don't turn off, not following the binary.
Is there something I'm missing here? thanks!

yes, you are missing the full schematic diagram and complete code from your post

Do not use pow(). This is a function that works with floating point
numbers. It is roughly equivalent (for y > 0) to
double pow(double x, double y)
{
    return exp(y * log(x));
}

As all transcendental functions, its implementation is prone to rounding
errors. It is not even guaranteed to give you the “correctly” rounded
version of the exact (i.e. infinite precision) result. In fact, very few
floating point functions give this guarantee.
As an example, if you compute pow(2, i) for i = 3, you get
7.9999980926513671875. This is 4 ULPs smaller than the exact value.
Passing this number to shift_SIPO() implicitly converts it to an
int, and this conversion always rounds to zero. Thus you get 7, i.e.
0b0111.
What you want is an integer, exact implementation of pow(2, i). It
turns out this is quite simple: Take the integer 1 in binary, then shift
it i times to the left. That is
shift_SIPO(1 << i);

Thank you! that worked!


text:
I’m having trouble getting a motor to run for 10 seconds and then reverse direction every time push button is pushed down
i am brand new to arduino and was looking for a little help. i am looking to activate a motor once the button is pushed for 10 seconds and then have it stop. then the next time the button is pushed, it runs in reverse for ten seconds and stops. i need it to continue this cycle everytime the button is pushed. button push 1 = forward 10 seconds, button push 2 = reverse ten seconds, button push 3 = forward 10 seconds and so on... i believe i am very close to accomplishing this task however like i said i am new to all this and i could be miles away. any help would be appreciated. i am using a mega 2560 even though the picture shows an UNO. i dont think itll matter as long as i use the correct pins.
link to tinkercad.com
int BUTTON = 9;
int DIRA = 3;
int DIRB = 4;
int FOR = true; //forward - reverse
int ENABLE = 5;

void setup() {
  //---set pin direction
  pinMode (ENABLE, OUTPUT);
  pinMode (BUTTON, INPUT_PULLUP);
  pinMode(DIRA,OUTPUT);
  pinMode(DIRB,OUTPUT);
  Serial.begin(9600);
}

void loop() {
 if (digitalRead(BUTTON) == HIGH) {
   digitalWrite(ENABLE, HIGH);
   if (FOR == true) {
    digitalWrite(DIRA,HIGH); //on forward
    digitalWrite(DIRB,LOW);
    delay(10000);
    FOR = false;
    digitalWrite(ENABLE,LOW);  //stop
   } else {
    digitalWrite(DIRB,HIGH); //on reverse
    digitalWrite(DIRA,LOW);
    delay(1000);
    FOR = true;
    digitalWrite(ENABLE,LOW); //stop
  }
 }
}`

you did not fully describe the desired behavior ... what should happen if the button is pressed and held? .... what about pressed, released and pressed again after one second?

And what is the problem with your code? Does it behave differently than expected? Then please describe in detail what you expected and what actually happened.

thanks for the replies. i hadnt even thought about different types of button presses. what i would like is that no matter if the button is pressed once, pressed and held, or pressed multipliple times, id like it to complete its cycle before the button can be pressed again. so on the push down it starts the cycle, and doesnt stop until the cycle is complete.
nothing happens when i push the button with my code and circuit as is.

the description of the problem belongs in the question at top of this page ... this site is not a forum ... reduce your code to only a push button that lights an LED when pressed ... does that work as expected?

Yes I I can get the push button to work without the motor controlling a simple RGB LED

next, write very simple code to test the motor ... run one direction for 2 seconds. stop for 2 seconds, run in other direction for 2 seconds, stop

Yes I did that already, I was able to get it to work without the L293D chip but can’t seem to get it to work with it

If you bypass the Arduino and just connect the motor wires to +5V & GND, does the motor spin? Can you get the motor to go in reverse by switching the wires?  If you can verify that then the next step would be to bypass the Arduino and  just use manual jumper wires to provide the correct voltages to the driver chip.  If this works, then you have eliminated everything except your code (assuming no dead Arduino pins).  Then replace the motor and driver chip with a simple resistor-LED combination on your output pins to provide a visual indication for output pin activity.


text:
Can you coax another I²C connection out of an Arduino Nano Every?
I'm looking to network a bunch of devices (boards in a Eurorack case) over I²C, but I don't want to compromise the address space available to each individual device for its own needs. The obvious solution here is to give each device its own I²C bus which it controls, and then connect them together over another.
Two independent I²C connections would be needed on a microcontroller in this setup, and if I understand the datasheet correctly, the MCU on the Arduino Nano Every can act as host on one bus and client on another using the Dual Mode setup of the Two-Wire Interface (see Chapter 25 of the linked datasheet), but the board only exposes two sets of I²C-capable pins and they are wired together in the schematic.
What steps would I need to take to coax another I²C connection out of an Arduino Nano Every?

ATmega4809 only has one hardware i2c interface. If you need a second i2C, you can use any GPIO pins as i2c pins and create software i2C (bit-banging) yourself, or find some software i2c library online. You can also buy i2c expander/extender as a hardware solution.

If that's the case, what exactly is the dual mode for? The host and client capabilities patently cannot use the same bus independently, as I²C is only half-duplex, so if what you say is true the datasheet seems to be misrepresenting the 4809's TWI.

If you're asking about hardware supported I2C/TWI, then you seem to have answered your own question. So, you could post an answer that says "No, not without modifying the board." For what it's worth, I don't understand the devices involved and the topology and direction of data flow well enough to know that modifying the board would ultimately help you anyway. Same for using an I2C multiplexer.

ATmega4809 datasheet does not misrepresenting the TWI. Dual mode does not mean two TWI ports, it means that you can have two set of TWI wires, one for master and one for slave, internally it controlled by setting the registers, you can think as there are two STDP switches controlled by the PORTMUX register that switch between master and slave wires. Read "15 PORTMUX" and "25. TWI - Two-Wire Interface" of the datasheet to understand the dual-mode TWI.

Welcome!
Theoretically you can connect 127 devices to the I2C bus. I suggest you do a little reading on the I2C bus before you start your design. Hopefully all of these I2C devices are on the same board but since you want to network them I have a feeling you are making a very painful mistake. I2C was never intended to be used for networking.
For a bunch of devices I would seriously look at CAN, two wires to connect them is all that is needed even for well over 250 meters or 800 feet with the baud rate of 250 kbit/s. I usually also run a ground. This will be much faster than the I2C. CAN is a simplex communication mode that turns around very fast. Each node can send and receive under software control. It does its own arbitration no need to worry about it the controllers do it for you.

I considered CAN, but I thought it a little overengineered for what I'm trying to achieve. I've clarified the question, as I didn't make it clear that the length scale is shorter than the verb "network" would suggest.

You will probably have to shield the I2C bus as that many on an audio mixer will create noise. You may also have to slow it down because of bus capacitance. Let us know how you do.


text:
Arduino UNO And SD Card Custom csPin
I've connected SD card module to Arduino UNO. I want to use PIN 10 for PWM DC motor control and because of that, I've connected CS pin directly to another pin (A3).
SD card is working properly, but after calling SD.begin(A3), it set PIN 10 to HIGH!
Immediately after SD.begin(A3) and set that pin to LOW, but meanwhile the motor took a small rotation.
I've digged into SD.cpp and Sd2Card.cpp, but couldn't find where this problem occured!
Any help appreciated....
The Solution:
Simply call SD.begin(-1) and it doesn't touch PIN10. Hope helps somebody else!

I do not see a difference for pin 10 between SD.begin(A3) and SD.begin(-1), but how do you set the SS pin for the SD card?

I've grounded SD csPin and it works.

Pin 10 is special. It's the hardware chip select pin for SPI.  It is integral to the SPI peripheral in the chip.
That pin must be an OUTPUT for SPI to operate as master, or INPUT for it to operate as a slave.
It's a stupid design decision by Atmel if you ask me, but there you go.  So basically trying to use SPI at the same time as PWM on pin 10 is "undefined" and to be avoided.
Use a different pin for PWM or if you need more than there are PWM pins available then consider an external PWM control chip.

Just probing around to get more detail on exactly how it all works, this is what I have found:

digitalWrite() explicitly disables PWM on a pin.
The direction of pin 10 defines the SPI operation as master or slave.
analogWrite() sets pinMode(OUTPUT).
The SD library calls pinMode(OUTPUT) and digitalWrite(HIGH) on pin 10.

This means that:

SD.begin() will terminate any existing PWM on pin 10.
Using PWM on pin 10 will force the pin to output rendering SPI slave mode impossible

You should be able to use PWM on pin 10 if, and only if:

You use analogWrite() after using SD.begin(), and
You never want to use SPI slave mode.

I am not saying it's a stupid design decision on your part - I am saying it's a stupid design decision by Atmel by tying the SPI operation to the direction of a specific pin.

Sorry, my mistake

10 must be OUTPUT for SPI master. not important if LOW or HIGH or PWM. only problem is the SD library assuming other SPI device on pin 10

second upvote for an obviously wrong answer?

@Juraj What's wrong about it? The issue isn't HIGH or LOW - that is irrelevant. The issue is pin 10 is integral to SPI.

INPUT for master??? INPUT for slave.

@Juraj Simple typo. Pretty obvious I'd have thought. Not a reason for it to be "wong" - only a reason for you to point out the typo.

but then the rest doesn't make sense

Why do you say that?

PWM is OUTPUT. pin 10 can be used for PWM is Atmega is master

Ah, I see your confusion. PWM is not OUTPUT. It is PWM. It is not controlled by port registers. It comes from the timer.

analogWrite has pinMode OUTPUT

So? That doesn't mean anything.

the register is set, SPI is master

SS and OC1B are both alternate functions on the same pin. You can have one and only one selected at a time.

I interpret the datasheet and the comments in the library so that if SPI is master, SS is is gpio. only if it would become INPUT LOW the SPI would switch to slave. did you test it with PWM? I didn't see anywhere a note about pin 10 PWM conflict with SPI master

digitalWrite explicitly disables PWM on the pin. I will dig out one of my old Arduinos and experiment, see what the actual operation is.

@Juraj I have tested all the different permutations and found where it is and where it isn't possible to use PWM on pin 10.  I have updated my answer with more detail.

thank you. I just started connecting the SD card of the Ethernet shield to Nano :-)


text:
Using a DFRobot Voltage Divider
I'm reading on the DFRobot website to implement this Voltage divider: Analog Voltage Divider SKU: DFR0051
void setup()
{
  Serial.begin(9600);
}
void loop()
{
      float val;
      float temp;
      val=analogRead(2);//This divider module will divide the measured voltage by 5, the maximum voltage it can measure is 25V.
      temp= val/40.92;
      val=(float)temp;
      Serial.println(val);
      delay(1000);
}

Where does 40.92 come from? And even when printing only VAL it's something like 210 and I'm not sure what this is supposed to be. I don't get how to get the actual voltage of the battery etc. being measured? If it's divided by 5, why do you not multiply by 5 anywhere?

1023/25=40.92

How is this Uno code? An Uno has no SerialUSB.

Im using it on another board, sam thing. just replae SerialUSB with Serial....

Then why is it tagged [tag:arduino-uno]?

The unit measures a maximum voltage of 25v. When the measured voltage is 25v it divides it by 5 to present a maximum of 5v to the Arduino.  That is measured as a value of 1023 by analogRead(). If you divide 1023 by 40.92 you get 25.


text:
Using an Arduino for a Diorama Controller
Kind of new to the whole DIY electronics scene.
I'm building a diorama for my son.  It will include a length of track, a station, some other buildings, and scenery.  It will be HO scale.  The buildings came with these cool little LED lights and I've bought additional ones as well.  I want it to be of the period of the late 1800s to early 1900s.  So the additional LEDs I bought give off a more "yellow" light to simulate candle/lantern light.  The track is not a circuit and is not powered.  It is just "static" to sit a train so it appears to be at the station.
I have the following questions:

Could I hook up the LEDs to a Arduino and have the different buildings (or floors within a building) be controlled separately?
Could I make the LEDs "flicker" to simulate candle/lantern light?
Could I maybe hook up a little speaker inside the train station to give off train noises, whistles, conductor calls, etc?
Could this setup (Arduino with LEDs/speaker) be run off of batter power (not a custom battery, just off the shelf AAs, AAAs, or Cs, etc.)?
Is an Arduino instead the appropriate controller for this kind of project?

I think this is a great opportunity to teach my kids not only modeling but also electronics (myself as well on the electronics).
Thanks in advance for any help/suggestions.
EDIT:
A little more about the setup.  The LEDs are made specifically for this type of application (model buildings/railroads).  Hence, they already have an 1800 ohm resistor attached to the input side of the LED.  There will indeed be multiple LEDs per building (even per floor).  I would like to at least isolate the circuits by building and even better if I could isolate them by floor.  I think it would be cool to have the software cycle the buildings/floors on and off at different times.
A smaller form factor for the Arduino would be ideal as it will have to fit into one of the scale buildings.  I've never really worked with the Arduino so I don't know all my options.  I've done a little with the Raspberry Pi and originally posted this question there and was told the Raspberry Pi would be overkill for this type of application.

Yes, but use a compact one, like the Arduino Nano or Pro Mini. I'm not sure how many battery life you will get, but I can't think of anything more appropriate as Arduino.

Arduino itself doesn't really have good audio capabilities, but there is an "SD card audio mp3 shield" in adafruit, that can be triggered easily

The Arduino can safely output 20 mA per IO pin, so you may power about ten 1.8 kΩ LEDs per pin without a transistor. But beware of the 100 mA limit per pin group (two groups: pins 5 — 13, all other pins). The LEDs are likely to consume more power than, say, an Arduino Nano, so this will likely be the limiting factor for battery life.

Thanks everyone for all the great feedback.  I hope to provide a status to this post when I make some progress.  It could be a while though.  I got to build the actual building first.

@EdgarBonet Can you further explain what you mean by "pin group"?

See the datasheet of the ATmega328P, the small notes below table 30–1. Each one of these two groups can source up to 150 mA: (5 — 13), (0 – 4, A0 – A5). Each one of these three groups can sink up to 100 mA: (0 – 4), (5 – 13), (A0 – A5). The entire chip cannot source nor sink more than 200 mA (see Absolute Maximum Ratings).

First, since you didn't mention any kind of Arduino, my answer is based on using Arduino Uno/Nano (I think its the most common)
 1. Yes you can. You use 1 transistor per building as switch (if there are many LEDs in the building) to gives optimal current and prevent your Arduino pin. The value of R2 -- Rx is depend the LED colour. You can control each group with one Arduino pin.

simulate this circuit – Schematic created using CircuitLab

Yes you can, one in my mind is using PWM feature, like this project
Yes you can. But maybe the generated sound is not up to your expectation. Here is one of the simple example and this maybe a bit challenging.
The battery is up to your setup. More output (such as led and speaker) requires power source that can provide greater current. Arduino Uno voltage limit is 6v-20v
In my opinion, yes.

As for the form factor, I think Arduino Nano is small enough to hide in the building, while Arduino Uno size is just slightly less than a Raspberry Pi.
Good luck for your project :)

The Arduino Nano is essentially the same, but in another form factor, this this answer also applies for the Nano.

Please don't use a single resistor for multiple leds. One resistor for each led. For yellow leds you probably need a higher value resistor. Also R1 shouldn't be 100 Ohms, as that would result in 44mA of base-emitor current, which if a bit over the maximum rating of an Arduino pin. Use something like 1000 Ohm (i.e. 1 kOhm).

Thanks for this help everybody.  I failed to mention that the LEDs are specifically built for model buildings and they each have an 1800 ohm resistor already attached.  I'll update the original post.  This may change this answer a little.  But I like the info I'm getting so far.

@dhimaspw Thanks for the link to CircuitLab.  That's a pretty cool online application that I had no clue existed.

@Gerben thanks for the correction. Just asking, how if all the LED are the same colour? should it also use multiple resistor? *ps : I forget to edit the resistance value, but thanks.

@dhimaspw If the are all the same you might be able use a single resistor. But even then different batches of the same led could have slightly different forward voltages resulting in one led drawing more current than the other. This is more a problem if you trying to run the leds at their maximum. Also if one led fails the rest will have to handle the extra current and fail shortly after. Resistors are cheap. Just use one per led.

@Gerben Thanks for the info.  I updated my original post.  All the LEDs are the same color and they already come with an 1.8 KΩ resistor attached, so I think that aspect is taken care of.

The only point would be that all LED's would go on/off at the same time. It would be weird if all the candles on the station would be in sync :p But that would be an easy fix, but keep it in mind while building.


text:
How to create a heart rate detection system that uses a chest strap?
I want to create a system that uses a chest strap from available Bluetooth-based heart rate monitoring systems. The straps seem very convenient compared to available Arduino pulse detection systems that use electrode pads (which must be placed individually and that wear out), or infrared sensors, which are cumbersome.
I find the Bluetooth systems not super reliable and would like to use the strap with a wired Arduino based system. Is it possible and if so how?

You're asking how to create a wired connection to an unspecified device not designed for it. You'll at very least need to specify the device.

You'll need a data-sheet (or other spec) for the sensors in the particular strap, and from that, buld an interface to your Arduino. It will probably involve supplying power to the sensor, amplifying the sensor output, noise rejection (low-pass filtering might be enough), detecting the signal exceeding a threshold, and outputing a level or a pulse when it does.

I can manage detecting a pulse from a signal. The strap is from a Polar H7. The battery is a CR 2025 which is 3V. Can the Arduino 3.3V supply power to the sensor? How could the output be amplified and the noise reduced? Is this post, http://forum.arduino.cc/index.php?topic=317073.0, relevent?

I think that the correct answer is yes/no. Theoretically you can, if you have the appropriate knowledge. Dismantle the sensor, and probably you will find that there is a battery, a circuit and some wires going to some electrodes. Detach the wires from the circuit, and use them exactly like you would use some standard electrodes. But when I built a small ECG I bought the electrode pads because other materials have a very high contact resistance, and so I think that the main problem with your band is the electrodes (consequently even with an arduino you will get poor performances)


text:
Read all relay output (high or low) from Bluetooth through Android app
I have written the following code for Arduino:
#define relay2 2
#define relay3 3
#define relay4 4
#define relay5 5
#define relay6 6
#define relay7 7
#define relay8 8
#define relay9 9
byte val;
void setup() {
  Serial.begin(9600);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  pinMode(relay7, OUTPUT);
  pinMode(relay8, OUTPUT);
}

void loop() {
  int a = 0;
  if (Serial.available()) {
    val = Serial.read();
    Serial.println(int(val));
    //Display received value on Serial Monitor
    //ASCII VALUES
    if (int(val) == 49) //Turn Light1 ON 1
      digitalWrite(relay2, HIGH);
    else if (int(val) == 50) //Turn Light1 OFF 2
      digitalWrite(relay2, LOW);
    if (int(val) == 51) //Turn Light2 ON
      digitalWrite(relay3, HIGH);
    else if (int(val) == 52) //Turn Light2 OFF
      digitalWrite(relay3, LOW);
    if (int(val) == 53) //Turn Light3 ON
      digitalWrite(relay4, HIGH);
    else if (int(val) == 54) //Turn Light3 OFF
      digitalWrite(relay4, LOW);
    if (int(val) == 55) //Turn AC ON
      digitalWrite(relay5, HIGH);
    else if (int(val) == 56) //Turn AC OFF
      digitalWrite(relay5, LOW);
    if (int(val) == 57) //Lock the DOOR
      digitalWrite(relay6, HIGH);
    else if (int(val) == 48) //Unlock the DOOR
      digitalWrite(relay6, LOW);
  }
}

Now on the Android side I have written the following code:
 //Bluetooth connection code ....
  mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

  mmSocket.connect();
  mmOutputStream = mmSocket.getOutputStream();
  mmInputStream = mmSocket.getInputStream();

  int byteCount = mmInputStream.available();
  if (byteCount > 0) {
    byte[] rawBytes = new byte[byteCount];
    mmInputStream.read(rawBytes);
    String string = new String(rawBytes);
    Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
  }

Now it works perfectly when I press a button to turn the light on/off. But I want to read all relay current status (high/low) when a Bluetooth connection is made.
So basically after connecting to the Bluetooth module I want all relay status.
How can I do that?

It's rather undocumented, but you can actually use digitalRead(relay2); on a pin (ex relay2) that is set to OUTPUT. I discovered it accidentally, and it worked exactly as expected, so i looked it up and it's legit. This is very handy to check an output pin's hi/lo state from a non-connected part of the code.
There is a tiny performance dip compared to reading just a variable, but it usually won't be noticed. If you need top performance, wrap the digitalWrite() with your own function, and set a variable with the new state:
int myState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

void digitalWrite2(int pin, int value){
   myState[pin] = value; // copy setting to a global array
   digitalWrite(pin, value); // apply the setting as intended
}

Now, you can instantly get all the relay states from the myState array, provided they've been set with digitalWrite2. The other advantage to an array is that you can easily persist it to SPIFFs or EEPROM as-needed and recover the relay states on the next boot.

Changing the mode of the pins would be a pain, so you might be better to store the state of the relays within you Arduino code (a bool array) as long as you know what state they start in, then send the data back over the serial connection.
Define an array of pin numbers, an array of Boolean states and rework your code to change both arrays at the same time when a number comes in.

Hi , Can you please explain me in brief with some demo code or can you provide some reference link ? . I am new to arduino uno family. so i am learning step by step.


text:
PWM output while using I2C with the ATTiny library
I've noticed that when using the USI interface on the ATTiny to send I2C via the methods from "Wire.h" with the ATTiny Arduino implementation included from the library manager (ATTinyCore), while analogWrite PWM on PB4 (Arduino pin 4, physical pin 3) works OK, it seems attempting to use it on PB1 (Arduino pin 1, physical pin 6) behaves erratically or hangs the processor.
Is this expected behavior, and is there a workaround? With the SDA line on PWM pin 0, physical pin 5 if that's the case it means when using the hardware USI to do I2C communications, I'm down to a single hardware PWM output, which is kind of a bummer.

Just a suggestion (perhaps you have already done this), make sure you are using the most up to date support (software) for this processor.  I had loads of problems with an ARM core Arduino until I updated the supporting software for that processor.

@st2000 The version I have installed via the boards manager is 1.1.4, which is congruent with the latest release on the github page for the project as of August 2017, so likely no joy there. :(

The project also uses millis() which I believe does something with an interrupt on one of the two hardware timers, so I wonder if that might be part of the problem as well, though I was under the impression that firing a timer overflow interrupt wouldn't interfere with the PWM channels. I plan on breaking the situation down into bare-minimum sketches today to try and isolate the problem

This is normal.
Timer0 is used as the clock source for the USI. It's the only internal clock source that can be used. The only other option is to use "software polled" mode where it's up to the sketch (or support library) to manually create the clock signal (less than desirable) by setting a bit in a register at the right time.
So you can only use Timer1 for your own (PWM) purposes while using the USI.

In a situation where two Tiny devices were using i2c to communicate, and at least one of them required more than a single hardware PWM channel, would it be preferable to use software-polling on the slave and the USI on the master, or vice versa?

It only relates to master mode. In slave mode the clock is provided by the master, not Timer0. The slave can have all the PWM running.

Ah, I didn't know if in acting as a slave it also required it for some purpose, that works out fine then.

The only time you need a timer both ends of a connection is for an asynchronous protocol like UART.


text:
No ports available
Heyy everyone!!! I have just started working on arduino uno board and for the first week it was working fine but yesterday when I plugged in the usb cable the port option in IDE turned gray(showing no ports).
I tried to update drivers by following commands as given on  forum but arduino.inf file was not there under the drivers folder.
Also mega 16u2 ic on my board gets hot as soon as I connect it with usb . Tx and Rx LEDs are constantly glowing and 13 pin led  glows just for a short time then goes off.
It would be of great help if someone can solve my problem:)

Also mega 16u2 ic on my board gets hot as soon as I connect it with usb .

Your board is electrically damaged and must either be replaced or be repaired by someone able to change out one or more failed surface mount components.
The time of those able to do so is commercially priced above the value of this board, so generally it would only be repaired by someone able to do so themselves, where time spent on a hobby project doesn't necessarily have the same economic value as time spent on paying work.


text:
How can I use the NRF24L01 modules without a library?
The datasheet is too intimidating for me, and I dont want to use the libraries available. Hence, I am looking for some clarity on this matter.

You can use them as book marks.

You can use the NRF24L01 by writing the functionality that is currently within a library yourself (and strip of parts you do not use).
However, for this, you need to understand the library, and therefore high likely the datasheet too.
You also can start without looking at a library, but your only documentation source is the datasheet itself.
A NRF24L01 has a lot of possibilities (that is why the datasheet is so extensive), so writing the functionality yourself might be causing more time.

And given all the functionality to be implemented to do even basic stuff, they would probably still end up writing something that looks very much like a library.

Indeed I did. But it's opened up the module for me. I was just stuck on the SPI commands though. Specifically the SPI read operation. I just didn't look at the diagram.


text:
ATtiny85 with sleep and serial
I want to communicate over serial to another device (dfplayer) and also set the microcontroller into sleep mode.
The ATtiny85 does not have a hardware serial pin so I need to use a virtual serial (like SoftwareSerial.h)
I've googled a lot and tried a lot of things but it basically seems to come always to the same problem. SoftwareSerial (or NeoSWSerial) do not work with avr/sleep. Something to do with interrupts,

NeoSWSerial.cpp.o (symbol from plugin): In function NeoSWSerial::read()': (.text+0x0): multiple definition of __vector_2'
.pio\build\attiny85\src\main.cpp.o (symbol from plugin):(.text+0x0): first defined here

AltSoftSerial won't work because it requires a 16bit timer which the ATtiny does not have__
Is there anything I can do about this?

What I actually want to do
Connect 6 buttons with 6 different resistors to a single ADC pin of the controller. When a button is pressed wake up the device /if necessary), read the ADC value, pick a track based on that value and then play the track on the dfplayer.
After a while, if no button is pressed, put the dfplayer and the mcu to sleep. And that's why I need the mcu at all. You can't set the dfplayer to sleep or wake it up without serial

Update:
I confused SPI and Serial indeed. I need to use serial communication
I want to send and receive packages. Send: InitCommand, Receive: PlayerInitialized / InitializationFailed. And so on.Well it's some hex codes of course but you get the point I think
My flow should basiclly look like this:
boot/wakeup  // <-- this is where I need the interrupt, don't I?
read adc value
pick track number based on adc value
send PlayTrack command to DFPlayer
delay x ms
send Sleep command to DFPlayer
go back to sleep
But the issue is in the combination of the Sleep and SoftwareSerial library. It's not the interrupt that is an issue. At least not yet

You've mentioned SPI and ADC - where does serial come into this?

The DFPlayer uses Serial.  I'm not sure where SPI is coming into this.  Perhaps the poster is confused about what SPI is.

Are you getting stuff from dfplayer, or sending stuff to it? If you are sending it to the player, I don't see where the interrupts are needed.

@NickGammon I updated my post to answer your question. Thank you

@Delta_G I updated my post to clarify the situation. Thanks

SoftwareSerial takes over all of the PCINT interrupt vectors.  That's all the pin change interrupts.  Your sleep code is wanting to use one of those interrupt vectors as well, likely as a wake signal.  The answer is going to either be modifying SoftwareSerial to only use the one vector it needs in your particular case, or finding another soft serial library that doesn't take them all.  I don't know which library would fit that bill so I'll just leave this a comment and not an answer.  Perhaps if someone knows the right library here they can answer.

Thanks to @Delta_G I was able to figure out a solution.
I took the source files of the SoftwareSerial library from github and copied it to my project. I renamed it so it wont give any conflicts. I then continued to comment out the interrupts in the cpp file and took care of calling handle_interrupt from my program. I also had to remove the inline keyword from the handle_interrupt function
I've posted my modified files on github.

boot/wakeup // <-- this is where I need the interrupt, don't I?

Is the interrupt to detect that you have pressed one of the buttons? If you have that then you shouldn't need to use a timer to wake up.
If you connect your buttons with resistors in such a way that any button at all will send at least 0.6Vcc (ie. 3V upwards for a 5V system) then that could be configured to generate an interrupt (a rising interrupt). So you might set up the resistors so the buttons send 3.2V, 3.5V, 3.8V, 4.1V, 4.4V and 4.7V. That gives you six different voltages and they are all high enough to be considered "high" on a digital pin. Then make that pin generate the interrupt and also do the ADC reading on it once you wake up.
Then you can put the processor into a deep sleep until a button is pressed. While the track is playing you might also set up a watchdog timer interrupt so that you can wake up and check if it is time to put the player to sleep as well.


text:
How to properly read ADC on an ATtiny85?
What I want to do: attach six buttons to a single input. Each button triggers a different action.
How I want to do it: Use an AD conversion and add a resistor with different values to each button so that you can distinguish between the different input signals
I use these values: 1k, 4.7k, 18k, 22k, 55k, 300k
Vcc is stable 3.3v but I also tried it on 5v. I use Vcc as reference value for the ADC.
The problem I have: no matter what I do I always read the same value on the ADC. Connected to  GND it reads 0 and on Vcc it reads a value that’s always the same regardless what resistor I actually use.
I tried a lot of things I’ve found on the internet but nothing really worked for me. I’m clearly doing something wrong
This is the method I call in setup() to initialize the converter on ADC2(pb4)
void initADC()
{
  // 8-bit resolution
  // set ADLAR to 1 to enable the Left-shift result (only bits ADC9..ADC2 are available)
  // then, only reading ADCH is sufficient for 8-bit results (256 values)

  ADMUX =
            (1 << ADLAR) |     // left shift result
            (0 << REFS1) |     // Sets ref. voltage to VCC, bit 1
            (0 << REFS0) |     // Sets ref. voltage to VCC, bit 0
            (0 << MUX3)  |     // use ADC2 for input (PB4), MUX bit 3
            (0 << MUX2)  |     // use ADC2 for input (PB4), MUX bit 2
            (1 << MUX1)  |     // use ADC2 for input (PB4), MUX bit 1
            (0 << MUX0);       // use ADC2 for input (PB4), MUX bit 0

  ADCSRA =
            (1 << ADEN)  |     // Enable ADC
            (1 << ADPS2) |     // set prescaler to 64, bit 2
            (1 << ADPS1) |     // set prescaler to 64, bit 1
            (0 << ADPS0);      // set prescaler to 64, bit 0
}

The code is taken from here https://www.marcelpost.com/wiki/index.php/ATtiny85_ADC
The page seems to be down at the moment so here is an archived version of it
https://web.archive.org/web/20230128091128/https://www.marcelpost.com/wiki/index.php/ATtiny85_ADC
In the loop() method I do basically this: Read ADC and then blink an LED n times, based on the read value.
ADCSRA |= (1 << ADSC);         // start ADC measurement
while (ADCSRA & (1 << ADSC) ); // wait till conversion complete

uint8_t adcValue = ADCH;

if (adcValue >= 0 && adcValue < 32) {
  blink(1);
} else if (adcValue >= 32 && adcValue < 126) {
  blink(2);
} else if (adcValue >= 126 && adcValue < 193) {
  blink(3);
} else if (adcValue >= 193 && adcValue < 227) {
  blink(4);
} else if (adcValue >= 227 && adcValue < 245) {
  blink(5);
} else if (adcValue >= 245 && adcValue <= 255) {
  blink(6);
}
delay(60000);

My breadboard has the resistors going from Vcc to an empty row and I connect a jumperwire from PB4 to one of these resistors and do an external reset of the microcontroller to test my setup. They share GND/Vcc
What am I doing wrong? What can I do to debug this?
Thanks

you forgot to connect a resistor between analog input and ground ... research voltage divider

Are you using an Arduino core which does not support analogRead() or is there another reason why you are directly reading ADC registers ? The ADC is 10bit  so can read analog values up to 1023. Does your application allow for pressing two or more buttons simultaneously? If you have a multimeter you could check the voltage between the analog pin and ground when a button is pressed.

Funnily enough, someone else also wanted to connect six buttons to an ATtiny85 to "Connect 6 buttons with 6 different resistors to a single ADC pin of the controller". It's an amazing coincidence!

@NickGammon I unfortunately can’t tell if you’re trying to be funny or sarcastic. It’s the same project but a different question.

Adding a schematic to your question, showing at least everything connected to the A/D pin, would help!

"I unfortunately can’t tell if you’re trying to be funny or sarcastic . . . ". This does not help. Please focus your efforts on providing responses to the followup questions you have been asked and are, as yet, unanswered. It is, incidentally, in the nature of school assignments that multiple instances of the same question can appear in various guises.

@6v6gt It wasn't my intention to be sassy. I was just confused by nicks comment so I tried to explain me

there is no schematic diagram in the question ... it is impossible to determine how the OP connected everything ... voting to close for being unclear

TBH I was indeed wondering if it was an assignment. Also maybe the previous question about the same thing may have helped, so it was a pointer to check it out.

@NickGammon I guess this is going too far here but it's meant to become a toy for my daughter. Not an assignment

OK, sorry for doubting you.

Unfortunately @jsotola only posted their solution as a comment. But it was the correct answer. So I'll just post my solution here
I now use a voltage divider setup with these values:
Voltage divider formula Vs * R2 / (R1 + R2)
Vs: 3.3v
R2: 100k Ohm
R1: 10k (3.0v), 27k (2.8v), 38k (2.6v), 50k (2.2v), 65k (2.0v)
Using an 8-bit ADC, I came up with these if statements to distinguish between the inputs. I gave it some room for deviation
if (adcValue >= 227 && adcValue <= 237)
{
  // 10k ohm (3.0V -> adc 232)
}
else if (adcValue >= 212 && adcValue <= 223)
{
  // 18k ohm (2.8V -> adc 217)
}
else if (adcValue >= 196 && adcValue <= 206)
{
  // 27k ohm (2.6V -> adc 201)
}
else if (adcValue >= 181 && adcValue <= 191)
{
  // 38k ohm (2.4V -> adc 186)
}
else if (adcValue >= 165 && adcValue <= 175)
{
  // 50k ohm (2.2V -> adc 170)
}
else if (adcValue >= 150 && adcValue <= 160)
{
  // 65k ohm (2.0V -> adc 155)
}

Here is a picture of my breadboard. I know it's not a real schematic but I couldn't figure that out right now. But I hope it's good enough

a comment is the only thing that was appropriate ... only a guess could be provided because of lack of information in the question

I don't see six buttons here. Is this a work in progress?

@NickGammon I just inserted different resistors to test each of them one by one. That was easier than setting up 6 buttons and was good enough. Just needed to know if it works in general

There seem to be some gaps in your ranges. For example, what if adcValue is 238? But perhaps that is deliberate. You could probably rewrite as only doing greater-than tests. For example, >= 227, then if it fails that, >= 212 and so on. Testing the other limit seems redundant.

It is not clear if it matters in this use case but a 65k resistor in parallel with a 50k resistor is effectively a 28.2k resistor. This is very close, allowing for tolerances, to the 27k resistor you are also using meaning that it could be difficult to distinguish between a single button press and at least some combinations of multiple button presses.


text:
Beginners code, loop doesn't detect unplugged pin
I'm learning on an Arduno UNO board, and im trying to turn a LED on three times when I connect pin 10 to ground and then turn it off. Then when I unplug the pin number 10 it should NOT blink again... yet it does and I can't find the issue.
this is the entire code:
bool ledBlinked = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(7, OUTPUT);
  pinMode(10, INPUT_PULLUP);
}

//Turns on and off a digital pin, a number of times, with a certain delay
void blinkLed(int pin, int times, int del){
  // activates a pin a number of times
  for (int i=0; i<=times; i++){
    digitalWrite(pin, HIGH);
    delay(del);
    digitalWrite(pin, LOW);
    delay(del);
  }
}

//Checks if passed pin number is connected to ground
bool pinIsGround(int pin){
  return (digitalRead(10) == LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(pinIsGround(10) && !ledBlinked){ //if pin is connected to ground and the LED hasn't blinked
    blinkLed(7,3, 100); //blink pin 7, 3 times, with a delay of 100ms
    ledBlinked = true; //LED has blinked already
  }
  if (!pinIsGround(10) && ledBlinked){ //if pin is not connected to ground and the LED hasn blinked
    digitalWrite(7, LOW); //turn LED off (unnecesary?)
    ledBlinked = false; //LED hasn't blinked yet
  }

}

if pinIsGround() returns false, and ledBlinked is false,   then (false && false) is true

Not sure what the use of the ledBlinked bool is,   but i think you should just use an else branch

google switch bounce

@ChadG : DO not confuse new student with bad logic. you are mixing it up with double negation.
If first operation of && returns false then the second is newer checked, but hole statement is false

SInce I can coment I have to write this as answer.
there are two ways of understanding your question:
If you dont want it to ever blink again then simply remove
ledBlinked = false;
If you are trying to prevent the blinking until the button is depressed and pressed again then first think I see is the error in blinkLed function as
for (int i=0; i<=times; i++) would run times+one time. because it runs first with value of i being 0 (Eg times=4 would run for i equal 0,1,2,3,4 -> Five times ) So correction to for (int i=0; i<times; i++) would run correct number of times (Eg times=4 would run for i equal 0,1,2,3 -> four times )
Although as you are not checking status during the running of blinkLed function for the status of the button, if you release it while blink is running the script would not notice unless its still unpressed when script gets back to Loop.

Although since hardware operation take more work then logical operation I would recommend if...else statement rather then multiple hardware operations. Although they make code simpler to read
if(digitalRead(10) == LOW){
         if(ledBlinked != true)...
   } else { ...}

I have intentionally avoided writing full code as that would kill the point of you learning


text:
Memory chip for arduino
I know that you can't expand your ram because it is intern. But I want a extern memory chip (1024KBytes) that is very fast. I know that I need a library to access information on this chip. And functions to read and write data. A shield or breakout board it doesn't matter, and I want that it is compatible with Arduino mega. If the arduino lost power it doesn't matter if I lost the data. It must hold the data when the arduino is powerd.

512mb seems quite unreasonably large for an 8-bit microcontroller. In order to get a better answer, could you explain why you need 512megabits of RAM on a chip that comes with 8kilobytes of SRAM onboard?

I've seen a lot of memory sizes, but I've never encountered a 0.5 bit memory cell. On a more serious note though, assuming you mean 512Mb, that's a ridiculous amount of memory. It would take you tens of minutes to fill up, and processing all that data would take ages. This sounds like an XY-problem.

SPI RAM chips of sizes up to 128 kilobytes seem to be more realistic for you. If you really want megabytes, get a microcomputer (Rasbpi, ..) http://www.microchip.com/design-centers/memory/serial-sram-serial-nvsram

Do you mean 512Mb (Megabit) or 512MB (Megabyte)? The sizes are VERY different.

Sorry, I mean 512 KBytes or 1024KBytes. And that is not true about it is not processable. A SD card is also processable with a capacity of 4GBytes

The point is, that the Arduino would take very long to fill up the space due to it's own speed and the speed of the connection, so it might not be reasonable, to get such high capacity. SD cards for Arduinos are mostly used, because with a simple FAT implementation you can easily copy the saved data to a PC.

Could you tell us what you need it for?  There may be a more appropriate solution than adding RAM.

You can quite easily connect multiple 128kB SPI ram chips to an Arduino. 4 of them together would give you 512kB of extra SPI-connected SRAM.
Access isn't super fast.
Another option is to use a parallel 8-bit SRAM chip. These take a lot more wiring since you need 8 wires for the data, log2(n) wires for the address, plus a couple of control wires (OE, WE, etc). But if you wire it making use of entire IO ports you can get much faster access times.  Also, these come in larger capacities than the SPI SRAM chips.
There is also PSRAM available in even bigger capacities. The same interface as SRAM but it's actually DRAM. The "P" stands for "Pseudo". You can get these in megabyte capacities, although they are usually in a BGA footprint, so you'd need to find one on a breakout board.


text:
How to convert 0-5v inverted serial to 0-3.3v non-inverted serial
This weather stations has a 0-5v serial output.  I'm trying to read the serial output with the Adafruit 32u4 feather board and I get nonsense data out of it.  When I hook the Ultimeter up to my serial->usb cable I get the normal data output.  When I hook up the Ultimeter to a 5v arduino via SoftwareSerial in inverted mode I get proper data.  But I need to connect this weather station to a 3.3v Feather board's hardware uart which doesn't seem to be able to operate in inverted mode.  Is there a 5v -> 3.3 level converter that also will invert the serial signal ?

Please add more information to your question about the used weather station and feather board. Specifications, brand, type, links. Does that weather have a rs232 output? and the arduino is a 3.3v atmega32u4 running at 8mhz and costs 45 dollars? You need to convert the rs232 to ttl-level. The feather board might be damaged by the rs232.

I have determined that the serial output of the weather station is inverted 5v ttl.  I can get the proper data using software serial inversion.
The 5v output may be too much for the 3.3v TTL but the hardware uart doesn't seem to be damaged at this point although I can't seem to get software serial to work on the Feather board.

The rs232 can be a signal from -12v to +12v, but some devices use -5v to +5v and there are also some devices that are not very compatible that use 0v to +5v. You should use a rs232 to ttl-level converter. For a test use at least a protection resistor to the arduino. For example 4k7 or 10k. The arduino serial is idle high and the rs232 is idle -12v. It is indeed inverted as you already noticed. You can try a transistor to invert the signal. There is no need to use SoftwareSerial. The SoftwareSerial has limitations for the atmega32u4/Leonardo https://www.arduino.cc/en/Reference/SoftwareSerial

I think you're looking for an inverting amplifier. This can be done with either a BJT or a MOSFET (assuming your input is enough to turn the MOSFET on). Here's an example with a BJT:

simulate this circuit – Schematic created using CircuitLab
The output range is independent of the input and is defined by the supply voltage.

Base > Collector is not good ,for NPN transistor.
Because "Base -> collecter" is PN.
So use LM393 for level convert.
LM393 is open collecter.

I ended up using a simple voltage divider to reduce the 5v to 3v and used SoftwareSerial to read the inverted serial. Thanks everyone.


text:
Arduino Nano 33 IOT - Bluetooth Classic (Serial)
I've an arduino nano 33 iot and I'm working with the first time with bluetooth.
So far BLE is working fine, I can use an app on my smartphone to check the services and characteristics.
Is it possible to send data over serial via Bluetooth on this board ?

This board has multiple processors on it.  The main processor (SAMD) rus your arduino code.  There is also an ESP32 based processor which runs the WIFI and the Bluetooth.  There is a pretty featured library for controlling the WIFI called WIFININA.  This library does NOT have any bluetooth functions though.  Therefore, until someone writes a library which lets you control the bluetooth functions of that ESP32 chip, I don't think you'll be able to send arbitrary serial data via bluetooth.  It is "possible" to do this but not without a lot of technical wizardry.
Here are some links to examples of what the code might look like if you were writing code directly to the ESP32 chip here https://github.com/espressif/arduino-esp32/blob/master/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino

Thanks for the reply!
So for the moment I'll continue with BLE as I've not the skills or time to write such a library!
Or use another bluetooth board/extension board.

Just FYI, BLE stands for Bluetooth Low Energy so it is itself also Bluetooth.

Yes I know. But you there is a difference in communication between Bluetooth "classic" and low energy is it correct ?
Like Serial over low energy is not possible ?


text:
Using Library LoRa.h with Wemos D1 R2 for Lora Shield
I have been using Lora Shield for communication between server and multiple sensor with arduino . But recently i must save data received to Cloud . So i choose Wemos D1 R2 that have similar board with arduino . But when i upload example code , LoraReceiver can'nt get data . Can Anyone Solve my problem ?

we have no idea what equipment you are using, how it is connected, what program you are running and what errors you get ... do you think that we can answer your question?

When you change boards you must also update your pin connections in software.  When you initialize the Lora Shield, you probably specify a few data pins.  Those pin numbers cannot be assumed to remain the same on the new ESP8266 based board.  Furthermore, the ESP8266 board is 3.3v logic while Arduinos are 5v logic so you must ensure that the shield and sensors will also work with 3.3v.