text:
How to get the esp32s2 recognized as USB device?
I have an esp32-S2 saola and I am trying to use it as a MIDI usb device. I am trying to use this github repository: https://github.com/chegewara/EspTinyUSB. I am able to run the code on the esp32s2 saola and I am connecting to a mac with a USB cable to pins 19 and 20 but don't get any MIDI input in my computer (mac), in fact my computer is not recognizing the device.
So I guess my actual question is about how to get the esp32s2 recognized as a USB device by the mac. Any clues of what might be happening? Or should connecting  to pins 19 and 20 be enough and I am dealing with a hardware bug?
For the usb cable I took a usb only-power cable apart and then rewired it so it was only data (two middle cables connected to pins 19 and 20). As it was not working I then connected also the usb's power and ground cables with no luck:

EDIT: This the documentation for the USB driver on the esp32-S2 and why I think the power cables might not be needed at all (which I tried but didn't work): https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/peripherals/usb.html

Pretty grizzly looking.  I'm not really following the whole scheme.  It would be helpful to see everything a diagram.  As is, I'm only guessing you swapped the power for data on both sides of the cable.  That you actually have a ground back to the USB port etc.  You are not seeing anything like an overcurrent event on the USB host?

On the other side of the cable (not shown in the picture) I removed a micro usb male header and ended up with bare cable going to pins 19 and 20 as per the diagram I found in the documentation: https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/peripherals/usb.html

This goes back to what I said above.  "That you actually have a ground back to the USB port etc."  Circuits work better when they're.... circuits.


text:
Deep sleep hangs when used with D0 pin when we connect to reset pin in nodemcu
I am using a nodemcu and running a code using hall effect sensor and ultrasonic sensor with deep sleep except the deep sleep keeps hanging when I use this code. With code taken from online it does not hang. What is wrong with my code Please help me!
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define sleepInterval 30 // 6 minutes

// Update these with values suitable for your network.

const char* ssid = "Thief_3h";
const char* password = "lan";
const char* mqtt_server = "ipaddress";
const char* mqtt_topic = "sensors/test/";
const int trigPin = 2;  //D4
const int echoPin = 0;  //D3
long duration;
float distance_cm;
const int hallSensorPin = 14;                      // connect the hall effect sensor on pin 2
const unsigned long sampleTime = 1000;
float radius = 10;
float velocity;
float rdepth = 5;
float cm;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[75];
int value = 0;
int rpm;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("/test/river/rpm", "starting");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void ultra(){
  delay(2000);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
   // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  //cm = microsecondsToCentimeters(duration);
  distance_cm = ( duration / 29 ) / 2;rdepth;
}

int getRPM()
{
  int count = 0;
  boolean countFlag = LOW;
  unsigned long currentTime = 0;
  unsigned long startTime = millis();
  while (currentTime <= sampleTime)
  {
    if (digitalRead(hallSensorPin) == HIGH)
    {
      countFlag = HIGH;
    }
    if (digitalRead(hallSensorPin) == LOW && countFlag == HIGH)
    {
      count++;
      countFlag=LOW;
    }
    currentTime = millis() - startTime;
  }
  int countRpm = int(60000/float(sampleTime))*count;
  return countRpm;
}

void goToSleep() {
  ESP.deepSleep(1000000 * sleepInterval);
}

void setup(){
  pinMode(hallSensorPin,INPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  //pinMode(D0, WAKEUP_PULLUP);
  delay(1000);
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  delay(100);
   rpm = getRPM();
  velocity = (rpm * 2 * 3.14 * radius)/60;
  ultra();
  delay(1000);
  senddata();
  delay(1000);
  goToSleep();

}

void senddata(){

distance_cm = ( duration / 29 ) / 2;rdepth;

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;

    snprintf (msg, 75, "Velocity:%6.2f Depth:%.2f", velocity, distance_cm);
    Serial.print("Publish message: ");
    Serial.println(msg);

    client.publish(mqtt_topic, msg);
  }
    Serial.print("RPM:");
  Serial.println(rpm);
  Serial.print("Velocity:");
  Serial.println(velocity);
  Serial.print("depth:");
  Serial.println(distance_cm);

}

void loop(){}

"With code taken from online it does not hang" With what code taken from online?

Move client.loop(); into the loop(), if your esp going to sleep for 6 minutes, you may also want to #define MQTT_KEEP_ALIVE 300. If you are expecting data to be received before go to sleep, then move ESP.deepSleep(1000000 * sleepInterval); into the end of the callback function.

source: Stack Exchange

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

sort: votes


text:
Arduino Yun not getting response from Azure API
I posted this on StackOverflow but figured I'd post it here too. Sorry in advance if thats not allowed.
I'm trying to get my Arduino Yun to talk to an API that I'm hosting on Azure. I would like to do more complex things in the future, but at the moment I'm just trying to make a GET request over wifi with a single integer as a parameter.
I'm basically just using the example found here with the url changed. The example works fine, so as far as I'm aware the issue isn't with my board, its with the interaction with Azure.
HttpClient.get() returns an int as a response (not the regular HTTP response codes, its unique for the library). I got 60 initially, and changing my API to accept http calls (instead of just https) fixed this and made me get a response of 0 instead. 0 is the same response that I get from the working Arduino example, but for some reason I'm not actually getting anything in the body of my response, as the client.available() loop is never entered.
The API works as intended when I go to the url in chrome, so the issue arises somewhere due to how the arduino and azure talk to each other, but I don't know enough about either to figure it out and nowhere that I look seems to point me in the right direction.
Any help would be greatly appreciated, thanks.

Found the problem, even though I set azure to accept http requests, it was still redirecting to https which the arduino couldn't handle. I've written a python script to offload the requests to the linux processor, and now it works.

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


text:
Can't Turn Off Internal I2C Pull-Ups on ESP32
I've designed a custom ESP32 board around the WROVER-IE module. To keep power low, I'm using a GPIO-controlled high-side FET to turn off unused peripherals when in deep sleep mode.
The issue: I've pulled up an SSD1306 I2C OLED to this AUX rail. It works great when the device is awake. On setup() I start the OLED via ssd1306.begin() and from that point on, the SCL and SDA pins (22, 21) are always tied to 3.3V until I reset the ESP32.
The I2C bus always being tied to 3.3 ends up bleeding through the pull-up resistors and into the AUX rail, resulting unwanted current draw when in sleep mode.
Is there any way to turn off the internal I2C pullups on the ESP32?
Things I've tried so far:

Setting SDA, SCL as OUTPUT and writing LOW (does not work)
Setting SDA, SCL as INPUT and/or writing LOW (does nothing)
Calling gpio_hold_dis(gpio_num_t(SDA));(does nothing)

I'm now trying to dissect the esp32-hal-i2c.c lib but am not finding any fixes. Any help is greatly appreciated!
Edit, added diagram:

-N

"The I2C bus always being tied to 3.3 ends up bleeding through the pull-up resistors" - how do you know that? The pullups don't consume any power as long as you don't communicate on the bus.

If I remove the OLED display, the AUX voltage on the AUX rail dissipates. I will create a digram

I have solved this problem. For anyone who would like to turn off the internal pullups on the I2C bus of the ESP32, you need to disable the entire driver before putting the device to sleep.
First, include the peripheral driver library from the IDF:
#include "driver/periph_ctrl.h"

Next, call the following before sleep:
rtc_gpio_isolate(gpio_num_t(SDA));
rtc_gpio_isolate(gpio_num_t(SCL));
periph_module_disable(PERIPH_I2C0_MODULE);
digitalWrite(SDA, 0);
digitalWrite(SCL, 0);

This will stop the ESP32 from pulling up pins 21 and 22 while in deep sleep. Calling display.begin() or wire.begin() will restartthe driver upon wake.


text:
I can't turn on the motor by Arduino IoT Cloud
I'm trying to turn ON/OFF a DC motor from Arduino Iot Cloud. I have to turn it ON/OFF physically and through the cloud, physically it works well but from the cloud it does nothing. I'm using an Arduino MKR WiFi 1010, a L298N Dual full bridge,9V DC motor and a push buttom. Mi circuit is like this
My code is this
#include "thingProperties.h"
#include <FTDebouncer.h>

#define MOTOR_PIN 2
#define BUTTON_PIN 5

FTDebouncer buttons;

void setup() {
  pinMode(MOTOR_PIN, OUTPUT);
  buttons.addPin(BUTTON_PIN, LOW);
  buttons.init();

  setDebugMessageLevel(2);
  Serial.begin(9600);
  delay(1500);
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
}

void loop() {
  buttons.update();
  ArduinoCloud.update();
  onMotorChange();
}

void onPinActivated(int pinNr) {
  // do something according to the _pinNR that is triggered. For instance:
  Serial.println(pinNr);
  toggle = !toggle;
}

void onPinDeactivated(int pinNr) {
  // do something according to the _pinNR that is triggered. For instance:
  Serial.println(pinNr);
}
void onMotorChange() {
  digitalWrite(MOTOR_PIN, toggle || motor);
  Serial.print("The motor is ");
  if (toggle) {
    Serial.println("ON");
  }
}

I tried with a LED and it worked very well, but with the motor doesn't.
This is the code that Arduino creates when I add things to the board, the part of

thingProperties.h

// Code generated by Arduino IoT Cloud, DO NOT EDIT.
#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>

// x-ed id
const char THING_ID[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or
use as
key for WEP)

void onMotorChange();

bool toggle;
bool motor;

void initProperties(){

ArduinoCloud.setThingId(THING_ID);
ArduinoCloud.addProperty(toggle, READ, ON_CHANGE, NULL);
ArduinoCloud.addProperty(motor, READWRITE, ON_CHANGE, onMotorChange);

}

WiFiConnectionHandler ArduinoIoTPreferredConnection(SSID, PASS);

Thanks for the help and suggestions. How should I connect the motor or what do I have to change in the code?

You have connected the button direct to the driver board: When you press the button, the Arduino is not involved. It recognizes the button press but its reaction doesnt matter. You can not say your button works with the Arduino program. You defined the motor output signal to pin 2 but you used pin 3 to connect it to the motor driver. You used different inputs on the driver (for the arduino signat and the button signal). It is possible that the other input is for a second motor. And finnally your program has  logic that make no sense; I doubt it compile at all. e.g. where is toggle declared?

@PeterPaulKiefer it might be declared in thingProperties.h, but that's unclear.

@PythonSchlange Yes that's possible. The OP is welcome to clearify that. Although toggle is a very generic name for a variable that is declared in a header file. And e.g. ArduinoCloud.update() could play a serious role. But I have no access to it. As far as I know the program, it makes no sense to me.

@PeterPaulKiefer I totally agree with you. Please upload the header file too.

@PeterPaulKiefer I was wrong making the diagram, just that. Toggle was declared in 'thingProperties.h', when you add your thing, the cloud generates a code

As you schematics do eventually not fit to the reallity, I can only argue with the code. First I've x-ed the ThingsId, it should not be published. ;-) There are so many things I see that's it's not easy to explain them shortly. "The code is the truth", so I wrote an answer with an commented sketch.

The following code is an example. As I don't know the Arduino Cloud Thing configuration, and I don't have access to the cloud and the Hardware, the
programm is just a guess making some commented assumptions.
There are many assuptions I made, and I can not rely on the schematics you showed me. Eventually you have to redesign the circuit/hardware setup. A L298N is a so called H-Bridge. That needs at least two control pins in1 and in2 connected to arduino outputs to define the direction of the motor. You only connected one of them to an output of the arduino. And one of them to the button and an input of the arduino. (If that part of the schematics is correct.)
If you press the button in1 gets HIGH but the in2 may also get HIGH because your program switches the motor pin to HIGH. That turns the motor off. If one pin is HIGH the other must be LOW to drive the motor. Some L298N modules also need a PWM signal at the enA pin. That sets the speed of the motor with the duty cycle of the PWA signal. Most modules have a pullup at enA and enB so per default the motors are configured for full speed.
#include "thingProperties.h"
#include <FTDebouncer.h>

#define MOTOR_PIN 2
#define BUTTON_PIN 5

FTDebouncer buttons;

void setup()
{
  pinMode(MOTOR_PIN, OUTPUT);

  // !!! PPK: Handler methods added
  buttons.addPin(BUTTON_PIN, LOW, onPinActivated, onPinDeactivated);

  buttons.init();

  setDebugMessageLevel(2);
  Serial.begin(9600);
  delay(1500);
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
}

void loop()
{
  buttons.update();
  ArduinoCloud.update();
}

void onPinActivated(int pinNr)
{
  if ( pinNr == BUTTON_PIN )
  {
     toggle = !toggle;
     // this assumes that the toggle triggers a change for
     // the motor variable in arduino cloud. If not,
     // the motor variable will not be changed and my code does not work.
     // uncommenting the following line may help, in that case
     // motor = toggle;
  }
}

void onPinDeactivated(int pinNr)
{
  // Intentionally left empty, we only react to the rising edge.
}

void onMotorChange()
{
  digitalWrite( MOTOR_PIN, motor );
  Serial.print("The motor is ");
  if ( motor )
  {
    Serial.println("ON");
  }
  else
  {
    Serial.println("OFF");
  }
}

This line  // !!! PPK: Handler methods added
buttons.addPin(BUTTON_PIN, LOW, onPinActivated, onPinDeactivated);  (?) I can't compile with this and I can't edit "thingProperties.h". BUTTON_PIN is the pin for toggle that is a bool thing as the motor, just to turn ON/OFF (I follow an example in Arduino project hub)


text:
Touch sensor trouble
I need help I use Touch Sensor(T)v.0 and it always receives a signal not matter I touched it or not.
Here is the code.
#define TOUCH_PIN 7
int touchVal = 0;

void setup() {
   Serial.begin(115200);
   pinMode(TOUCH_PIN, INPUT);
}

void loop() {
   touchVal = digitalRead(TOUCH_PIN);
   Serial.println(touchVal);
   delay(200);
}

What touch sensor do you have? Please provide a link to the datasheet or to the product page at your reseller. How did you connect it? Is it active HIGH or active LOW? (meaning if touching it makes the output HIGH or LOW, both is possible)

https://aliexpress.ru/item/32800470168.html?&sku_id=64142657896

Honestly, I don't  know it's active HIGH or active LOW but it doesn't chengs value when I touched it always print 1

how do you know that the output is digital ?

why does your code not look for a change in the output?

I just want understand does my sensor work or not that's why I haven't output. In this line, I just print the value. Serial.println(touchVal);


text:
Arduino Mega Clone CH340G Capacitor Values
I'm making my own Arduino Mega board with ATmega2560-16AU and CH340G. Jump to the end of the post to find the real question.
I have already ordered a PCB before and it didn't work when I soldered everything in place. I have already asked why that board didn't work on another post here: Programming custom Arduino Mega with Arduino Uno
But I was not satisfied with the answers and started suspecting whether or not the capacitor values were right on my board.
I'm trying to make my own version of RobotDyn's Arduino Mega 2560 Pro so I tried taking the already programmed ch340g and soldering it on my own board and still failed. When I put a previously not programmed ch340g on the RobotDyn board and programmed it using Arduino UNO (Arduino as ISP) the board would work.
So now I ordered a new PCB but haven't ordered any of the passive components yet.
If any of you could tell me where I could find the values from the schematic below I would really appreciate that.
https://robotdyn.com/pub/media/0G-00005641==MEGA-PRO-CH340GATmega2560/DOCS/Schematic==0G-00005641==MEGA-PRO-CH340GATmega2560.pdf

Most capacitors are decoupling capacitors, so 100nF. C1 is from the original Arduino schematic - also 100nF. As is C12. All the others depend on the components they are supporting - the load capacitance of the crystals, the required input and output capacitance for the voltage regulators, etc.

Just a dumb question, the processor chip is programmed with the bootloader?

@Majenko Oh yeah sorry forgot to tell about the regulators, I don't need the values for that but I believe I'm having trouble with CH340G capacitors.

@Dorian Uhhh.. yeah. I want to be able to program my Arduino via USB so I have CH340G there to translate the program to the MCU.

C3/4 are dependent on whatever crystal you're using. C2 is for the internal 3.3V regulator in the Ch340G. No idea what it needs, but probably 1uF is more than adequate.

The values can be easy found for generic CH340g and ATmega2560 implementations:
C1,C2 = 100nF, C3,C4 = 22pf but depends on the crystal you use, all others excepting C12 are decoupling capacitors.
C12 has no sense where it's placed, it seems that the schematic is a bad combination of schematics, this capacitor should reset the board at power on but it breaks the reset pulse from CH340g so you cannot program the board without pressing manually the reset pushbutton. Don't place C12 at all.
Also place a short instead of R5 and R6 that are not in the CH340g manual (there is a special mention to connect the pins straight to USB bus), remove R8, is not needed for the same reason, R3 makes no sense, don't place-it.
R2,R4 = 1K, R7,R9 = 10K, R10,R11,R12,R13 = 1K, R14 = 10K , R15 = 1M.
Y1 = 12Mhz, Y2 = 16Mhz
A 22 ohm resistor is missing in your schematic between Y2 XTAL1 and ATMEGA XTAL2 but I don't think it's important.
I hope I didn't missed something
The bare minimum is to remove c12 and maybe R3 and check the values you used for R2, R4 against the above values.
If something would be wrong with CH340g the USB connection would fail but I see no mention about that in your post.

"C4 has no sense where it's placed".  I'm guessing you didn't mean C4 there, because you mention C4 above that point.  So, perhaps C5?.  But it is connected to AREF (for decoupling) rather than RESET.  Anyway, something for you to check.

@timemage you're right, sorry, it's C12. Fixed.

I think the  "all others excepting C4" may be caught up in that as well.  Referring to C12 as well?  Regarding C12, you can see it represented in AVR042 figure 3-1, along with the reason for it a few paragraphs above.  That said, it's probably not needed here.

@timemage Yes, missed that to. Yes, it's a combination of some schematics,  in the AVR042 the reset line is not driven by another chip. The spike through C1 that should reset the chip to enter in botloader mode when programming is filtered by C12 and the programming fails.

Scratching my above comment.  You're right, it likely is counter-productive to have it there.  Before, I'd throught the pulse might make it through okay.  But, assuming two caps around equal value, the pulse will stop quite short of being adequate for reset.

@timemage  Not only short  but also half size because the pulse voltage will be divided between capacitors. At best would be 2.5V. As I know the Reset input has histeresis and needs more than half VDD to activate.

We're in violent agreement.


text:
Does HC-05 module buffers the data received?
I am using HC-05 bluetooth module for sending large data(80-100KByte) from my phone to arduino-uno.
I had found that this module has a flash chip of 8Mbit  (SST39VF800A) but the datasheet of HC-05 has nothing about buffering of the data to be transmitted or data received.
I need clarity about the buffering of data so that I can change the data rate from the phone for better communication.

Mhh, interesting question. As bluetooth itself is packaged, I think the module needs to at least buffer a few packages. This answer states, that maximum package size could be around 1KB. But to be sure, one would to read the firmware code or ask the one, who wrote that. I'm not sure, if that firmware is opensource.

I didn't find any help in any data-sheets I could find, either. So I'd suggest a simple experiment, sending increasingly large packets before the other side attempts to read anything, until some data goes missing. The packets don't even need to be very sophisticated if all you want to know is whether N_received == N_sent and for what maximum 'N'.
Update:

All bytes were received correctly if there is no delay but with
increasing delay in reading from HC-05 data was not fully received and
with delay greater than 800ms only 63Bytes were received.

If you're collecting data as it arrives, then you can't measure the buffering. When you wait until all data has been set before you try to read any, the number of bytes you receive is the buffer size. It sounds like a 63 byte buffer, probably only what the HC-05's hardware UART can buffer, without using any of its memory to increase that.

I did the experiment by sending 100B and 1000B of data separately which took 4ms and 70ms respectively. All bytes were received correctly if there is no delay but with increasing delay in reading from HC-05 data was not fully received and with delay greater than 800ms only 63Bytes were received.

I think the buffer is FIFO since the data received were FIRST 63 bytes.


text:
Arduino while loop with or condition
How do I write a program to wait (delay) until one out of two buttons pressed? I have written a program to wait until a single button is pressed. It's working fine. However, if I extend it to second button it's not working. Pls help on this.

while (digitalRead(bt_Select) == HIGH) {} -- working.
while (digitalRead(bt_Select) == HIGH || digitalRead(bt_Reject) == HIGH) {} -- Not working.

Complete code:
const int bt_Select = 2;
const int bt_Reject = 3;

void setup() {
  Serial.begin(9600);
  pinMode(bt_Select, INPUT_PULLUP);
  pinMode(bt_Reject, INPUT_PULLUP);
}

void loop() {
  Serial.println("Pl input:");

  while (digitalRead(bt_Select) == HIGH {} // This is the line I change

  if (digitalRead(bt_Select) == LOW) {
    Serial.println("Select Button pressed:");
    delay(250);
    Serial.println("");
  }

  if (digitalRead(bt_Reject) == LOW) {
    Serial.println("Reject Button pressed:");
    delay(250);
    Serial.println("");
  }
}

while (digitalRead(bt_Select)==HIGH||digitalRead(bt_Reject)==HIGH){}
should be
while (digitalRead(bt_Select)==HIGH&&digitalRead(bt_Reject)==HIGH){}
The first loop would break only if you press both buttons at once. I believe you are trying to break if either button is pressed.

yes I try to break if either button is pressed.

Thank you it's working.. 5n

however i confused how it could works?!*

@AkRikas Your code stays in the while loop when one of the buttons is HIGH and the other code when both are HIGH. Does this answer your question?


text:
DFRobot GSM / GPS shield with UNO init error
Apologies, but I have little experience of Arduino etc. Has the "Sim808 init error" been resolved anywhere please? I have tried every example I can find including the ones on these StackExchange pages without success. I started with the GPS test code from:
https://wiki.dfrobot.com/SIM808_GPS_GPRS_GSM_Shield_SKU__TEL0097
Parancey, Marcello, Pooya and Arslan and others have suggested mods to this code so I have tried all of them I think - none working.
Then I watched this video:
https://www.youtube.com/watch?v=fN8fwX3KmsM
which appears to show the code below or similar:
/*
### Get GPS data
1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
2. Open the SIM808_GetGPS example or copy these code to your project
3. Download and dial the function switch to Arduino
4. open serial helper
4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

create on 2016/09/23, version: 1.0
by jason

*/
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

//#define PIN_TX    10
//#define PIN_RX    11
//SoftwareSerial mySerial(PIN_TX,PIN_RX);
//DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

DFRobot_SIM808 sim808(&Serial);

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

  //******** Initialize sim808 module *************
  //while(!sim808.init()) {
  while(!sim808.checkPowerUp()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");

}

void loop() {
   //************** Get GPS data *******************
   if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
    Serial.print("/");
    Serial.print(sim808.GPSdata.month);
    Serial.print("/");
    Serial.print(sim808.GPSdata.day);
    Serial.print(" ");
    Serial.print(sim808.GPSdata.hour);
    Serial.print(":");
    Serial.print(sim808.GPSdata.minute);
    Serial.print(":");
    Serial.print(sim808.GPSdata.second);
    Serial.print(":");
    Serial.println(sim808.GPSdata.centisecond);

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat,6);

    sim808.latitudeConverToDMS();
    Serial.print("latitude :");
    Serial.print(sim808.latDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.latDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.latDMS.seconeds,6);
    Serial.println("\"");
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon,6);
    sim808.LongitudeConverToDMS();
    Serial.print("longitude :");
    Serial.print(sim808.longDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.longDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.longDMS.seconeds,6);
    Serial.println("\"");

    Serial.print("speed_kph :");
    Serial.println(sim808.GPSdata.speed_kph);
    Serial.print("heading :");
    Serial.println(sim808.GPSdata.heading);

    //************* Turn off the GPS power ************
    sim808.detachGPS();
  }

}

I have mounted the DFRobot shield on a UNO and powered through the barrel connector with a 2_amp 5V stabilised power supply. The DFRobot shield shows a red LED power light and pressing reset flashes the blue LED next to it, but nothing else does anything - the serial monitor just repeats "Sim808 init error". In the video the blue "net" LED flashes even before the SIM card is inserted, but my card does not flash. Do I return the board to Farnell and ask for my money back?
Any help greatly appreciated!

The problem is probably that you are trying to use Serial for both communication with the SIM808 and the PC at the same time. That can't really work.

Do you have a genuine Arduino or a cheap chinese knock-off?

@Majenko: Thanks for help. This is with genuine Arduino Uno from RobotShop not a knock off and the DFRobot shield came from Farnell in a proper labelled box and in antistatic bags for antenna and shield. The code quoted is just one of many I have tried.

Not entirely relevant, but I have just connected up a Chinese generic Sim900 board and it worked 'straight out of the box' using the LastMinuteEngineers' code so I think my DFRobot Sim808 shield is broken/ unserviceable.

The dfrobot board has a weird boot button system that you need to follow to boot up the board. I spent ages attempting to get it to work before I finally achieved anything.
There is a blue led on the board that will flash continuously at different rates if the chip has been correctly powered and is searching for a mobile network.
I noticed that you commented it the while(!sim808.init()) line. This attempts to power the board on automatically, but I do remember something being funny about the implementation.
From doing a while load of research the dfrobot breakout board is not the best hardware implementation of this chip. Actually from memory there aren't any modules I have been able to find which satisfy all my requirements for a project. I'd recommend looking at all the documentation dfrobot provide on their website. Hopefully that should get you working.
Summary: it's an insanely fiddly process to get it working, but the boards are functional


text:
How can I read the data stored in EEPROM although is powered OFF based on the simple code I wrote?
I need help regarding on EEPROM library. Based on the code below, for every 2 sec, I want to store the int for increase where it will keep increasing by 1. Then, I upload to my Arduino Nano and open Serial Monitor to let it run for about 20 seconds. The serial monitor shows that Increase Count:10.
Then I unplug the Arduino Nano, closed the Serial Monitor, wait for 5 sec, then plug back to computer and turn on the Serial Monitor, then the Serial Monitor start to shows Increase Count:1, which indicated it start to recount again from 1,2,3,4.....
I thought that EEPROM will store the last number it counted which is 10, then when I unplug and plug back it should continue to count from 10, 11, 12, .......
So I would like to ask community whether my execution code and the method is correct or not. If not, can you advice me on how I can execute it correctly. Thank you in advance!
#include <EEPROM.h>

int addr=5;
int storagedata;
int increase;

void setup()
{
  storagedata=EEPROM.read(addr);
  Serial.begin(9600);

  timevalue=millis();
}

void loop()
{
  if (millis()-timevalue>=2000)
  {
    increase=increase+1;

    EEPROM.update(addr,increase);
    storagedata=EEPROM.read(addr);

    Serial.print("Increase Count:");
    Serial.println(storagedata);

    timevalue=millis();
  }
}

Yup, true. That is why I need some guidance. Thanks

increase is a global variable and will implicitly initialized with the value zero. Then you are reading the EEPROM data into the variable storagedata in setup(). And then in loop() you are increasing increase from zero to one and write that to EEPROM. This value then gets read back into storagedata. So now increase and storagedata have the same value: one. So the counting begins on every reset at 1.
It is unclear, why you even have 2 variables for this. One would be enough (unless you want to test the EEPROM for some reason). In setup() read the data into increase. Then the counting starts with the number in EEPROM.

strange what some people consider as useful answer

@Juraj I'm not sure, what you are criticizing here. Can you explain that a bit more? Is my answer not good in some way? Or is it about the fact, that such an easy answer gets more upvotes, as more complex ones? (Which I also wonder about)

I wonder how is the answer useful for anybody else then OP

@Juraj About that we could have a full discussion. Here we often have question, from whose answers others will most likely not profit. We have the possibility to dismiss those questions and close them, or answer them to help. Or - if you have an answer to the question, which would also help others - you can add your own answer.

Hey there, thank you for highlighting my error and I learned so much from your reply. Is fixed and it works fine.

The problem is that you fail to initialize increase during setup(). The variable is undefined when the code enters the loop() function, even regardless of whether this is the first boot or not. You should change storagedata to a local variable in loop() and use increase to keep the value (or vice versa).

You never use the value you read in setup().  Go through your loop() function one line at a time:
// this does not use the value read in setup, variables are initialized to 0
// so the first time through this loop it will set 'increase' to 1
increase=increase+1;

// you are updating EEPROM with the value of 'increase' which is 1 the first
// time this is executed
EEPROM.update(addr,increase);

// you are reading the '1' that was just written into 'storagedata', you have
// never used the value you read in 'setup()' and have now overwritten it
storagedata=EEPROM.read(addr);

I'm not sure why you have two separate variables, but in setup() you just need to
initialize increase as the value read from EEPROM:
storagedata=EEPROM.read(addr);
increase=storagedata; // start with stored value instead of default 0


text:
Generate a true analog signal using Arduino
I am looking for a way to create a true analog output with the arduino uno. I am constantly reading an analog input on a0 pin, all i want to do is send the same signal as output. I know arduino convert the signal into pwm so have can i convert it back to true analog signal.I have a dac too but not getting proper output.
secondly, i want to send same signal by converting it into bits through Ethernet so how do i send and receive the signal.
here is my code for dac.
#include "Wire.h"
#include "MCP4725.h"
MCP4725 MCP(0x60);
uint32_t microphonePin=A0;
uint32_t threshold=800;
const int ledPin=13;

void setup() {
    Serial.begin(115200);
    pinMode (ledPin, OUTPUT);
    Serial.print("MCP4725 test program: ");
    Serial.println(MCP4725_VERSION);
    if (MCP.begin() == false)
     {
       Serial.println("Could not find sensor");
     }

    MCP.begin();
 }

void loop() {
   uint32_t sensorValue=analogRead(microphonePin);
   MCP.writeDAC(sensorValue);
   Serial.println(MCP.getValue());
   if (MCP.getValue()>threshold)
    {
      digitalWrite (ledPin, HIGH);
    }
   else{ digitalWrite(ledPin, LOW); }

  }

here is my circuit for audio amplifier

and for the speaker it is connected on DAC out.
FYI:I am able to read the data on my serial monitor form mic and i am also able to so do some operation by just using mic and GUi. I just want to here what i am saying on speaker.

you cannot output the same signal as intput, because you are not reading all of the input signal ... you are reading only intermittent samples of the input signal

using those value i want to create if not the same signal then approximately same signal

Can you describe how the signal you get is different from the expected signal? What frequencies do you need to process?

i have connected mic with amplifier circuit on my analog pin a0 now i want that send that signal to the speaker which is connected with dac. DAC is connected With A4 and A5 pin.

Why are you connecting the speaker with the mic through the Arduino? Why not connecting the mic amplifier circuit directly to the speaker amplifier? The Uno is not really made for audio processing. You can do some, but the result is not very good. And you give it an unnecessary workload with also outputting the digitized signal as analog.

my end game is to connect mic to one arduino and speaker to another arduino then communicate between them as they will be kept far from each other. but problem is that its not able get output on one device two device is far fetched.

I see that MCP4725 uses Wire library with the default clock of 100,000 kb/sec.
At a rough estimation each call to MCP.writeDAC or MCP.getValue will be at least 32 bits long and you use three of them in each loop.
This one:
   Serial.println(MCP.getValue());
   if (MCP.getValue()>threshold)

is redundant, you should store the value in a temporary variable and use-it in both "print" and "if".
With 10us for each bit that means 1060 us for each loop. The analog read also takes 100us to complete. Over all 1160us minimum.  Is the MCP.getValue() really needed?
That means that your maximum sample frequency is 860hz and the maximum bandwidth of 430hz. I doubt that this is an acceptable bandwidth for a microphone.
Even so, the output signal will not look similar at all, you need a higher bandwidth or to limit,  if possible, the bandwidth of the input signal.
In some limits you can modify the MCP4725 library to use fast wire clock four times faster if it suits your requirements. If you also drop the two MCP.getValue() calls that will be again almost three times faster, up to 5khz.
Also you might search for faster ADC on Arduino.
Update after OP microphone amplifier schematic.
The ADC works only with positive voltages. Short the output capacitor of the amplifier!

Hey, thanks for reply i have removed those two line only difference is their is less high pitch noise but i am not getting desired output.

@eTollSystems Oh!!! Now I see the other big flaw in your design!!! The ADC is not working with negative voltages!!! See the updated answer.

If you want something simpler than the transistor version you can use the following as well, for the other options skip to the --here-- mark
Oldstyle analog out. this works like a vacuum tube and while I use a LDR you can also use heat or a actual vacuum tube.
You Will Need:

A low resistance LDR or multiple in parallel.
A cardboard box or other box to isolate it from outside interfearance.
A Led or light bulb.

How this works: while a led flashes, a LDR needs a certain time to just to values(often up to around a few ms), so this will stabilize your adc signal.
You send the desired amplitude as a pwm signal to the light source(you probably want to invert your pwm signal) which aims at the LDR. you send your sound frequency through the LDR which now works as a variable resistor.
!!Use low resistance LDR's and a bright light source to get a as low as possible resistance. with (weak)lasers, you can get a normal LDR down to around 1 to 0 ohm. but you will most likely use a led since that has more precise intensity control.

Another simple method is the inversed of analog read in an Arduino. you basically use multiple output ports with different resistances to get a different output when done right in this case you can get around 257 different volume levels with 8 pins for the amplitude and 1 for the frequency.
--here--
--added this here as a simple explaination/guide--
first start with getting your microphone working, see if analogread get's some high values. if it stays at 0, 1 or another low value, then you didn't include a transistor with your microphone to boost the signal.
-For your output start with a project without a microphone to see if it is working right.
you will need to use 2 pins to power your output(excluding ground, assuming single-channel audio).
-the first one you will need for your frequency signal output. the other one is for the amplitude/volume/gain.
-We will use any type of amplifier(transistor) to merge the signals, in this case, I assume a transistor since they are cheap, simple low power, have an easy dynamic range and you most likely have them already.
-this following part can be done in 2 ways I would suggest to try way 1 first since it is most simple, logic, and fast which is great on a slow which is great in a small microprocesssor. where method 2 might seem the exact different way around but is much more precise.
Method 1: connect the frequency output pin to the emmitor pin of the transistor where the + normally goes in.
Connect the amplitude output pin to the base pin of transistor(the trigger)
add a very small capacitor(or a bigger one for tests) between the base and ground this is to convert the adc in analog voltage instead of pulses.
the collector of the transistor which you would normally connect to ground is your output.
you might want to add a small resistor after it especially if you are using it for a audio cable. you can also directly connect a very small speaker to hear the sound
for a cable(be careful withconnection arduino IO to things like a pc) you connect the output as oudio signal and the ground as ground. but check what voltage the other devices audio port supports since arduino's IO pins generate 5v
method 2.
connect the frequency out pin to the base of the transistor,
connect the ADC of the amplitude pin to the emitter pin of the transistor,
connect a capacitor of larger capacity than described in method 1 between the emitter pin of the transistor and the ground of the Arduino.
the collector is again your output, you might to as a resistor to it.
connect a wire from an analog port to the emitter pin of the transistor to read out the voltage in the capacitor for precise voltage regulation.
tinker with the values of the capacitor size.
(you now have an energy pool in front of the transistor if you know the ampere on which you are outputting you can use this to regulate the pool, otherwise you can read it using the analog feedback loop).
important to know is that if you want precise volume you use a larger capacitor, if you want fast volume differences you use a small one and intentionally use more pins to charge it. for an Arduino Uno due to low analog read speeds, I would recommend a larger capacitor or this.
extra stuff when putting your complete system together you might run into speed issues. you should therefor connect the microphone to both a digital and a analog pin. the digital pin constantly monitors the frequency and the analog pin measures the amplitude sometimes(add a small capacitor get that average amplitude).
I would also recommend turning down the analog read precision to prevent checking for all 1024 possible voltages.
for method one you can also add a extra resistor from base to ground and from the amplitude pin to base so you can more precisely calculate the voltages.
--end of simple version--
You can try to use 2 pins for the output signal. one of them sends the frequency digital(3 pins if you also want negative polarity audio). this output signal should go to something like a transistor or a digitally controlled potentiometer or amplifier. I will assume you use a transistor since those are most common and quite fast.
the first digital output pin should go to the emitter pin of the transistor
the second pin is used for the volume and will go to the base of the transistor. you might want to add a very small capacitor between the base and ground to reduce frequency interference(to prevent the ADC frequency from showing up in your signal).
the Collector pin would be your analog output suitable for audio.
So in basic steps:

split  the signal into a digital frequency and volume. (the digital frequency can be made by seeing a signal above a certain value as high and the other as low, this works best when you use both the positive and the negative side of the soundwave otherwise you will need to chose a very low number)(the analog frequency is literally your analog value for the positive only audio, and value-512 (*-1 for negative numbers to get only positive numbers) for the full audio if you include the negative audio)
Send the frequency signal to the emitter pin of your diode.
Send the amplitude signal to the base pin of your diode.
Connect a small capacitance between the ground and the amplitude signal.

however What Dorian said are things you might want to keep track of as well since they often indeed tend to kill of such projects because you very easily run into speed limits(analog read in a arduino ar basically 1024 digital reads(literally)).
So some tips for your cirquit:

If your microphone doesn't have a transistor connected to boost the signal add it since otherwise the analog port of the arduino uno is not sensitive enough to measure the signal. you can and should fist test this using a project where you constantly analogread and print it. you can add a small capacitor between the analog port and the ground to just measure the voltage.
use diodes to rectify your microphone signal, your arduino can only read positive voltage, the microphone also sends negative voltage. redirect the negative voltage to the arduino ground (you can invert the negative voltage using a transistor or some other methods to read the negative voltages as well, but I would recommend just sending the negative signals to ground since this would give the near full range as well)
use 2 microphones one for frequency and one for amplitude. or connect the output of your microphone to both a analog and a digital port. you might in the last case want to use resistors to lower the current going to them this makes sure both get a accurate voltage.
avoid as manny analog reads as possible, storing it is better than calling it twice
use c/c++ bitmanipulations for IO, not only is it more easy to program larger systems when using them, they are also a lot faster( arduino uno has the PORTB, PORTD, PIND, PINB, DDRD, DDRB, and the a and c version(however you most often only use the D and B) predefined. bitmanipulations require very little knowledge compared to other programming methods as long as you know the port addresses, which again for the arduino uno are predefined search: arduino uno bit manipulations or arduino uno PORTB.
you can sample the sound frequency using a digital port at a higher frequency than the amplitude. since sound often doesn't jump to fast in amplitude in a way that you would clearly notice. this means you could read the sound with a IO pin and write it on another IO pin, additionally you could once every interval measure the amplitude to use which makes your code a lot faster.

there are way more ways but these are easy to do.
for sending it trough internet however you need to be careful that the module you use processes those things itself so that you do not just connect a internet port since that would slow your system down even more.
For those wanting a ms paint sketch:
version one:

version two:

note that I just used random images from the internet you can use any capacitor and transistor that works for this, I did not check if this transistor is right for this, but it had a nice layout description in the image. the capacitor doesn't need to be ceramic, but this way you see clear legs and I don't need to focus on polarity. in general, all cheap 5v compatible transistors should work and all capacitors if they are not way too big or too small for your load.
I used descriptions rather than logos, so anyone should be able to read it as long as they have software to tell the differences in colour if they are colourblind.
How it works
The transistor sends the voltage from the emittor to the collector(or the other way around based on the transistor you use). so in method 2 which also works for mosfets. we send a adc signal to the capacitor to charge it to a voltage, you should however also add a resistor to ground or a cable to a analog port, because otherwise the voltage can just build up to 5v. this capacitor which we charge becomes a analog power source. we connect it to the emmitor(or pin which you normally connect on the + side). so if we where to open up the transistor(close the cirquit) by putting a positive voltage on the base or trigger pin then you would get a output of the voltage that you put into it. so if you play the frequency digital on the base completely opening and closing the transistor then you get a voltage output similar to the voltage in the capacitor.
method one works more difficult but a transistor opens up relative to the current going from base to exit, so we use the pwm and a small capacitor to get a analog voltage on it only partly opening it, then we send the digital audio signal into the pin that you normally connect to 5v and you get that frequency payed with the transistor acting as a variable resistor
So method one uses a transistor as a variable resistor
And method two uses the transistor or fet as a switch which uses the voltage build up in the capacitor, doesn't actually need to use pwm if you use a feedback loop.

i will work on it to see if it give desire output.

mic is working fine. I am not able to understand what other frequency you are sending to the transistor. one will be mic output through arduino which will be pwm data.

@eTollSystems the pwm data is used for the amplitude/volume only. since pwm sends a digital frequency that would show up as sound as well and only does it X times a secon, we can't use pwm for the audio signal.

@eTollSystems the signal pin is used to mirror the frequency/sound the mic hears. so you send out the sound digital. and use the pwm for the volume.

@eTollSystems so if your mic would give these signals: 0,382,890,3,999,4,439,0
then you could for example say everything above 200 is high and all other  is low. if you use a digital pin to read the mic it will be a lot more easy that way you can just ask if it is high or low( you can connect the mic to both a analog and a digital port(just add a resistor towards the digital port))

so the mic's sound is send as a digital signal, and the loudnes can be send as pwm.

@eTollSystems I've added 2 new methods, the first is similar to the others but more simple and old-fashioned, so this should be much more easy to make. the other is quite different but needs no conversion since you can literally write a analog signal with that(it does however take more pins). I also added some clarification about the 2nd transistor method. your mic hardware seems good and you said it worked. however you can connect the + out to the analog port and through a resistor to a digital port to also get a digital signal, or manually convert analog to digital in code.

i will look into your suggestion and yes my mic signal is working fine. when i am connecting those two pin directly to the speaker i am getting the proper output. Now i want to separate  mic and speaker and communicate it via one arduino if that works then i will be separating  mic and speaker further more by connecting mic in one arduino and speaker in another arduino and communicate between the arduino. If you have any suggestion or alternative for that please provide. thax in advance

@eTollSystems if your second arduino is only to reduce load in the first one you can also just connect the mic with amplifier to the arduino and the speaker, you can add a extra transistor as extra amplifier if it needs to be louder. you should also first try the output using tone() and a some predefined amplitudes since the analogread samplerate is really low so reading a microphone with a arduino as a analog device often needs a lot of custom extensions to your arduino to still hear the propper sound.(without other code a arduino could theoretically perform 10.000 analogreads per second max)

hey, ted i have started receiving some desire output but their is still lot of noise. I will add more filter and transistor to make it proper.  and no i am not separating my mic and speaker because of load my end game is mic will be in one room and speaker in another and  i should be able to here that voice properly .

@eTollSystems To detect where the problem is can you check the sample frequency so we know for sure that is right, since that is the most likely to have problems.
also I haven't used that specific amplifier chip you use, but do you have the powersource+ connected to the arduino + and powersource - to the arduino- and not a powersource that delivers negative voltages relative to the arduino ground. In the chips I use there is a reference pin, most often this one is only for the voltage so you can put that to 2,5v using resistors.  this will make it output 0v to 5v

for this wave however you will need to split it in 2 sections. <2.5v would be one wave and >2.5v would be another wave. so you need to see if it is below or above. if above just subtract 2.5v and do the result *2. if it is below. than do it -2.5v again and *-2 you might want to enlagre the low area instead of only using exactly 2.5v for example  >2<3

@eTollSystems For the other noice. again not based on your specific chip, but I use medical amplifier chips which are made for low noice. yet when build wrong you still get nice. so what you should do with high amplification is : keep short cables, avoid static charges or areas with magnetic fields such as earthlines or transformers and electric cables/coils. a more simple approach is to use aluim foil to make a faraday cage around your amplifier cirquit. so put aluim around longer jumpercables to shield them. and put cardboard with aluim around the cirquit, connect the aluim to arduino grnd

for your case(audio) there also is https://github.com/connornishijima/arduino-volume1
or the volume library
to install it you can use the git to get the files, or if you use the arduino ide, you can open the arduino ide and in the software go to helptools(4thoptionoftopmenubar)->Manage Libraries-> {type volume in the search bar}-> install the library called volume. you can also chose volume 2 or volume 3, see the git for the differences.
this however still uses micro pwm, so it is not true analog, but for audio it works. also note that on low volume the audio will be affected. I recommend only using the volumes between 100 and 255.
this method requires no additional hardware, and works well for audio, to send the audio to other devices however I would just send the audio values and not the audio output.
NOT TRUE ANALOG, but it solves your problem, the methods I described in my other answer will work well for most other analog cases, or even adding a small capacitor at that ma output might work in many cases. however since audio needs the voltage to change really fast this method works well, also since the volume is read by your mind instead of a digital device it has a normalization filter built in and a low sampling speed as well as sensitivity to only low frequency(how human brains and ears work) which will make the volume sound natural.
If you have a separate arduino for the volume or a well optimized code you can also avoid interrupts to get a higher frequency, this method is harder and requires you to know what your code does but allows for better quality volume(speciffically at low volume levels)
alternatively you can use a shiftregister and connect resisters to the outputs, for example 12800, 6400,3200,1600,800,400,200,100. like a bit but reversed, since the audio gets louder with a lower resistance. you can use other values, just don't make them to low, since arduino outputs 5v and 3.3v, both are much higher than your average headphone connection, also turning on multiple parallel resistors at once gives a lower resistance. for example if we turn on the 100 ohm and the 200 ohm resistor we get a output of around 66,66666666 ohm since the output is 1/((1/Resistor1)+(1/Resistor2)+(1/ResistorETC)
like this a singe 8 bit shift register can deliver 256 different volume levels as true analog. if you have ports free on your ardruino you can also use those instead of a shift register, however be sure to use bitmanipulations and not digitalwrite, since the later one is slow.
1 pin = 2 volume levels
2 pin = 4 volume levels
3 pin = 8 volume levels
4 pin = 16 volume levels
5 pin = 32 volume levels
6 pin = 64 volume levels
7 pin = 128 volume levels
8 pin = 256 volume levels
etc.
this method can give true analog voltage if you know the resistance at the output, a speaker however differs in resistance based on many factors, but doing this will still give you good volume control like actual analog voltage, even though it is actually more analog amperage. to get voltage content the terminal connected to all the outputs of the resistors to another resistor to generate a voltage divider, this works for things like vga displays, however for things like audio, lights, etc. you should jus directly take the output of the resistors


text:
Why does a pull down resistor configuration not destroy the pin it's connected to?
I don't understand why a pull-down resistor connected to ground would prevent a pin connected to 5V through a button would not destroy the pin as the current does not need to go through the resistor to get to the pin. I've tried looking online but the question was never asked and I couldn't find any information that explained how it works.
I'm asking this in the context of something without internal resistors so it would have no protection against a short circuit/being connected straight to a source.

When you have a pin in INPUT mode it is high impedance. That means that to all intents and purposes, to the outside world, the pin is not connected to anything internally.
In reality it is, but that internal connection is of such a high impedance (i.e., resistance) that it is almost equivalent to an open circuit.
It's simplest to think of an input pin as a voltmeter.  A pulldown resistor and button would look like this:

simulate this circuit – Schematic created using CircuitLab
When the button is opened the voltmeter reads zero, because one end is connected to ground, and the other end is connected to ground through the resistor.
However when you press the button the voltmeter reads the voltage across the resistor - that is, 5V - because one end is connected to ground and the other to 5V, with a resistor across it.
If you don't have the resistor then the voltmeter can't measure anything when the button isn't pressed - it's just waving around in the air without a clue what it's doing - and a wire waving around in the air is called an antenna...
The Arduino is that voltmeter. All it does is detect the voltage at the pin, it doesn't conduct any (or only a very very tiny amount of leakage) current through the pin.
Now the possibility of a short circuit comes when you set the pin to OUTPUT. If you drive the pin LOW then the pin is essentially connected to GND, and pressing the button will connect the 5V straight to GND through the LOW-driven IO pin.

good analogy...

A pullup or pulldown wire would destroy the pin because it would source or sink enough current to burn out the pin driver.  But a pullup or pulldown resistor limits the current to a very small value (I = E/R = 5v/10000Ohm = .0005A or .5 ma, well within the pin driver's 20 ma limit.


text:
Don't understand problem with my code
I'm trying to get a robot car(elegoo one) to do the obstacle avoidance course. I am trying to write my own one from scratch to better myself and thus would really appreciate it if someone were to tell me what's wrong with my code and why it's not working
#include <Servo.h>  //servo library
Servo myservo;      // create servo object to control servo
Servo servosweep;
int Echo = A4;
int Trig = A5;

#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define carSpeedForward 100
#define carSpeedLeftandRight 150
int rightDistance = 0, leftDistance = 0, middleDistance = 0;
int pos=0;

void forward(){
  analogWrite(ENA, carSpeedForward);
  analogWrite(ENB, carSpeedForward);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Forward");
}

void back() {
  analogWrite(ENA, carSpeedForward);
  analogWrite(ENB, carSpeedForward);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Back");
}

void left() {
  analogWrite(ENA, carSpeedLeftandRight);
  analogWrite(ENB, carSpeedLeftandRight);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Left");
}

void right() {
  analogWrite(ENA, carSpeedLeftandRight);
  analogWrite(ENB, carSpeedLeftandRight);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Right");
}

void stop() {
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
  Serial.println("Stop!");
}

//Ultrasonic distance measurement Sub function
int Distance_test() {
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(20);
  digitalWrite(Trig, LOW);
  float Fdistance = pulseIn(Echo, HIGH);
  Fdistance= Fdistance / 58;
  return (int)Fdistance;
}

void setup() {
  myservo.write(pos);
  myservo.attach(3);  // attach servo on pin 3 to servo object
  Serial.begin(9600);
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  //stop();
}

void loop(){
  for (pos = 0; pos < 90; pos += 1.0) {
  servosweep.write(pos);
  delay(50);
  leftDistance=Distance_test();
  }

  myservo.write(90);
  middleDistance=Distance_test();

  for (pos=90;pos<=180;pos+=1.0){
    servosweep.write(pos);
    delay(50);
    rightDistance=Distance_test();

  }

  if(rightDistance > leftDistance) {
        right();
        delay(360);
      }
      else if(rightDistance < leftDistance) {
        left();
        delay(360);
      }
      else if((rightDistance <= 40) || (leftDistance <= 40)) {
        back();
        delay(180);
      }
      else {
        forward();
      }
}

I'm trying to get the ultrasonic sensor to read values from the left(0 to 90), the middle(90) and the right(90 to 180) and then use them for comparison to decide where to go. When I run this code my car goes in circles and I don't know what the problem is. Any help would be appreciated.

you don't need the two for loops .... leftDistance is only measured at 90 degrees ... rightDistance is only measured at 180 degrees

As jsotola writes, you are running through the 0-89 position and updating leftDistance every time. Then you find the middleDistance and finally you go through 91-180 and update rightDistance. After the two for loops, leftDistance will have the value for 89 and rightDistance will have the value for 180 because you overwrite your value without doing anything with it.
Start by skipping the for loops and measure at 0, 90 and 180 and use these values as you left, middle and right distance. When deciding if you want to back up, use the middle distance. Remember to use a delay between measurements that is large enough for the servo to get to the position for the next measurement

As a couple people already pointed out, you're using for loops that are unnecessary, and will cause you to get the wrong measurements. You're better off just using myservo.write(); to set your servo to positions 0 and 180.
Additionally you never check to see if there's an obstacle infront of your robot. Instead, your robot immediately tries turn right or left. That's what's causing it to spin.
Here's a fixed version of your void loop()
void loop(){

  myservo.write(0);
  delay(50);
  leftDistance=Distance_test();

  myservo.write(90);
  delay(50);
  middleDistance=Distance_test();

  myservo.write(180);
  delay(50);
  rightDistance=Distance_test();

  /* Start by checking if there is space to go forward */
  if(middleDistance > 40){
     forward();
     }
/* If there isn't space to go forward, turn */
  else if(rightDistance > leftDistance) {
        right();
        delay(360);
      }
  else if(rightDistance < leftDistance) {
        left();
        delay(360);
      }
  else if((rightDistance <= 40) || (leftDistance <= 40)) {
        back();
        delay(180);
      }
   else {
        forward();
      }
}

I hope this helps!


text:
Why am I receiving random input values in my Arduino?
I want to use a switch for my Arduino using digitalRead(), but I keep receiving random inputs. Whenever I connect energy to that pin, it always returns HIGH, but otherwise it goes completely random.
I have tried using a resistor for the input pin, but that didn't seem to help. I am using an Elegoo UNO, and the input pin I am using is pin 2. Here's my code in case you need it:
const int switchPin = 3;

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

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(switchPin) == HIGH){
    Serial.println("on");
  }

  else{
    Serial.println("off");
  }
}

No pulldown resistor on that pin then...?

Let me guess: You are not using an external pullup or pulldown resistor (relatively large value resistor from the pin to eiter Vcc or ground). When nothing is connected to a pin it is floating (basically an antenna). A pullup/down resistor pulls the pin to a fixed value, when nothing else is connected. You can use an external resistor, or you can use the internal pullup resistor by doing pinMode(switchPin, INPUT_PULLUP)

Does this answer your question? Digital Pin State - Some 1, Some 0

How did you connect the resistor for the input pin?

You're getting noise pickup on the input pin when the button is not pressed. You need a pull-down resistor, about 10 kΩ to ground, to quiet the noise when the switch is open.
Or even easier, use the built-in pull-up resistor in the Arduino, which is ~10 kΩ to +5 V, wire your button to ground instead of +5 V, and reverse the if tests to test for logic LOW instead of HIGH, to detect a button press. You'd change your pinmode statement to:
pinMode(switchPin, INPUT_PULLUP);  // engage the input pullup

and your test to:
 if (digitalRead(switchPin) == LOW ){ // Negative logic

No additional (external) hardware is needed!

Your code mentions pin 3 while you describe using pin 2. Perhaps that has to do with your error.
Otherwise, check the following things:

do you use long cables or is it near strong magnetic or static
objects.
for your code since you only read if it is high, see if the button is connected to 5 V and pin 2 or 3 whichever one you use

You can try adding a resistor between your I/O pin and the ground.
Another test I prefer to do is:
Take a working jumper cable, test it with a voltmeter, or see if you can make an LED light up when connected to it (use the Arduino 5 V, ground and a resistor for this (resistor to not let your LED explode like that zeppelin).
With the working jumper cable or breadboard cable, connect one end to the pin you plan to use. Then run the program and connect the other end to ground, then 5 V, and then ground and so forth to see if it responds well.
This is based on an Arduino Uno. If you use another type of Arduino, make sure to use the proper voltage pin. You can always add a resistor between the wire and the Arduino for extra safety.

Here is what you can do

Check if the switch is connected to the defined input pin. The Arduino starts form pin 0 and sometimes we can misread while connecting.

Check if the serial monitor has same baud rate as defined in the program.

Check the voltages around switch using a multimeter.

Still not getting a solution? Attach a pull-down resistor.

Still not getting a solution? Invert the logic and current flow as suggested by JRobert.

Few things that can be checked and used.

If you are using a normal push button then check the connections properly as two of the pins are internally connected two each other. So we need 2 pins that are not connected so check it with DMM.

You need a Pull-UP or pull-Down resisters attached to the input pin.
The value of a resistor depends on your requirement like if you have long wires or more noise you need a strong pullup or pulldown resister like 1k. And the best way is to test it out first with an internal pull-up resistor which is considered a week pullup and Atmega328p has its value of around 20k.
pinMode(switchPin, INPUT_PULLUP);

As TeD has stayed check that you are using the same digital pin in your hardware and code.

And last a simple counter type debouncing logic will help to denounce the button input signals. as shown in the below code.

#define switchPin 2
byte debounce_counter = 150;

void setup() {
  pinMode(switchPin, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(switchPin) == HIGH) {
    debounce_counter++;
  }
  else {
    debounce_counter--;
  }

  if (debounce_counter >= 240)
  {
    debounce_counter = 150;
    Serial.println("OFF");
  }
  else if (debounce_counter <= 60)
  {
    debounce_counter = 150;
    Serial.println("ON");
  }
}

You can also check other methods and libraries for debouncing the input signals which uses the millis function.


text:
Detect if a display is connected
I want to detect wether a display is connected or not.
This is the display: https://www.az-delivery.de/en/products/1-77-zoll-spi-tft-display
I read connecting a pin of the display with another pin with a pull up resistors. Unfortunetely nothing worked so far.
My microcontroller board is Arduino Mega.

What methods with which code have you tried? How have you troubleshot them?

Best thing is send a schematic, not a frizzy thing. What pin is connected to what pin is important, and only one setup is correct. Might as well post the code as well.

if the board is plugged in, then pin 1 and pin 14 are connected together

There is nothing immediately apparent on that display that can tell you if it's connected or not. If you had a full SPI interface (you are missing the MISO pin) you could query the display for the HWID, but alas not. And there's no pins at all that are outputs.
The only suggestion I can come up with is to connect a small (say 1Ω) resistor between the Arduino's 5V pin and the display's VCC / LEDA pins and use an analogue input to measure the voltage on the display side of it. When the display is disconnected it will give a 5V reading. When it's connected the reading will drop to a slightly lower voltage (depending on the current draw).
Schematic:

simulate this circuit – Schematic created using CircuitLab

As jsotola mentioned in his comment, pin 1 and pin 14 on the display are connected to each other (GND). You can connect pin 14 to an input pin with enabled INPUT_PULLUP. If no display is connected, this pin will be pulled high by the pullup, thus the pin will read high. If the display is connected, the pin will read low.


text:
NodeMCU and SDS011
today I connected the SDS011 to NodeMCU. I noticed that this only works when the sensor is connected to the voltage VU. If I connect the sensor to another pin for the voltage, it does not respond.
Why is this so?
If I see it correctly, the reason must be that data is exchanged via RX and TX.
#include "SdsDustSensor.h"

int rxPin = 5; //d1
int txPin = 4; //d2
SdsDustSensor sds(rxPin, txPin);

void setup(){
  Serial.begin(9600);
  sds.begin();
  sds.setCustomWorkingPeriod(0);

}

void loop(){
PmResult pm = sds.readPm();
  if (pm.isOk()) {
     Serial.println(pm.pm25);
     Serial.println(pm.pm10);
  }

  delay(250);

}

how can anyone know? ... you said nothing about the sketch that you are using

Share some schematic/code.

The SDS011 needs 5 V powering and the VU pin is the 5 V from USB on the NodeMCU development board.


text:
How can I store a value of 1000 over to EEPROM of Arduino Nano?
I need some of your feedback and guidance. In my prototype project powered by Arduino Nano(Space Constraint), it will operate continuously until it reach a maximum of 100 hours. Once it reached 100 hours mark, Nano will prompt users to do servicing/maintenance etc.
So in order to preserve the operating time from losing when powered off, I used EEPROM library to store the data. Based on my research, EEPROM.update(addr,value), each addr can hold one byte, which is 0-255 values. To prevent my EEPROM die from storing operating time of 100 hours, I used flag method, where every 5 mins of operation it will increase flag and store the flag value to EEPROM.
Is there other method other than changing the 5 mins benchmark?
Below is the simple/direct code that I wrote, the original code is too complex, and I have put a few comment especially the "Ideal Command" that I want.
#include <EEPROM.h>

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

  regenflag=EEPROM.read(regenaddr);
}

void loop()
{
regenflag=EEPROM.read(regenaddr);

if(totaltime>=300000)//Every 5min machine operated, increase regenflag (Fixed)
  {
    regenflag=regenflag+1;
    Serial.print("How many times it Operated==> ");
    Serial.println(regenflag);
    unblink=1;//Flag for other operation

    EEPROM.update(regenaddr,regenflag);
    regendata=EEPROM.read(regenaddr);

    totaltime=0;
}

/////////////////////////////////Ideal Command/////////////////////////////////////////////////////////
if (regendata>=1200) //100hrs=6000mins (6000mins/5mins=1200 times)
{
  Serial.println("Need to do Servicing")
}

use EEPROM.put and EEPROM.get https://www.arduino.cc/en/Reference/EEPROMPut


text:
Rotating Servo Motor using Arduino
Using arduino, I'm trying to rotate a 360 servo that will move clockwise 5 seconds,pause and counterclockwise for 5 seconds and then completely stop. However, my servo just continuously keeps on rotating in one direction. Any suggestions will be helpful

Please post your code and circuit, otherwise we can't really help you.

you have not put your code here so i can not understand it properly.From what i understand you must have put your code for rotating the servo motor 5 times in void loop. Don't do that put loop for rotating servo 5 time in setup.
void loop run continuously so it must be rotating 5 time then again 5 time and so on.


text:
Renault car (2003) remote control signal is not received by rc receiver (rcswitch)
I have an arduino uno, I have set up a rf receiver as well known library rcswitch suggests I do, but I can never see something on the serial monitor in the IDE environment. I am using the example provided by the library, and did the pin set-up as described.
The key (car card) is that of an old Renault Laguna 2. I have browsed the web and am pretty sure that it sends an rf 433mhz signal, and my receiver is also listening to that frequency, so I am quite surprised that nothing pops up.
I also have a transmitter but only 1 dev board so can't really think of any way to test the receiver. Any suggestions ? In case the receiver might be broken how can it be tested? Am quite new to this.
Any help appreciated

433MHz is just the name of the band. You need the receiver to be tuned to the exact frequency the key fob transmits on - and then it needs to decode the data in the right way to make some sense of it.

Step one with any unknown transmitter is to buy a cheap USB SDR dongle and analyse the radio signal.

@Majenko thanks for the answers.but i was looking for a way to do it without buying nothing else. i was lookin thru the rfswitch lib and I don't see where it sets the frequenct on which to listen on, is this the same as setting the protocol ?

The frequency is set by the receiver module. If that doesn't match the transmitter it won't receive anything at all.


text:
Can I create an hemi-cycle raising signal with one pin and the other hemi-cycle signal with another pin?

I am new to Arduino, I would like to know if someone could help me to create this type of signal with the Arduino Uno. Many thanks!!

I'd use an MCP4822.

the arduino does not have analog output per se ... it is a PWM output ... please clarify what pin 9 and pin 10 signify in the diagram ... what is the purpose of the signal

it is to create an induced magnetic field in coils and stray currents. It is for an electrochemical project. Yes!! I know you cannot generate an analog output but if it is similar to the sketch would be OK. The pins 9 and 10 are I want to use, so the pin 9 and ground and the pin 10 and ground.

it is unclear how pin 9 and pin 10 are used ... if pin 9 and pin 10 are analog outputs, then you should draw two separate waveforms

Yes!! you are right, my fault it is unclear, they are two different waveforms superimposed


text:
Is there a Arduino UI library that provides dialog box and button functionality at a minimum?
I have been looking at the Arduino TFT Library and it supports all the bits and pieces for making a simple display, but I am looking for something a little higher level that has primitive dialog box and button capability, and presumably, the ability to layer the display so I can push and pop display elements.  Is there a higher level GUI library for Arduino TFT displays?

a quick search found this ...https://youtu.be/UEKrithNr1g

Take a look at this library. Will this do all that you want?
https://github.com/AndreiDegtiarev/AWind
I have not tried it yet but I would like to.
Edit:
I just remembered this https://github.com/ImpulseAdventure/GUIslice
https://github.com/ImpulseAdventure/GUIslice/wiki
A lightweight GUI framework for embedded displays
The library supports creation of multiple pages of buttons, text, images, checkboxes, sliders and other graphics primitives. New UI / widget types can be created easily.
It works with many existing TFT libraries. There also is a drag & drop builder application.  https://github.com/ImpulseAdventure/GUIslice-Builder


text:
Can't test for equality with string received from bluetooth module
I am trying to keep the program within a loop until the user inputs "ok" on the Bluefruit Connect App. I use the readString() function on the bluetooth object (ble) to read from it. Before this loop, my String command variable is initialized to be empty. Here is my code:
while(!command.equalsIgnoreCase("ok"))
{
  while(ble.available())
    command = ble.readString()
}

I have confirmed that I can receive data as I can output the command variable to the Serial monitor.
Why does the condition for this loop always return true (i.e. why is the String command variable never equal to the string literal "ok", while ignoring case)?

output the length of the command variable to serial monitor ... it may not be what you expect ... always do that when you're debugging code

@jsotola Wow you are right. When I send the string "ok" it says the length is 3. Is that the newline character being sent with it, or something else? How would I go about removing that extra character in the string?

this may help ... https://majenko.co.uk/blog/reading-serial-arduino

@jsotola It's working now!  Thank you so much!


text:
What is the highest baud rate that can work between Android device and an Arduino connected to an HC05?
I see a lot of baud rates in the AT Command documentation for the HC05 however I am not sure what is the fastest that can work between the Arduino controlled embedded system and the Android phone. I also do not know of a way to change the baud rate of the Bluetooth communication in software. I am writing the application in Java with Android Studio IDE.
I read the documentation for HC05 and realize that it only operates with one Bluetooth profile. i.e the Serial Port Profile. The documentation says that this profile offers a maximum data-rate of 128000 bits/sec. However, the HC05 has a max baud rate option of 1382400 bits/sec. Why would this option be there if it is not possible to use? Can you please explain what I am missing and point me into the direction of some useful information? Thank you.

The HC-05 may only have implemented baud rates up to 1382400, even though the protocol is spec'd for up to 128000.
If you're using Software Serial to talk to the HC-05 from an Uno, 9600 baud is about as fast as SoftwareSerial can keep up with incoming bytes (I've heard from some people that 19200 will work).
If you're using one of the UARTs on a Mega, you may be able to use the full rate implemented by the HC-05. An experiment would be in order...
Update:

I did an experiment and found out that the maximum baud rate
achievable between the HC05 (communicated with by SoftwareSerial on
Arduino Nano) and the Android device is 115200.

I would guess you were transmitting from the Arduino? I've been able to transmit that fast with SoftwareSerial but its receiving ability is more limited. (This has enabled me to, f/ex, set an HC-05 or an ESP8266 to a slower baud-rate than it shipped with, by blindly transmitting an appropriate 'AT' command at the higher speed, then testing it at my intended speed to see if the command worked).

I did an experiment and found out that the maximum baud rate achievable between the HC05 (communicated with by SoftwareSerial on Arduino Nano) and the Android device is 115200. Any baud rate higher than this did not work for neither HC05 - HC05 nor HC05 - Android. Also, I could not find a way in the Bluetooth Documentation (https://developer.android.com/reference/android/bluetooth/BluetoothSocket) to change the baud rate used on the Android device with Bluetooth SPP. It was as if the device automatically adjusted to the baud rates I configured on the HC05. i.e. 9600 - 115200.

Seems logical, that Android will change the baudrate to be matched. The communication from HC-05 to Android is only a virtual serial interface. Baudrate doesn't have much meaning for it. Only the real UART interface between HC-05 and Arduino really needs a baudrate


text:
How does one wire OV7670 camera with Arduino Due?
The parts that I want to interface together are:

Arduino Due
OV7670 Camera Module
3.5" TFT Touchscreen LCD (uses MCUFRIEND_kbv library)

My goal is to get the video feed from the camera to the LCD screen. Any help will be appreciated.

I am working with small project same in little bit like what you trying to do..
starting with..
1- Arduino UNO + OV7670 + 2.4" TFT LCD (I got not clear live Image)..
so I made some changes..
2- Arduino DUE + OV7670 Live Image (still working with, having problem in reading Image) want to compile the result Image (convert it to text) then sending the result to (3) by serial Port
3- Arduino UNO + 3.5" TFT LCD (it works)..
by the way  Arduino UNO + OV7670 Live Image (worked perfectly), but I am trying to get same project using DUE.. (faster speed & maybe could deal with Image too..)
here link of how OV7670 work with Arduino DUE..
https://www.instructables.com/How-to-Connect-OV7670-to-Arduino-Due/
.....

I tried the link you provided (and many others) before coming to stackexchange for help. I wanted to use the OV7670 for sending video feed to 3.5" Touchscreen display. As I was short on time, I did move on to using OV2640 with Arducam chipset as it has libraries available for Arduino Due. So far, the process has been smooth with OV2640 module.


text:
EM-18 RFID module not reading Card ID
I am using EM-18 Rfid module with Arduino mega the problem is that when i swipe the card for reading the card ID nothing will shown in serial monitor.Code given below.EM-18 connection diagram is given in attachments.
int count = 0;
    char card_no[12];
    void setup()
    {
       Serial.begin(9600);
    }
    void loop()
    {
       if(Serial.available())
       {
          count = 0;
          while(Serial.available() && count < 12)
          {
             card_no[count] = Serial.read();
             count++;
             delay(5);
          }
          Serial.print(card_no);
       }
    }

your code is unnecessarily complex .... furthermore,  you do not print anything until 12 characters have been received .... that is "shooting yourself in the foot" .... print the characters as they arrive ... that means, get rid of the while block .... reduce the code to if serial data is available, then get serial data and print it

Is this ok?
int count = 0;
char card_no[12];
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
         card_no = Serial.read();

      Serial.print(card_no);
   }
}