body: I need to connect the 89c51 with Arduino UNO but same time I need to connect 89c51 microcontroller with Arduino without using serial reception and transmission pins of UNO b'coz that pins already engage with GSM module. plz, suggest me the program solution to serially receive data from 89c51 and send the message to gsm module.

title: serial communication between arduino to 89c51 with gsm

Answers: 1

body:
The Arduino Uno only has one (hardware) serial port. Since you need two, you have in principle two solutions:

- Use a software serial, this will work only for low speed transmissions. You can download this as a library.
- Use an Arduino (or other microcontroller) which has more than one hardware serial port, like the Arduino Mega which has 4.


body:
I'm working on a project in which I need a series of very accurate pulses containing 2 shots in every pulse. The pulse should have 100µsec on time followed by 300ms off time. But when I'm programming the Arduino Due I'm getting random pulses of non-uniform width. But when I'm trying the same code in microsecond range I'm getting perfect wave.
Here is the code that I'm using
<!-- language-all: lang-cpp -->

    #define LED 8 // Pin designated to give out the pulse
    int cycles = 2;  // No. of times you want it to give pulse
    int high = 100; // High time in microseconds
    int low = 300;  // Low time in milliseconds
    int i = 0;
    int univ_cycle = 10;

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

    }
    void loop(){
      for (i ; i < univ_cycle; i ++){
      pulse();
      delay(100);
      }
    }
    void pulse() {

      // put your main code here, to run repeatedly:
      for(int counter = 0;counter < cycles;counter++){
      digitalWrite(LED, HIGH);
      delayMicroseconds(high);
      Serial.println("ontime");
      digitalWrite(13, LOW);
      Serial.println("offtime");
      delay(low);
      Serial.println(counter);
      }

    }
Here is the image of the waveform in microsecond setting
[![enter image description here][1]][1]

Here is the wavefrom that we got in millisecond setting
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/UvccR.png
  [2]: https://i.stack.imgur.com/n83Kz.png

I would like to know how can I get the similar wave in microsecond also.

title: Series of µsec pulse generation using Arduino Due

Answers: 0


body:
I am generating two 50kHz square waves, but I would like to generate three square waves. I have problems with generating the third square wave.
Basically, I need to configure the timer bits so that I can get the third square wave.

    Here is the code I need to modify for the third square wave:
    // This code demonstrates how to generate two output signals
    // with variable phase shift between them using an AVR Timer

    // The output shows up on Arduino pin 9, 10

    // More AVR Timer Tricks at http://josh.com

    void setup() {
      pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
      pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B

      // Both outputs in toggle mode
      TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );

      // CTC Waveform Generation Mode
      // TOP=ICR1
      // Note clock is left off for now

      TCCR1B = _BV( WGM13) | _BV( WGM12);

      OCR1A = 0;    // First output is the base, it always toggles at 0

    }

    // prescaler of 1 will get us 8MHz - 488Hz
    // User a higher prescaler for lower freqncies

    #define PRESCALER 1
    #define PRESCALER_BITS 0x01

    #define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

    // Output phase shifted wave forms on Arduino Pins 9 & 10
    // freq = freqnecy in Hertz (  122 < freq <8000000 )
    // shift = phase shift in degrees ( 0 <= shift < 180 )

    // Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC

    /// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.

    int setWaveforms( unsigned long freq , int shift ) {

      // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.

      unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave

      ICR1 = clocks_per_toggle;

      unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision

      OCR1B= offset_clocks;

      // Turn on timer now if is was not already on
      // Clock source = clkio/1 (no prescaling)
      // Note: you could use a prescaller here for lower freqnencies
      TCCR1B |= _BV( CS10 );

    }

    // Demo by cycling through some phase shifts at 50Khz

    void loop() {

      setWaveforms( 50000 , 90 );

      delay(1000);

    }

title: Configuring Timers to Add One More 50kHz Square Wave

Answers: 0


body:
I was given the task of being able to drive two motors in the forward direction, able to drive two motors in the reverse direction, and they must be able to drive each motor independently. I was wondering if anyone can give me directions, advice, or tips on the coding for this task. All I know is that:
if(switchState == HIGH){
digitalWrite(motorPin, HIGH);
}
else{
digitalWrite(motorPin, LOW);
}
}
I know this code makes the motor turn on and off with the high and low, but what type of code do I use to make it work at a certain speed, and to move independently?

title: Help with my project on motors using the Arduino Board

Answers: 1

body: you can use PWM function of digital pins (analogWrite())to control the motor speeds as desired.


body:
I am trying to send data to a php file via http GET method.

I am able to send static data but I am unable to send dynamic data.

    #include <SoftwareSerial.h>
    SoftwareSerial gprsSerial(9, 10);

    char inchar;
    int ledPin = 13;
    int sensorPin = A0;
    int sensorValue = 0;

    boolean gs = true;
    boolean es = true;
    boolean ss = false;

    void setup()
    {
      gprsSerial.begin(9600);
      gprsSerial.println("AT+CNMI = 2,2,0,0");
      Serial.begin(9600);
    }
    void loop()
    {
       currentMillis = millis();
       if(gprsSerial.available()>0)
      {
        inchar = gprsSerial.read();
        if (inchar == '#')
        {
          delay(10);
          inchar = gprsSerial.read();
          if (inchar == '1')
          {
            Serial.println("System Enabled");
            ss = true;
            snd_msg(0);
          }
          else if (inchar == '0')
          {
            Serial.println("System Disabled");
            ss = false;
            snd_msg(1);
          }
          delay(10);
          inchar = gprsSerial.read();
          if (inchar == '1')
          {
            Serial.println("Geofence Enabled");
            gs = true;
            snd_msg(2);
          }
          else if (inchar == '0')
          {
            Serial.println("Geofence Disabled");
            gs = false;
            snd_msg(3);
          }
          delay(10);
        }
      }
        gprs();
        delay(10000);
    }

    void toSerial()
    {
      while(gprsSerial.available()!=0)
      {
        Serial.write(gprsSerial.read());
      }
    }
     void snd_msg(int a)
    {
      gprsSerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      gprsSerial.println("AT+CMGS=\"+918148090646\"\r"); // Replace x with mobile number
      delay(1000);
      if ( a == 0)
      {
        gprsSerial.println("System Enabled");
      }
      else if ( a == 1)
      {
        gprsSerial.println("System Disabled");
      }
      else if ( a == 2)
      {
        gprsSerial.println("Geofence Enabled");
      }
      else if ( a == 3)
      {
        gprsSerial.println("Geofence Disabled");
      }
      delay(100);
       gprsSerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
      gprsSerial.println("AT+CNMI = 2,2,0,0");
      delay(1000);
    }
    void vibra_sensor()
    {
      sensorValue = analogRead(sensorPin);
      Serial.println(sensorValue);
      for(int i = 0; i < 5; i++)
      {
      if (sensorValue > 500)
      {
        es = true;
        break;
      }
      else
        es = false;
      delay(500);
      }
      delay(1000);
    }
    void gprs()
    {
      vibra_sensor();
      Serial.println("Config SIM900...");
      delay(2000);
      Serial.println("Done!...");
      gprsSerial.flush();
      Serial.flush();

      // attach or detach from GPRS service
      gprsSerial.println("AT+CGATT?");
      delay(100);
      toSerial();

      // bearer settings
      gprsSerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
      delay(2000);
      toSerial();

      // bearer settings
      gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"www\"");
      delay(2000);
      toSerial();

      // bearer settings
      gprsSerial.println("AT+SAPBR=1,1");
      delay(2000);
      toSerial();
      // initialize http service
      gprsSerial.println("AT+HTTPINIT");
       delay(6000);
       toSerial();

       // set http param value
     **gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=ON\"");**
       delay(5000);
       toSerial();

       // set http action type 0 = GET, 1 = POST, 2 = HEAD
       gprsSerial.println("AT+HTTPACTION=0");
       delay(6000);
       toSerial();

       // read server response
       gprsSerial.println("AT+HTTPREAD");
       delay(1000);
       toSerial();

       gprsSerial.println("");
       gprsSerial.println("AT+HTTPTERM");
       toSerial();
       delay(300);

       gprsSerial.println("");
       delay(10000);
       gprsSerial.println("AT+CNMI = 2,2,0,0");
      delay(1000);
    }

**What I've Tried**

1.) Saving URL in a string

    String URL = "adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=";
        URL += ss;
        gprsSerial.println("AT+HTTPPARA=\"URL\",\"+URL\"");

Doesn't Work

2.)Attaching values using print statement

    gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus=");
    gprsSerial.println(ss+"\"");

3.)Entering value directly in URL

    gprsSerial.println("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="+ss+"\");

**Error**

    invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

I'm using an arduino uno and a sim 900a GSM module.

**QUESTION**

How do I send dynamic values for **gfence, sstatus, estatus**?

I am also using a messaging service, the code is included. **The help I need is in the gprs() function.**

The data I need to send is,

gfence from gs

sstatus from ss

estatus from es

title: Sending dynamic data to webserver

Answers: 1

body:
You should split it up:

    gprsSerial.print(F("AT+HTTPPARA=\"URL\",\"adnansait74.000webhostapp.com/operation.php?timestamp=02:50:00&latitude=11.374545&longitude=76.728986&gfence=OFF&estatus=OFF&sstatus="));
    gprsSerial.print(ss);
    gprsSerial.println(F("\""));

Note the use of `print` on each part up until the *last* part which is the only one that uses `println` in order to terminate the line.

Also note the use of the `F()` macro to reduce the wastage of RAM that string constants cause.


body:
This may be a very stupid question, but I have got me one of those cheap 433 MHz RF modules for the Arduino.
I'm wondering if I can vary the receiver's frequency by simply changing the length of the antenna? Or does the circuit limit the frequency band to 433 MHz?

Thanks in advance.

title: Change RF Receiver Frequency by Antenna Length

Answers: 1

body: No, changing the antenna length will only change the resonant frequency of the antenna circuit. That is, it will affect the sensitivity of the receiver, but won't actually change the frequency that the receiver "listens" to.


body:
[Background] I'm constructing a water bottle rocket which is going to use apogee detection and a mechanism for the parachute release.

Connected to the Uno will be an accelerometer and a servo, now due to the need to minimise the dry mass of the rocket I want to use as few and as light batteries as feasible. Would it be possible to power this setup with 2 AAAs? If not how many would be necessary? Would other types of Arduino such as a micro work on fewer batteries?

Thanks for the help

title: Powering an Arduino Uno using 2 (or as few as possible) AAA batteries

Answers: 1

body:
I've got [a page about power saving](http://www.gammon.com.au/power).

My first suggestion would be to not use a Uno, which is quite heavy (because of its size) but a smaller Arduino like a Mini. Second, I think you'll find that LiPo batteries are quite light, and come in various sizes (and thus, weights). A single cell will output around 3.7V which is fine for driving an Atmega328P. Possibly you could drop the clock to 8 MHz because of the voltage.

If you don't need it to be "awake" all the time consider using the techniques described in my link above to make it sleep for (say) 4 seconds at a time and then take a measurement.


body:
Basically I created a web page to control 4 channel relay, then I made an HTTP get request from that page and got the following response:

    Linked

    T+CIPSEND=4,50

    > GET /ard/sensor.html HTTP/1.1
    Host: localho
    SEND OK

    +IPD,4,351:HTTP/1.1 200 OK
    Date: Sat, 07 Apr 2018 01:22:58 GMT
    Server: Apache/2.4.9 (Win32) PHP/5.5.12
    Last-Modified: Sat, 07 Apr 2018 01:17:13 GMT
    ETag: "72-56937eec1c277"
    Accept-Ranges: bytes
    Content-Length: 114
    Content-Type: text/html

    <p> Relay1 = 1#  </p> </br>
    <p> Relay2 = 0#  </p> </br>
    <p> Relay3 = 0#  </p> </br>
    <p> Relay4 = 1#  </p> </br>
    OK

    OK
    Unlink

Now I want to store Relay1 status (which is 1 here) in a variable, also all other Relays in order to control them high or low
Note : # is supposed to be the separator
and here is my code:

        #include <SoftwareSerial.h>

    const int LED_PIN = 13;

    String ssid = "ABC";
    String password = "a14102016a";
    const byte rxPin = 6;
    const byte txPin = 7;

    SoftwareSerial ESP8266 (rxPin, txPin);

    unsigned long lastTimeMillis = 0;

    void setup() {

      Serial.begin(9600);
      ESP8266.begin(9600);
      reset();
      connectWifi();
      delay(2000);
    }

    //reset the esp8266 module

    void reset() {

      ESP8266.println("AT+RST");
      ESP8266.println("AT+CIOBAUD=9600");
      delay(1000);

      if (ESP8266.find("OK") ) Serial.println("Module Reset");

    }

    //connect to your wifi network
    void connectWifi() {

      String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
      ESP8266.println(cmd);

      delay(4000);

      if (ESP8266.find("OK")) {

        Serial.println("Connected!");

      }

      else {

        connectWifi();

        Serial.println("connect to wifi");
      }

    }

    void printResponse() {
      while (ESP8266.available()) {
        Serial.println(ESP8266.readStringUntil('\n'));
      }
    }

    void loop() {

      if (millis() - lastTimeMillis > 30000) {
        lastTimeMillis = millis();

        ESP8266.println("AT+CIPMUX=1");
        delay(1000);
        printResponse();

        ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
        delay(1000);
        printResponse();

        String cmd = "GET /ard/sensor.html HTTP/1.1\r\nHost: localhost";
        ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
        delay(1000);

        ESP8266.println(cmd);
        delay(1000);
        ESP8266.println("");
      }
      if (ESP8266.available()) {
        Serial.write(ESP8266.read());

    Byte R[ ] = ESP8266.read () ;
    Serial write (R[ ]);

    //    if (readString.indexOf("Relay1=1">0))
    {
        Serial.write("found");
    }
      }

    }

Any suggestions ?

title: Parsing HTTP get response to extract values

Answers: 1

body:
First of all, I would avoid using the `String` class, because of the
memory fragmentation issues that come with it. The most obvious solution
is probably to store the result in a character array, then parse the
array, with `strstr()` or `sscanf()`, to extract the values you want.
However, this requires storing the whole response in RAM, which is
expensive. A better option is to parse the string as it comes, character
by character, using a kind of finite state machine.

Here is how I would do it. First, I assume you know what you want to do
with these values. Since I don't, I will instead use this dummy function
to just print the values out to the serial port:

<!-- language-all: lang-c++ -->

    static void parse_relay_callback(uint8_t index, uint8_t value)
    {
        Serial.print("parsed: relay ");
        Serial.print(index);
        Serial.print(": ");
        Serial.println(value);
    }

You will have to replace this with whatever is appropriate for your
application.

Then here is the parser:

    static void parse_relay(char c)
    {
        static const char templ[] = "RelayI = V#"; // I: index, V: value
        static uint8_t pos, index, value;
        char expected = templ[pos++];
        if (expected == 'I' && c >= '0' && c <= '4')
            index = c - '0';
        else if (expected == 'V' && (c == '0' || c == '1'))
            value = c - '0';
        else if (expected == '#' && c == '#')
            parse_relay_callback(index, value);
        else if (c != expected)
            pos = 0;
    }

You just feed it one character at a time, with something like:

    while (ESP8266.available())
        parse_relay(ESP8266.read());

Feeding the parser with your response example gives the following on the
serial port:

<!-- language: lang-none -->

    parsed: relay 1: 1
    parsed: relay 2: 0
    parsed: relay 3: 0
    parsed: relay 4: 1


body:
I'm using an ESP8266 with the following pin configuration and it doesn't connect to my WiFi. The blue light on the ESP module is on and my LED is on. That's it.

- VCC - 3.3v
- GND - GND
- CH_PD - 3.3v
- GPIO 0 - GND
- GPIO2 - LED

I'm using a 1,000 mah 3.7 LiPo battery for this.
Here's my Arduino code. I'm following a tutorial from nyl.io.

    #include <ESP8266WiFi.h>
    #include <ArduinoJson.h>

    const char* ssid     = "sukkaa";
    const char* password = "123456789123";
    const char* host     = "www.sukkzzesp.tk"; // Your domain
    String path          = "esp\light.json";
    const int pin        = 2;

    void setup() {
      pinMode(pin, OUTPUT);
      pinMode(pin, HIGH);
      Serial.begin(115200);
      delay(10);
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);
      int wifi_ctr = 0;
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("WiFi connected");
      Serial.println("IP address: " + WiFi.localIP());
    }

    void loop() {
      Serial.print("connecting to ");
      Serial.println(host);
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
      }
      client.print(String("GET ") + path + " HTTP/1.1\r\n" +
        "Host: " + host + "\r\n" +
        "Connection: keep-alive\r\n\r\n");
      delay(500); // wait for server to respond
      // read response
      String section="header";
      while(client.available()) {
        String line = client.readStringUntil('\r');
        // we’ll parse the HTML body here
        if (section=="header") { // headers..
          Serial.print(".");
          if (line=="\n") { // skips the empty space at the beginning
            section="json";
          }
        } else if (section=="json") { // print the good stuff
          section="ignore";
          String result = line.substring(1);
          // Parse JSON
          int size = result.length() + 1;
          char json[size];
          result.toCharArray(json, size);
          StaticJsonBuffer<200> jsonBuffer;
          JsonObject& json_parsed = jsonBuffer.parseObject(json);
          if (!json_parsed.success()) {
            Serial.println("parseObject() failed");
            return;
          }
          // Make the decision to turn off or on the LED
          if (strcmp(json_parsed["light"], "on") == 0) {
            digitalWrite(pin, HIGH);
            Serial.println("LED ON");
          } else {
            digitalWrite(pin, LOW);
            Serial.println("led off");
          }
        }
      }
      Serial.print("closing connection. ");
    }

Pls help me with this error. Thanks.

title: ESP8266 doesn't connect to WiFi

Answers: 0


body:
I am working with the MCP4131 Digital Potentiometer and I am running into some trouble. The MISO and MOSI functionalities are multiplexed onto the same pin. Obviously, this means that I have to have Pin 13 and 12 hooked into the same pin on the chip.

I want to read send a READ command to the chip so that I can get the current value of the POT; however, when I send the lower byte in order to retrieve the value, I simply am getting back whatever I send because pins 13 and 12 are hooked into the same spot.

Is there any examples on how to work with a module such as the MCP4131 where the MISO and MOSI are on the same pin? Thank you!

title: Reading data from potentiometer with MISO and MOSI on same pin

Answers: 1

body:
You need to do a little conversion:

* Connect the SDI/SDO line to MISO on the Arduino.
* Connect a 1kΩ resistor between MISO and MOSI on the Arduino.

Then you first send the command byte(s) to the slave. You will receive these back, but you can just ignore them.

Then you receive the data. You do this by sending 0xFF for each byte. The 1kΩ resistor means the slave can override the 0xFF from the MOSI. The MOSI -> MISO resistor effectively becomes a pullup resistor and is, to all intents and purposes, ignored (it's just in parallel to the pullup resistor internal to the slave).


body:
I'm new to programming. I would like to change the characters on an SSD1322 OLED display. Here are the photos.

Is this possible with an Arduino Uno? Is the program of the display in the display or in the Mega 2560?

Thanks for your help!

[![2560][1]][1]
[![SSD1322][2]][2]
[![overview][3]][3]

  [1]: https://i.stack.imgur.com/E6YY2.jpg
  [2]: https://liedson.fr/2.jpg
  [3]: https://liedson.fr/3.jpg

title: How to program an SSD1322 display?

Answers: 0


body: Is there good tools (IDE, CLI or IDE addon) to send file via USB port to SPIFSS internal espressif ESP hardware SoC ?

title: What is the tool to send file to SPIFSS on ESP8266/32?

Answers: 1

body:
The [mkspiffs][1] tool creates bin from file system data (or extracts data from bin).

SPIFFS bin is uploaded with esptool over USB or with espota over WiFi. It can be uploaded with the sketch binary in one command.

Example:

    esptool.py -p /dev/ttyUSB0 write_flash 0x0 sketch.bin 0x300000 spiffs.bin

[The IDE plugin][2] adds SPIFFS upload to Arduino IDE Tools menu.

  [1]: https://github.com/igrr/mkspiffs
  [2]: https://github.com/esp8266/arduino-esp8266fs-plugin/blob/master/README.md


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

title: How to write Arduino API code in VL53L1X?

Answers: 1

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

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

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

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

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

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


body:
- I have an Arduino Due that is connected both over native USB to PC and a 12v power supply in the Jack.

- Mounted on the Arduino I have a custom PCB that drives 3 motor drivers. The Motor drivers are powered via the arduinos VIN Pin with 12v.

As Ive read elsewhere the arduino automatically chooses the 12v powersupply in this case. My question is: If the 3 motor drivers exceed the 1amp that the powersupply can supply, will the arduino encounter errors/shutdown or automatically switch back to USB for power supply?

If so, is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Also, how much current can I safely drive through the VIN Pin?

Thanks!

title: Can external power supply above current limit lead to errors/shutdown arduino?

Answers: 1

body:
If the incoming voltage drops below 6.6V the MOSFET will activate for the USB power and that will become available. But it's not perfect.

The MOSFET is always "partially" active - that is, the "body diode" is always available, so if the 5V rail drops below the USB voltage minus the forward voltage of that body diode the USB power will take over regardless of what else is happening. That 5V rail then feeds the 3.3V regulator, and
since the ARM chip on the Due is a 3.3V chip, even a dip of a volt or so on the 5V rail should have no effect on the MCU.

So theoretically the chip should keep running fine all the time regardless of what happens with the power.

> Is there a way I can force the arduino to take the USB 5v even though 12v are connected through the Jack?

Not really, no.  You can remove the 12V from the jack though and just power from USB. Connect the 12V to your motor drivers, and link its ground to the Arduino ground. The motors will use the 12V supply, and the Arduino the 5V supply.

> Also, how much current can I safely drive through the VIN Pin?

The diode inline with the barrel jack is rated at a maximum sustained current of 1A. Any more than that and you risk blowing that diode.


body:
I am using an LDR sensor to store its readings into the database. My code is as follows:

      #include <SPI.h>
      #include <Ethernet.h>

      const int ledPin = 13;   //the number of the LED pin
      const int ldrPin = A0;  //the number of the LDR pin

      byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

      IPAddress ip(192, 168, 1, 177); // ip of arduino

      char server[] = "192.168.1.105"; // IMPORTANT: If you are using XAMPP you
      will have to find out the IP address of your computer

       // Initialize the Ethernet server library
       EthernetClient client;

       void setup() {

       // Serial.begin starts the serial connection between computer and Arduino
       Serial.begin(9600);
       pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
       pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
       // start the Ethernet connection
       Ethernet.begin(mac, ip);

     }

   Next, I wrote the setup code:

     void loop() {

      int ldrStatus = analogRead(ldrPin);   //read the status of the LDR value

      //check if the LDR status is <= 300
      //if it is, the LED is HIGH

      if (ldrStatus <=300) {

       digitalWrite(ledPin, HIGH);               //turn LED on

       }
     else {

    digitalWrite(ledPin, LOW);          //turn LED off

    }

    // Connect to the server (your computer or web page)
    if (client.connect(server, 80)) {
    client.print("GET /info.php?"); // This
    client.print("value="); // This
    client.print(ldrStatus);
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.1.105");
    client.println("Connection: close"); // Part of the GET request telling the
    server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server

    }

    else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
    }

    // Give the server some time to recieve the data and store it. I used 10
    seconds here. Be advised when delaying. If u use a short delay, the server
    might not capture data because of Arduino transmitting new data too soon.
    delay(1000);
    }

The problem is that when I try connecting to database, it gives a database connection failed. I have crosschecked the ip address of my computer and have even logged into it using xampp to check if it is working.
However, the problem is still persistent.

title: Cannot connect to database Ethernet Shield

Answers: 0


body:
I have a 144 LED strip - Adafruit NeoPixel Digital RGB LED Strip 144 LED, link here:  https://www.adafruit.com/product/1507

If I create a simple project, eg turning pixels on off from the serial connection, then everything works fine.  But when I build a solution with an ethernet jack and acting as a http server and lots more code, as soon as I try to show the strip then random pixels light up in random colours.

I know the code is logically ok because if I run it to eg print a string to the serial port, "Turning pixels 0-71 green" the code works.

There are 762 lines of code and quite a few global variables defined.

When I compile I see:

    Sketch uses 19180 bytes (59%) of program storage space. Maximum is 32256 bytes.
    Global variables use 1462 bytes (71%) of dynamic memory, leaving 586 bytes for local variables. Maximum is 2048 bytes.

I did previously see build messages warning of instability due to size of global variables which I cut down and at least don't see the instability warning now.  Could it be that the code is using too many resources?  Any tips of reducing the code and / or use of global variables?

I am powering via the USB cable.  The unit is an Arduino Uno -the Arduino starter kit.  Could it be a power issue?

I have a 470ohm resistor on the data line into pin 6.  And a 1000uF capacitor between 5V+ and ground.  Anything else that could help?

I am using the Neopixel library to control the led strip: https://github.com/adafruit/Adafruit_NeoPixel

title: Lighting up long led strip no longer works when my code grows

Answers: 0


body:
Apr 06, 2018, 09:52 pm
I hope this is appropriate.  I posted this question on the Arduino/Sensor site, got 42 views, but no reply.
-----------------------------------
I had no success getting help with any earlier post on this subject, so I am starting over with new code by Kevan Darrah. He is a good  programmer, so the code should work, but it doesn't.  I did a lot of reading and I understand how it should work, so let me spend few words explaining what I learned and maybe someone can take it from there. The LMT01 output is 0.6V to 1.6V pulses 10 usec wide, I verified this using a scope, the total number of theses pulses is proportional to the temperature. This repeats every 100 msec.  This signal is input to pin D2, but that is a digital pin: High=5V, Low= 0V, but Arduino IDE does something sneaky when you use the special function "attachInterrupt(pin,ISR,Falling)" - It redirects the signal internally to pin A0N of the positive side of an Analog Comparator, and attaches to AN1 internally a stable reference voltage of 1.1V. Now the 0.6V to 1.6V pulses are exactly centered on the comparator so it puts out a perfect 1's and 0's for easy counting.
So to repeat myself only Pin2 is attached with the LMT01 to the Arduino. Why doesn't this  &!#^-thing work, it compiled and uploaded correctly.  If I had  a debugger on this software, moving one line at a time I could fix it myself.  Code follows:
------------------------------------------------------------------------

     //Sample Code for LMT01 Temperature Sensor
    //LMT01ELPGQ1
    //Kevin Darrah

    //TempPins
    #define pulsePin 2 //D2 on arduino D5 on esp8266 **This is the output from the LMT01

    //globals for the LMT01 temp sensor
    volatile unsigned int pulseCount = 0;//pulses out of the sensor
    float temperatureC = 0, temperatureF = 0;//converted temperatures
    float tempHIGH, tempLOW = 1000;

    //functions
    void pulseDetect();//interrupt function
    float getTemperature();//call this to get temperature from the LMT01 - returns a float for the temperature in (C)

    void setup() {
      Serial.begin(115200);
      pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

    }

    void loop() {
      temperatureC = getTemperature();// call getTemperature() to return temp in C
      if (temperatureC != 1000) {//returns 1000 if anything went wrong
        temperatureF = temperatureC * 9.000 / 5.000 + 32;
        if (temperatureF > tempHIGH)
          tempHIGH = temperatureF;
        if (temperatureF < tempLOW)
          tempLOW = temperatureF;
        Serial.print(temperatureC);
        Serial.print("C  ");
        Serial.print(temperatureF);
        Serial.print("F  HIGH=");
        Serial.print(tempHIGH);
        Serial.print("F  LOW=");
        Serial.print(tempLOW);
        Serial.print("F  DIFF=");
        Serial.print(tempHIGH - tempLOW);
        Serial.print("F  ");
        Serial.print(pulseCount);
        Serial.println("pulses  ");
        for (int i = 0; i < random(50, 200); i++)
          delay(1);
      }

    }

    float getTemperature() {// *********  GET TEMPERATURE FUNCTION *** returns the temperature C
      attachInterrupt(digitalPinToInterrupt(pulsePin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge

      unsigned long conversionStartTime = millis();//keeps track of timing

      while (millis() - conversionStartTime < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
       // yield();//for the ESP8266 to keep other tasks happy
        if (pulseCount > 0) {
          pulseCount = 0;
          conversionStartTime = millis();
        }
      }

      pulseCount = 0;//reset pulse count
      while (millis() - conversionStartTime < 150) {//wait for first pulse
       // yield();//for the ESP8266 to keep other tasks happy
        if (pulseCount > 0)
          break;
      }
      if (pulseCount == 0)
        return 1000;//FAIL - never got a pulse

      conversionStartTime = millis();//conversion done, so reset time
      unsigned int oldPulseCount = pulseCount;//just to help keep track of timings when pulse pin goes idle
      unsigned long pulseTime = millis();
      while (millis() - conversionStartTime < 60) { //measure pulses
       // yield();//for the ESP8266 to keep other tasks happy

        if (pulseCount != oldPulseCount) {//new pulse, so update timer
          oldPulseCount = pulseCount;
          pulseTime = millis();
        }
        else if (millis() - pulseTime > 5) {//no pulses for a while, must be done.
          break;
        }
      }
      //^^^ Stays stuck here counting pulese for 60ms

      if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
        return 1000;//FAIL
      }

      detachInterrupt(digitalPinToInterrupt(pulsePin));//done with the interrupt
      temperatureC = 256.000 * pulseCount / 4096.000 - 50;//conversion
      //see 7.3.2 Output Transfer Function in Datasheet

      return temperatureC;//throw the temp back
    }

    //change this function to look like this if using the ESP8266
    //void ICACHE_RAM_ATTR pulseDetect()

    void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
      pulseCount++;
    }

title: LMT01 temperature sensor code does not run - need help

Answers: 1

body:
This is added 15 months after the OP but there is very little information on this sensor.

You have not included your schematics which would be useful. For this setup TI gives you four options: transistor level shifting, isolation, multiple devices to one MCU pin, and common ground with high-side signal. Kevin Darrah uses the transistor level shifting method in his videos. Please refer to the [TI datasheet][1] for connections, pages 3 and 21 are relevant in setting that up. There is also [this sample code][2] supplied with a video that shows setup using the comparator.

NOTE: Ensure you do not have your sensor reverse biased or it will not work and may wreck it. Diodes are a good idea here.

Try commenting this out:

    if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
    return 1000;//FAIL
  }

I found this sensor gives very low pulse readings if you have something setup incorrectly which will come out around -50C and this line may be causing it to read a fail. If that is the case you will need to rewrite the getTemperature() function, possibly using the comparator method supplied by TI which will require you to rewire, see their training code which includes a video. TI notes the first couple of readings may be incorrect. In my code I have my function perform several throwaway tests before spitting out a reading.

TL;DR If you use the TI comparator method, you can use the digital pins for power instead of the +5VDC like they do but use a diode (needed also for multiple sensors) to isolate the sensor to prevent reverse bias. If you do this you can shut the sensor off by switching it to INPUT but be aware, OUTPUT mode goes to ground by default which can cause reverse bias and fry your sensor. Use digitalWrite(pin,HIGH) prior to switching to OUTPUT to change default behaviour to +5V rather than GND (true, the diode should protect you here but adding this line is necessary anyway so do it in this order, safety first). I needed multiple sensors in my build so this is what I found, I used the Arduino-based comparator method quite successfully.

I don't have the necessary components to connect with transistor level shifting and actually test this at the moment but you could try this code if you want. I trimmed it down, eliminated most of the ESP8266 stuff you weren't using anyway and modified the getTemperature function to resemble what I have working right now.

    //Sample Code for LMT01 Temperature Sensor
    //LMT01ELPGQ1
    //Kevin Darrah
    // Ben Nesbitt, 2019

    // For LMT01 if using transistor method of connection

    //TempPins
    #define pulsePin 2 //D2 on arduino  **This is the output from the LMT01

    //globals for the LMT01 temp sensor
    volatile unsigned int pulseCount = 0;//pulses out of the sensor
    float tempC = 0;//converted temperatures
    float tempHigh = 151;
    float tempLow = 151;
    unsigned long timeMillis = millis();

    //functions
    void pulseDetect();//interrupt function

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

      pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

    }

    void loop() {
      timeMillis = millis();
      tempC = getTemp(pulsePin);// return temp in C

      Serial.print(tempC); Serial.print("C  ");
      Serial.print(pulseCount); Serial.println("pulses  ");

      while (millis() - timeMillis < 5000) {} // Change this for how often you want to sample the temperature.

    }

    float getTemp(int pin)
    {
      attachInterrupt(digitalPinToInterrupt(pin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge
      float temperature = 0;
      unsigned long timeMillis = millis();//keeps track of timing
      int counterRef = 0; // Pulse count reference

      while (millis() - timeMillis < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
        if (pulseCount > 0) {
          pulseCount = 0;
          timeMillis = millis();
        }
      }

      pulseCount = 0;//reset pulse count
      for (int i = 0; i < 3; i++)
      {
        while(pulseCount < 1) {}  //* TI recommends aborting the first one or two tests as inaccurate

        if(pulseCount != 0){
          //Wait for counting to be complete
          counterRef = 0;
          while(pulseCount != counterRef)
          {
            counterRef = pulseCount;
            timeMillis = millis();
            while (timeMillis == millis()){}
          }
          if (i < 2)
          {
            pulseCount = 0;
          }
          else
          {
             temperature = 0.0625 * pulseCount -50; // Pulses to temperature conversion
          }
        }
      }

      detachInterrupt(digitalPinToInterrupt(pin));//done with the interrupt

      //see 7.3.2 Output Transfer Function in Datasheet

      return temperature;
    }

    void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
      pulseCount++;
    }

  [1]: https://www.ti.com/lit/ds/symlink/lmt01.pdf
  [2]: https://training.ti.com/how-interface-lmt01-temperature-sensor-arduino


body:
I am trying to set up a load cell using the HX711 amplifier. Whenever I upload my sketch, my serial monitor only will read zeros regardless of load applied to the sensor (no signal appears to be sending from my load cell).

Here is my wiring, with the Arduino Uno connected to a COM port. I am using an Arduino Uno, HX711, and Sparkfun's TAL220 Straight Bar 10kg load cell.

[![enter image description here][1]][1]

Here is the calibration sketch I am using (from the HX711 hookup guide):

    #include <HX711.h>

    #define DOUT 9
    #define CLK 8

    HX711 scale(DOUT, CLK);

    float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

    void setup() {
      Serial.begin(9600);
      Serial.println("HX711 calibration sketch");
      Serial.println("Remove all weight from scale");
      Serial.println("After readings begin, place known weight on scale");
      Serial.println("Press + or a to increase calibration factor");
      Serial.println("Press - or z to decrease calibration factor");

      scale.set_scale();
      scale.tare(); //Reset the scale to 0

      long zero_factor = scale.read_average(); //Get a baseline reading
      Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
      Serial.println(zero_factor);
    }

    void loop() {

      scale.set_scale(calibration_factor); //Adjust to this calibration factor

      Serial.print("Reading: ");
      Serial.print(scale.get_units(), 1);
      Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();

      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp == '+' || temp == 'a')
          calibration_factor += 10;
        else if(temp == '-' || temp == 'z')
          calibration_factor -= 10;
      }
    }

And here is a typical output from the serial monitor (I previously had this load cell functioning correctly, which is why my calibration factor is so different).

[![enter image description here][2]][2]

Observations:

 - Whenever I upload the sketch and open the serial monitor, the TX LED on my Arduino Uno will light up flashing, but the RX LED stays off.
 - Removing the scale.tare() step will output a constant nonzero value, but the load cell is unaffected by any loading:

[![image description][3]][3]

 - I have tried adding an external power supply to the hookup assembly (I don't know if this is even necessary, but I know the load cell requires excitation to function, so I thought I'd give it a try). So far it has not changed the output in any way.
 - I have also tried adjusting the calibration factor, which only offsets the constant value outputted.
 - I have re-soldered the connecting wires to the load cell and replaced the remaining wires, as well as tried multiple Uno Boards and a new USB cord. I have also gone over my wiring and had my labmate check it too (though I will definitely not rule out it being some small wiring/hardware mistake on my part, as I am still very new to Arduino).

Thank you for any suggestions!

  [1]: https://i.stack.imgur.com/Dasf8.png
  [2]: https://i.stack.imgur.com/WVEOpm.png
  [3]: https://i.stack.imgur.com/ibTqNm.png

title: How do I get a nonzero output from my HX711 and load cell?

Answers: 1

body: The zero factor 8388607 showed up in a similar question on another forum and is associated with the range of the HX711 amplifier. This indicated that my amplifier was broken; I have since replaced it and am now receiving a signal from the load cell.


body:
In a library I am using with an OBD adapter, they define a public function to get the state of the OBD connection using some strange (and, in my opinion, useless) custom defined variable type:

    // states
    typedef enum {
        OBD_DISCONNECTED = 0,
        OBD_CONNECTING = 1,
        OBD_CONNECTED = 2,
        OBD_FAILED = 3
    } OBD_STATES;

    ...

    // get connection state
    virtual OBD_STATES getState() {
          return m_state;
    }

How can I get the state into a variable such as `boolean isConnected` or `int state` so it can interact with the rest of my code? I have tried the following with no luck:

    boolean isConnected = obd.getState() == OBD_CONNECTED;
    if(isConnected) { ... }

    int state = (int) obd.getState();
    if(state == 2) { ...}

title: Comparing custom variable type definitions

Answers: 2

body:
I found the answer to my problem, but it is not very convenient.

    Serial.write("ODB State: ");
    OBD_STATES state = obd.getState();
    if(state == OBD_DISCONNECTED) Serial.write("Disconnected");
    if(state == OBD_CONNECTING) Serial.write("Connecting");
    if(state == OBD_CONNECTED) Serial.write("Connected");
    if(state == OBD_FAILED) Serial.write("Failed");
    Serial.write("\n");

body:
In response to your answer: why don't you think it is convenient? As you already noticed, you can use the enum values directly in your sketch.

Anyway, it is better to use a switch statement:

    Serial.write("ODB State: ");
    switch (odb.getState()) {
      case ODB_DISCONNECTED:
        Serial.write("Disconnected");
        break;

      case OBD_CONNECTING:
        Serial.write("Connecting");
        break;

      case OBD_CONNECTED:
        Serial.write("Connected");
        break;

      case OBD_FAILED:
        Serial.write("Failed");
        break;

      default:
        // Error case
        break;
    }
    Serial.write("\n");

This way, whenever the enum is changed (e.g. added items), you automatically fall into the error state, so you know you have to adapter the code.


body:
I want to generate music/sounds for a video game I am making with my son (using an Arduino Mega and a 240x320 LCD graphical display). I have a basic understanding of the MIDI protocol. I've been a computer programmer for over 30 years. I read the MIDI implementation in the [DSP-G1](https://cdn-shop.adafruit.com/product-files/2400/2400.pdf) manual, but I don't understand how to go from this to sending the right signals from the dev board to the chip pins.

Everything I find is about connecting a physical MIDI device. Can anyone possibly provide or point me to information on how to control the [DSP-G1](https://www.adafruit.com/product/2400) programmatically/electronically? I think I need some hardware or software to serialize MIDI protocol bytes into a sequence of voltage changes, but all my searching leads me to info about a physical device.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/qPqAV.jpg

title: How to control a DSP-G1 programmatically/electronically?

Answers: 1

body:
The purpose of the MIDI output circuit is to convert the TTL signal into a 5 mA current.
The purpose of the MIDI input circuit is to convert the current back into a TTL signal.

If the Arduino and the DSP-G1 are part of the same circuit (and share the ground), you can omit these conversions, and connect the Arduino's TX directly to the LPC810's RX, without any other components needed. (The LPC810 requires a 3.3 V power supply, but its RX pin is 5 V tolerant.)

MIDI was designed to work with most microcontrollers, so it uses standard UART signals at 31250 baud. The only configuration you need is:

    Serial.begin(31250);


body:
So I have quite a few ideas for wearable devices using Arduino boards (mainly the Nano and the Micro clones). With that in mind, I want to determine what the best way to power an Arduino is, with compactness in mind (and cost too, of course). One single button cell battery does not supply enough power to the Arduino to power it properly. I can use [these 2x button cell battery holders (6v)][1] but they mainly ship only from China and, for some reason, are relatively expensive ($15 for 6 of them).

Does anyone know of a better and cheaper way of powering these Arduino boards, with wear-ability in mind?

Thanks! :)

  [1]: https://i.ebayimg.com/images/g/6HEAAOxyeglTXeyb/s-l1600.jpg

title: Most compact way to power 5V Arduino boards?

Answers: 1

body:
I made a [torch locator](http://www.gammon.com.au/forum/?id=12769) which looks like this:

[![Torch locator][1]][1]

That was powered by a single button cell. The actual processor is an ATtiny85. As you can see it isn't much bigger or heavier than the coin cell.

You can run the Atmega328P (and the ATtiny) at 3V (as from that battery) provided you slow them down to 8 MHz. That is quite easy to achieve, and then you don't need an external crystal as the Atmega328P has an inbuilt oscillator which can drive it at that frequency (as does the ATtiny).

I have [a page about power saving](http://www.gammon.com.au/power) which might help you with your design.

A possible alternative is a single LiPo cell (nominally 3.7V) which, if you get a small one, should be quite light.

  [1]: https://i.stack.imgur.com/8I29L.jpg


body:
I need to connect a Raspberry Pi and an Arduino Uno through serial communication and decided to follow [this guide][1], which mentions the use of a voltage divider.

I understand the connection to the Raspberry Pi GPIO requires 3.3V but I also plan to power the Raspberry Pi from the Ardunio's 5v output pin.

What's the safest approach to achieve this and the recommended current? Thanks.

  [1]: https://oscarliang.com/raspberry-pi-and-arduino-connected-serial-gpio/

title: Arduino - Raspberry Pi serial communication

Answers: 1

body:
1. You **CAN NOT** reliably power any model Pi from the Arduino 5V output.

2. You can interconnect the Arduino serial to the Pi using a voltage divider or (preferably) a level converter, as suggested in the linked article. (I might add that the linked article contains a number of errors which will not work on recent Pi models).

Better still you can use a USB connection, to provide serial communication to the Arduino, **AND** you can power the Arduino from the Pi (I often do this).


body:
Is it possible to store a value of time while you're inside a loop? Entertain the condition:

    if (condition && value > 0)
    {
    timeTrans = millis() + 2000;
    timeTrans - millis() = value;
    }

basically i want it to begin counting down from 2 to 0 no matter what time it is at, but the problem is if it's inside the loop tineTrans will update as millis counts up, and value will always be 2000 and will never count down to 0. And the condition stated in the if function cannot be called in void setup(), so there's no hope in that direction. I'd post my code but it's a little long, if it will help find a solution i will post it and point around to what i'm working on.

Also, the condition is met randomly. I do not know when, or at what time/millis() it will be met at.

I also tried using for loops as well but it counts wayyyy too fast for it to be viable, and obviously i cant delay it while its inside a void loop(). Is there any other way i can go about with this?

I've been looking at the beginners guides and here's where i'm at right now, this is about as clear and concise as this question is going to get

is there any way to make "time-2000" a constant variable in this example?

    unsigned long time, timeNow, timePast, timeStart, value;
    unsigned long period;

    void setup() {
      Serial.begin(9600);
      timeStart = 0;

    }

    void loop() {
      time = millis();
      if (time > 3000) //Using time bigger than 3 sec as a condition substitute to trigger my event
      period = time-2000; //Since in my example, we'll know at what time the condition was triggered (once it's triggered), I set the "period" to that.
        if ((time - timeStart) > period) //aaaaannndd the attempt
          timePast = period;

      Serial.print("Time: "); //debugging
      Serial.print(time);
      Serial.print(" please work ");
      Serial.println(timePast);

that "time-2000" just needs to be turned into a constant somehow. After that, i'll be golden. Anybody know a way around this?

title: Storing random and different values of millis() while inside a loop?

Answers: 0


body: Can someone interpret the code in the Title line for me?  Specifically the function of the "%" sign?  It is a line having to do with a 100 element circular buffer.

title: put_index = (put_index + 1) % 100;

Answers: 2

body: In C the % symbol is the modulo operator : https://en.m.wikipedia.org/wiki/Modulo_operation

body:
The `%` is the modulo operator in C/C++, which basically means:

1. Divide the value to the left of the `%` by the value to the right of it
2. Discard the quotient and keep only the remainder.

For instance, `10 % 5 = 0`, because 10/5 = 2 with no remainder. Whereas `11 % 5 = 1`, because the remainder of the division is 1.

In your case, the modulo operator is likely being used to keep the value of `put_index` less than 100 at all times. If it became 100 because of the operation `put_index = put_index + 1`, then the modulo operation would make the 100 into 0, so `put_index` will keep incrementing 0–99 repeatedly.


body:
The hardware is an Arduino Uno, using the Arduino IDE.
As a simplest working example, say I have this code
(partially from Edgar Bonet's [answer][1]):

<!-- language: lang-c++ -->

    // Simulate an initialization that can hang. Connect pin 8 to ground if
    // you want the function to ever return.
    void initialize()
    {
        pinMode(8, INPUT_PULLUP);
        while (digitalRead(8) == HIGH)
        ;  // wait
    }

    setup()
    {
        initialize();             //Function I want to run

        Serial.begin(9600);       //Baud rate
        Serial.println("TEST 1"); //Test message
    }

    loop()
    {
        Serial.println("TEST 2"); //Test message
        delay(1000);
    }

if the `initialize()` function does not complete after some time, such as 2 secs.,
is there a way to ignore that function and continue with the rest of the code?

  [1]: https://arduino.stackexchange.com/questions/51628/if-i-run-a-function-in-loop-or-setup-and-the-function-doesnt-work-after-so/51651#51651

title: If I run a function in loop() or setup(), and the function doesn't work after some time, is there a way to escape the function and return to the code?

Answers: 2

body:
I'm not sure if you should want this in the first place. Initialization normally should contain the necessary parts to start with.

If there is a device/component you want to initialize that is not able to initialize (because it is not present, or broken), check first if there is an intiialization function with a timeout and when the timeout is reached, set a boolean to denote the device has not been initialized.

If there is not a timeout function, you could try to set up a timer interrupt and start it just before you initialize the device/component you want to initialize. When the timer interrupt triggers and the device is not initialized, behave the same like a timeout has occurred.

body:
In general, the _right thing_ to do in such a situation is to fix the
`initialize()` function so that it always returns. If there is a timeout
to be handled, it should be handled within that function. This is likely
to be the easiest and cleanest solution.

However, if for whatever reason that is not feasible (maybe it comes
from a library that is too opaque to edit), then the idea suggested by
Michel Keijzers is a viable alternative:

> [...] set up a timer interrupt and start it just before you initialize
> the device/component you want to initialize. When the timer interrupt
> triggers and the device is not initialized, behave the same like a
> timeout has occurred.

The issue with this is that you would want the ISR (interrupt service
routine) to return to the point where `initialize()` was called. This is
not trivial, but it can be done. Actually, and contrary to what my own
comment says, it can be handled without resorting to assembly hacks, by
using the [setjmp][] “non-local goto” feature of the avr-libc. Here is a
proof of concept:

<!-- language: lang-c++ -->

    #include <setjmp.h>

    jmp_buf env;

    // Simulate an initialization that can hang. Connect pin 8 to ground if
    // you want the function to ever return.
    void initialize()
    {
        pinMode(8, INPUT_PULLUP);
        while (digitalRead(8) == HIGH)
            ;  // wait
    }

    // This fires when the initialization times out.
    ISR(TIMER1_OVF_vect)
    {
        TIMSK1 = 0;       // disable timer interrupt
        longjmp(env, 1);  // go to where setjmp() was called
    }

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

        // Configure Timer 1 to fire an interrupt in about 4 seconds.
        TCCR1A = 0;           // reset timer
        TCCR1B = 0;
        TCNT1  = 0;
        TIFR1  = _BV(TOV1);   // clear interrupt flag
        TIMSK1 = _BV(TOIE1);  // enable timer overflow interrupt
        TCCR1B = _BV(CS10)    // clock at F_CPU / 1024
               | _BV(CS12);   // ditto

        // Attempt initialization.
        if (setjmp(env) == 0) {

            // This is the normal program flow.
            Serial.println("Attempting initialization.");
            initialize();
            TIMSK1 = 0;  // disable timer interrupt
            Serial.println("Initialization succeeded.");
        } else {

            // We get here through longjmp() in case of timeout.
            Serial.println("Initialization aborted on timeout.");
        }

        Serial.println("Moving on to the rest of the program.");
    }

    void loop(){}

If pin 8 is grounded, the initialization succeeds and the program prints

<!-- language-all: lang-none -->

    Attempting initialization.
    Initialization succeeded.
    Moving on to the rest of the program.

If pin 8 is left floating, the initialization hangs and the program
prints

    Attempting initialization.
    Initialization aborted on timeout.
    Moving on to the rest of the program.

with a 4 second pause between the first and second lines.

[setjmp]: https://www.nongnu.org/avr-libc/user-manual/group__setjmp.html


body:
I can't upload a program that uses `digitalRead`, `analogRead`, and `Serial.print` on my standalone Arduino, because I get this error:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xbf

However, I have no trouble uploading the blink program to it, which only uses `digitalWrite`, so it has to do something with the methods mentioned at the start of this post.

You can see the diagram below.

[![diagram][1]][1]

  [1]: https://i.stack.imgur.com/uMOQ9.jpg

title: Can only upload certain programs to standalone Arduino

Answers: 0


body:
So I have a project to create a 2 set of traffic lights which would detect a car coming and stopping on the ultrasonic sensor and my code would allow the traffic lights to loop and let the car through. But now I also have to add a pedestrian code in for the pedestrians to press the button, the traffic lights to loop back to red and give 30 seconds of crossing time.

I did the ultrasonic sensor traffic lights code already and some of it seems confusing but somehow works quite well. I'm not familiar with the buttons and looping the traffic lights correctly back to red so I need help to add a pedestrian crossing code to this code:

    // Variables for Station 1 Traffic Light Components
    const int Red1LED = 9;
    const int Yellow1LED = 2;
    const int Green1LED = 3;
    const int GreenArrow = 4;
    #define trigPin 12
    #define echoPin 13
    // Setup Variables for Station 2 Traffic Light Components
    const int Red2LED = 5;
    const int Yellow2LED = 6;
    const int Green2LED = 7;
    const int GreenArrow2 = 8;

    void setup() {

      pinMode(Red1LED, OUTPUT);
      pinMode(Yellow1LED, OUTPUT);
      pinMode(Green1LED, OUTPUT);
      pinMode(GreenArrow, OUTPUT);
      pinMode(Red2LED, OUTPUT);
      pinMode(Yellow2LED, OUTPUT);
      pinMode(Green2LED, OUTPUT);
      pinMode(GreenArrow2, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(trigPin, OUTPUT);
     Serial.begin(9600);
      // Set Initial state of all red LED to HIGH
      digitalWrite (Red1LED, HIGH);
      digitalWrite (Red2LED, HIGH);
    }

    void loop() {
      // put your main code here, to run repeatedly:
     long duration, distance;
      digitalWrite(trigPin, LOW);  // Added this line
      delayMicroseconds(2); // Added this line
      digitalWrite(trigPin, HIGH);
    //  delayMicroseconds(1000); - Removed this line
      //delayMicroseconds(10); // Added this line
      //digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      Serial.println(distance);
      if (distance < 20) {  // This is where the LED On/Off happens
         delay(1000);  //  1 Seconds of Red
      digitalWrite(Green1LED, LOW);  //  Sets Red1 OFF Green ON
      digitalWrite(Yellow1LED, HIGH);
      delay(1000);  // 1 Seconds of Green
      digitalWrite(Yellow1LED, LOW);  //  Sets Green1 OFF Yellow ON
      digitalWrite(Red1LED, HIGH);
      delay(1000);  // 1 Seconds of Yellow
       // Station 2 Timing
      delay(1000);  //  1 Second of Red
      digitalWrite(Red2LED, LOW);
      digitalWrite(GreenArrow2, HIGH);  //  Sets Red2 OFF Green ON
      delay(1000);  // 1 Second of Green
      digitalWrite(GreenArrow2, LOW);
      digitalWrite(Green2LED, HIGH);  //  Sets Green ARROW OFF Yellow ON
      delay(1000);  // 1 Second of Yellow
      digitalWrite(Green2LED, LOW);
      digitalWrite(Yellow2LED, HIGH); // Sets Green 2 OFF YELLOW OFF
      delay(1000);
      digitalWrite(Yellow2LED, LOW);
      digitalWrite(Red2LED, HIGH);

       digitalWrite(Red1LED, LOW);
      digitalWrite(GreenArrow, HIGH);
      delay(1000);
      digitalWrite(GreenArrow, LOW);  //  Sets Yellow1 OFF Red ON
      digitalWrite( Green1LED, HIGH);
    }
      else {
       digitalWrite(Red1LED, LOW); // When the Red condition is met, the Green LED should turn off
      digitalWrite(Red2LED, HIGH);
      digitalWrite(GreenArrow, LOW);
      digitalWrite(Green1LED, HIGH);
      digitalWrite(Yellow1LED, LOW);
      digitalWrite(Yellow2LED, LOW);
      digitalWrite(Green2LED, LOW);
      digitalWrite(GreenArrow2, LOW);

      }
    }

I NEED HELP ASAP PLEASE. Due tomorrow by 12 am. It is extension so I am not that worried if I don't get help by the deadline but if I still do after the deadline I can still learn so don't hesitate to post.

title: How to add a pedestrian button code to a traffic light with ultrasonic sensor?

Answers: 1

body:
Thank you for making it clear that this is course work.
You are asking for help to do the extension, but by your own words you don't understand how the core code works.  I have to be honest I can't be bothered to read the code, it looks horrible.  If I was your teacher I would quit, because I have failed to teach you one of the most fundamental aspects of coding.  "You write it once but it gets read many times", it is ALWAYS worth spending a few minutes making the code look pretty!  (If you teacher can't be bothered to read it, you aren't going to get 100%!)

1. Comments - commenting out code is not the best use for // explaining __why__ you are doing what you are doing is.

2. Its good that you have defined variables to identify you pins, but you have two identical sets of variables, so you could have used an array, a structure or an array of structures.  (These might be more advanced than where you are at the moment, sorry if that's the case).

3. Breaking you code down into bite sized pieces make it more readable.  That start of your loop contains some code that could be in a function called `getDistance()`

4. Turning the lights on and off in the way you are doing it is open to errors.  You could turn the red light on and the green light on.  If you made a class to represent the lights then you could have a function that turned off all of the lights and only turned on the one you wanted.  You wouldn't need to store the state.

Example code (not tested or compiled)

    class Lights
    {
      public:
        enum eLight {Red, Amber, Green, GreenArrow, GreenPedestrian, RedPedestrian, eMaxLight};
        Lights(int[] pins)
        {
          for (int l = 0; l < eMaxLight; ++l)
            pinMode (pins[l], OUTPUT);
        }
        ~Lights()
        {}
        void setLight (eLight newLight)
        {
           for (int l = 0; l < eMaxLight; ++l)
             digitalWrite(m_Light[l], LOW);
           digitalWrite(m_Light[newLight], HIGH);
        }
    }

You probably want to look at a state machine.  List all the possible LEGAL combinations and then create a enum with each of those states in and then write a function that moves from a state to the next legal state, you will need conditionals for has the button been pressed.  This should give you a working system with a pedestrian button that hopefully you understand.


body:
This is my first time posting on this forum. I have tried to format this question properly, but let me know if I need to correct anything. I searched to see if someone else had a similar problem, but let me know if someone has already answered this question.

**Overview:** I am sending pulses to my Arduino, but sometimes one single pulse is interpreted as anywhere from 2 to 30 pulses. But after looking at the pulse on an oscilloscope (see Fig. 1) I am not sure why. When I use a really long wire the ratio of false pulses to legit pulses is about 1 to 1. I shortened the length of the wire and improved the situation, so that only 1 in about every 2,000 pulses is registered as a false pulse.

For one test, I added a capacitor to the short wire situation, but that increased the rise time and made the problem worse. I am currently using `attachinterrupt` and have tested the situation with using both a rising and falling edge. Right now, I mainly want to understand how interrupts work on the Arduino in light of my current problem, although I welcome general advice.

1. When I set the interrupt to the falling edge, why does the Arduino still sometimes count 1 pulse as several? The falling edge in the photo, which is for the really long wire case, lasts about 40 microseconds and appears to have a clean break. The pulse remains low for about 80 milliseconds. Could the falling interrupt trigger during the rise time based off the oscillatory behavior shown in Fig. 1? I smoothed out the signal by adding in a 1 nF capacitor, but the Arduino still counted false pulses. So could the rise time period have anything to do with it? I also have a 10k Ohm pullup resistor connected to the Arduino's 5 V for the pulse path.

I have the relevant code attached below. I have much more code as well, but it deals with saving pulseCounts to the SD Card and uploading electricity consumption files through the cell network.

Cheers.

    //Global Variables
    unsigned long pulse_time = 0;
    unsigned long last_pulse_time = 0;
    byte code = 1; //code let's me see if a false pulse was reported for each
    //SD file

    void setup() {
      attachInterrupt(digitalPinToInterrupt(3), onPulse, RISING);
    }

    void onPulse() {
      pulse_time = millis();
      if ((pulse_time - last_pulse_time) > 50 ) {
        Serial.println("Good Pulse");
        pulseCount++;
        last_pulse_time = pulse_time;
      } else {
        Serial.println("Bad Pulse");
        pulseCount++;
        code = 2;
      }
    }

[![Fig. 1: Pulse With Really Long Wire (Counted as multiple pulses)][1]][1]

  [1]: https://i.stack.imgur.com/GeoaG.jpg

title: Interrupt fires a random number of multiple times for one pulse

Answers: 1

body:
Firstly, unless the processor pin is a Schmitt trigger, increasing capacitance will only make the problem worse by allowing any noise to be interpreted as multiple high-low transitions.  For a CMOS logic input the area around the transition point of 1/2 VDD typical is actually an area of linear operation, not digital.

A Schmitt trigger introduces hysteresis such that when the signal is interpreted as a high level, it must go low by more than the hysteresis to be interpreted as a low level again.  This is accomplished with a bit of positive feedback added to a buffer where the output transition from low to high then pulls the input that much higher or a transition from high to low pulls the input that much lower:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Z6kAG.png

The red line represents the typical CMOS threshold and the green lines represent the thresholds defined by the hysteresis of the Schmitt trigger.  The hysteresis defines the noise immunity of the input.  Most processors have pins that are equipped with a Schmitt trigger or and external device like a 74HC14 can be used.

Another way to deal with this type of noise is to lock out any transitions within the expected pulse-to-pulse transitions:  Once triggered, no more transitions are allowed until the lock out time expires.


body: So for my project, I am measuring heartbeat of a person in a span of 10s. However, as the number of heartbeats may differ for each person, is it wise to use a vector?

title: Which container to use?

Answers: 1

body:
No, you don't want a vector, for a number of reasons:

1. There is no "vector" unless you add extra (unsupported) code.
2. Vectors use dynamic memory. Arduinos don't work well with dynamic memory.
3. It's pointless anyway.

Just allocate an array big enough to contain enough timestamps. In a 10 second period, if you get more than 100 beats, the person you are measuring the heart rate of is most likely in a noticeably "unfortunate" state. That's 600bpm. That's entering panicked mouse territory.

Even with that extreme number of beats an array of 100 32-bit values is only 400 bytes.


body:
My project aims to send `HTTP GET` request to web page(using Arduino UNO and ESP8266-01) then receive response, extract wanted values from response and react with(for example turn on LED1,LED3) then resend led's status to another web page to be inserted in mysql database using `HTTP POST` in order to make sure that Arduino received the command and executed successfully (in an infinitive loop).
Each request `HTTP GET` or `HTTP POST` works fine alone, but when trying to do that in a sequence `HTTP GET` then `HTTP POST` inside the loop I got bad result shown in serial monitor like unknown strange characters.
Here is my `loop` :

    void loop() {
      if (millis() - lastTimeMillis > 40000) {
        lastTimeMillis = millis();
        ESP8266.println("AT+CIPMUX=1");
        delay(1000);
        printResponse();
        ESP8266.println("AT+CIPSTART=4,\"TCP\",\"" + server + "\",80");
        delay(1000);
        printResponse();
        String cmd = "GET /ard/sensor.php HTTP/1.1\r\nHost: localhost";
        ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
        delay(1000);
        ESP8266.println(cmd);
        delay(1000);
        ESP8266.println("");
      }
        if (ESP8266.available()){
        Serial.write(ESP8266.read());
        }
      Value1=(digitalRead (LED_PIN1));
      Value2=(digitalRead (LED_PIN2));
      Value3=(digitalRead (LED_PIN3));
      Value4=(digitalRead (LED_PIN4));
     data = "Value1=" + Value1 + "&Value2=" + Value2 + "&Value3=" + Value3  + "&Value4=" + Value4;
      httppost();
    }

And here is

> httppost()

    void httppost () {

        ESP8266.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");
        if( ESP8266.find("OK")) {
        Serial.println("TCP connection ready");
        }
        String postRequest =
        "POST " + uri + " HTTP/1.0\r\n" +
        "Host: " + server + "\r\n" +
        "Accept: *" + "/" + "*\r\n" +
        "Content-Length: " + data.length() + "\r\n" +
        "Content-Type: application/x-www-form-urlencoded\r\n" +
        "\r\n" + data;
        String sendCmd = "AT+CIPSEND=";
        ESP8266.print(sendCmd);
        ESP8266.println(postRequest.length() );
        delay(5000);
        if(ESP8266.find(">")) { Serial.println("Sending.."); ESP8266.print(postRequest);
        if( ESP8266.find("SEND OK")) { Serial.println("Packet sent");
        while (ESP8266.available()) {
        String tmpResp = ESP8266.readString();
        Serial.println(tmpResp);
        }
        ESP8266.println("AT+CIPCLOSE");
        }
        }
    }

When uploading this code it seems like only `HTTP POST` works fine in a loop while `HTTP GET` having a trouble. So how to make them both work fine in a loop?
Thanks in advance

title: Synchronizing http GET and POST request

Answers: 0


body:
 this is my method

    void mensaje_sms()
    {
      string numero = "777777";  // this is my variable
      SIM900.print("AT+CMGF=1\r");
      delay(100);
          SIM900.println("AT+CMGS=\"591"numero"\"");
    //IM900.println("AT+CMGS=\"59177777777\""); //only in this way does it work
          delay(100);
          SIM900.println("SEND NUMERO VARIABLE RODO");
          delay(100);
          SIM900.println((char)26);
          delay(100);
          SIM900.println();
          delay(5000);
          Serial.println("SMS sent successfully");
        }

***how can I send a variable to println?***

title: how can I send a variable to println?

Answers: 1

body:
Change:

    SIM900.println("AT+CMGS=\"591"numero"\"");

to

    SIM900.print("AT+CMGS=\"591");
    SIM900.print(numero);
    SIM900.println("\"");

Note that only the final call is to `println()` (which just prints a carriage-return character at the end.)


body:
Can a cheap RF(transmitter and receiver) module be used for two way communication, not at the same time of course but for example arduino A sends string to be printed on lcd the arduino B receives it and prints it on lcd, then after some time arduino B sends a temperature data back to arduino A, then arduino prints the temperature data on the serial monitor. All of this while arduino A is connected to a transmitter and arduino B is connected a receiver.
[![these are the RF modules i'm using:][1]][1]

  [1]: https://i.stack.imgur.com/yuCpj.jpg

title: Can a cheap RF module be used for two way communication

Answers: 2

body: Sure it can.  A transmitter is only a transmitter *while it's actively transmitting*.  And you can have as many receivers as you like.

body:
Each device that will ever transmit anything will need a transmitter. Each device that will ever receive anything, needs a receiver. The devices you show in your question are separate receivers and transmitters, so on Arduino A **and** Arduino B, you will need both a receiver and a transmitter in order to have real, two-way communication between them.

Some RF devices are "Transceivers" which have both a receiver and a transmitter in the same module. Some of these can operate "full-duplex", meaning they can receive at the same time they are transmitting other data (Typically each direction is on a different frequency, but not necessarily.) Most cheap ones are half-duplex, meaning the module can only receive or transmit at any one time.

**ADDITIONAL INFORMATION ABOUT RADIOHEAD**

Your comment mentioned the RadioHead library. I was able to find the documentation on the library and see that it supports a wide range of radio chipsets and modules. The cheap ones you note are simple ones that use OOK (on-off-keying) or ASK (amplitude-shift-keying) and don't actually have a protocol. The receiver simply provide a `HIGH` or `LOW` output if it detects a signal on it's designated receive frequency. The transmitter simply oscillates at the transmit frequency when it's input pin sees a `HIGH` value, and stops when it sees a `LOW` value.

The RadioHead `RH_ASK` class deals with these simple transmitters. The documentation is at http://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html#details

This page notes the way to connect both a transmitter and receiver thus:

    Connecting to Arduino

    Most transmitters can be connected to Arduino like this:

    Arduino                         Transmitter
     GND------------------------------GND
     D12------------------------------Data
     5V-------------------------------VCC

    Most receivers can be connected to Arduino like this:

    Arduino                         Receiver
     GND------------------------------GND
     D11------------------------------Data
     5V-------------------------------VCC
                                      SHUT (not connected)
                                      WAKEB (not connected)
                                      GND |
                                      ANT |- connect to your antenna syetem


body:
I need to separate numbers from the text where my string of numbers will always be of length 8:

    string text = "77953505HELLO THIS IS A MESSAGE"; //my string of numbers will always be of length 8

###My result

    string number = "77953505"; //my string of numbers will always be of length 8
    string message = "HELLO THIS IS A MESSAGE";

What operation should I use?

this is the job I'm doing

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

    void loop() {
      if (Serial.available() > 0) {

        String Texto = String(Serial.read());

        String number = Texto.substring(0, 7);
        String message = Texto.substring(8);

        Serial.write(number);
        Serial.write(message);
      }
    }

help me!

title: How do I isolate numbers in text?

Answers: 2

body:
Depends, and probably better to use C strings:

1. If you know the number is always the same amount of characters, use the C function `strncpy`.

2. You can also split on a delimiter (char), with `strtok`, but in your case this is not possible since you don't know the delimiter character.

3. If the number has a variable length, start copying character by character through the string, until you find a character that gives false for the `isdigit` condition and copy the remainder (with strncpy) to the other string.

**Update after the question's edit**

Since the number of text to be copied is know, strncpy can be used with the following prototype:

    char *strncpy(char *dest, const char *src, size_t n)

In your case put the text in a normal text string:

    char text[80]; /* Assuming max length of text */

Copy it where needed:

    strcpy(text, "77953505HELLO THIS IS A MESSAGE");

Note: it can be done in once like this:

    char text[] = "77953505HELLO THIS IS A MESSAGE";

Than you can copy the items by:

    char number[9]; // Add 1 for \0
    char message[81]; // Assuming max length of message;

    strncpy(number, text, 8);
    strncpy(message, &(text[8]), strlen(text) - 8);

(Note not checked with compiler).

Improvements: use instead of 8 a define e.g.

    #define NUMBER_LENGTH 8

    char number[NUMBER_LENGTH + 1];

    strncpy(number, text, NUMBER_LENGTH);
    strncpy(message, &(text[8]), strlen(text) - NUMBER_LENGTH);

You can do similar for MESSAGE LENGTH

    #define MESSAGE_LENGTH 80

Also, another improvement is not to copy the message, but just set the pointer to the correct place:

    char* message = &(text[8]);

message will point to "HELLO THIS IS A MESSAGE"

like below

    "77953505HELLO THIS IS A MESSAGE"
    |        |
    +-- text |
             +-- message

In an Arduino 80 bytes can be a lot of memory, using two buffers cost 160 bytes, and this way you save at least one buffer.

body:
For a fixed length substring the simple arduino-ish way would be to use [String.substring(left_pos, right_pos)][1]

    String number = text.substring(0, 7);
    String message = test.substring(8); // right_pos is optional

This is not necessarily the best option depending on how you intend to use the resulting substring.  Memory is allocated and the content is copied. Requiring at least double the memory (plus some overhead). If memory is tight you may not want to create a String but use char* instead.

  [1]: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/substring/


body:
I have old speaker which I want to use to play sound. I chose to use PWM mode on ATMega328 (which is in turn on Arduino Uno R3 board) in order to do it.

For **signal** on the speaker I chose rectangular wave because it does not require any additional setup. To generate this signal I chose *timer1* because it is easy to change PWM frequency just by changing `ICR1` value. For **duty cycle** I chose 50%. So my program looks as follows:

    #define     CLK_FREQ 16000000   //clock frequency on ATMega328
    #define     PRSCLR   1024       //chosen prescaler of timer1

    //duration of one note
    unsigned int halfDur = 200;
    //number of notes in the melody
    const int notesSize = 32;
    //frequencies of notes in the melody:
    unsigned int notes[notesSize] = { 220, 277, 329, 277, 220, 277, 329, 277,
                                      207, 277, 329, 277, 207, 277, 329, 277,
                                      184, 277, 369, 277, 184, 277, 369, 277,
                                      220, 293, 369, 293, 220, 293, 369, 293 };
    //method to play one note
    void PlayFreq( unsigned int freq );

    void setup()
    {
        //PB1 pin in OUTPUT mode
        DDRB |= ( 1 << DDB1 );

        TCCR1A = 0b0;
        //non-inverting mode of PWM
        TCCR1A |= ( 1 << COM1A1 ) | ( 1 << COM1B1 );
        //Fast mode PWM with ICR1 as TOP:
        TCCR1A |= ( 1 << WGM11 );
        TCCR1B = 0b0;
        TCCR1B |= ( 1 << WGM12 ) | ( 1 << WGM13 );
        //prescaler = 1024
        TCCR1B |= ( 1 << CS12 ) | ( 1 << CS10 );
    }

    void loop()
    {
        for ( int i = 0; i < notesSize; i++ )
        {
            PlayFreq( notes[i] );
            delay( halfDur );
        }
    }

    void PlayFreq( unsigned int freq )
    {
        //claclulate TOP according to note frequency
        ICR1 = CLK_FREQ / PRSCLR / freq - 1;
        //50% duty cycle
        OCR1A = ICR1 / 2;
    }

Problem is *only several first notes are playing and then there is no sound, then again I hear some notes then there is no sound and so on.* It seems that tempo is OK. It just skips some notes. What it could be?

title: Use PWM to play notes on ATMega328

Answers: 0


body:
Arduino Uno with ATMega328P `Processor.analogWrite` is not working properly in if statement. It changes the brightness of the LED as if there wasn't any if statement at all.

There are 2 potentiometers to create an intervall in which to program increases of the LED brightness, starting at 40% of the maximum. When it's lower than the minimum value, the LED is turned off.

    int ledPin = 6;
    int sensorPot = 1; // it's a potentiometer for now
    int maxPot = 7; // potentiometer
    int minPot = 3; // potentiometer
    int fortypercent = 255*0.4;
    int brightness = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(sensorPot, INPUT);
      pinMode(maxPot, INPUT);
      pinMode(minPot, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      int start = analogRead(minPot);
      int maxVal = analogRead(maxPot);
      int sensor = analogRead(sensorPot);
      Serial.println(sensor/4);
      Serial.println(start/4);
      Serial.println(maxVal);
      if(sensor/4 > start/4) {
        analogWrite(ledPin,sensor/4);
      } else if(sensor = baslangic) {
        analogWrite(ledPin,LOW);
      } else if ((start < sensor < maxVal)) {
        brightness = sensor/4 - fortypercent;
        analogWrite(ledPin,brightness);
      } else if (sensor = maxVal) {
        analogWrite(ledPin , 255);
      }
    }

title: AnalogWrite not working in if statement

Answers: 1

body:
**ORIGINAL RESPONSE, BASED ON DIFFERENT CODE**

You are comparing `sensorValue` to see if it's ever less than `minValue`.

However, you have mapped `sensorValue` to range from `0` to `255`, and `minValue` is set at `0`. How can anything from 0-255 be less than zero?

**NEW RESPONSE, BASED ON UPDATED CODE**

One of your `if` statements: `else if(sensor = baslangic)` is not comparing, but assigning `baslangic` to `sensor`. To compare, use `==`.

Your other `if` statement: `else if ((start < sensor < maxval))` is wrong. C++ doesn't work this way. Maybe you want: `if ((start<sensor) && (sensor<maxval))`?

Instead, your statement evaluates like `if ( (start<sensor) < (maxval) )`, which means you are comparing the `TRUE` or `FALSE` of `(start<sensor)` to the `int` that is `maxval`.


body:
I am struggling to implement a custom class that uses the Arduino Extended Database Library (EDB.h). The purpose of my custom class is to manage my application's internal database.

While searching for a solution I found [this][1], which seems very relevant: the code and goal are the same as mine.

But my problem with that Q&A is that I am not able to implement the given solution as I don't fully understand the way it should be written.

For the sake of trying to give the best support for explanation, I upladed the code below. Feel free to explain me how to modify it.

Thank you.

EDIT: Following duplicate comments, I'll try to be more precise in my question.

  [1]: https://arduino.stackexchange.com/questions/14480/pass-a-member-function-pointer-to-a-method-of-a-foreign-class-edb-lib

title: How to implement the Arduino Extended Database library in a custom class?

Answers: 1

body:
It is difficult to answer this question because I'm not sure what you have managed to achieve.  Sorry if some of it seems a bit basic.

Look at Majenko's answer to the question.  If you want to use this EDB class then you need to define two functions:

      void configWriter( unsigned long address, byte data );
      byte configReader( unsigned long address );

You need to be able to access the **single instance** of these functions from anywhere in the code, so the need to have global scope.  When they are global you can assign them to pointers by using the function name and no brackets/parenthesis.  i.e.

    aPtr = configWriter;

So the call to create the EDB instance would be:

     configDB = new EDB( configWriter, configReader );

Now you could create the EDB instance using a class member function.  To do this you have to make the function a `static` member, which means it has no access to the class's data. (in its simplest terms static means there is only one of the things it is referring to) i.e.

    class myEDB
    {
      public:
        static void configWriter( unsigned long address, byte data );
        static byte configReader( unsigned long address );
    ...
    };
    configDB = new EDB( myEDB::configWriter, myEDB::configReader );

Essentially its the same thing, but the code is compartmentalised better and you end up with neater code.

However, if you are only ever going to have one instance of the myEDB class then you can have a static member variable that hold the value of `this`.  You set this value in the class constructor.

    class myEDB
    {
      public:
        static void configWriter( unsigned long address, byte data );
        static byte configReader( unsigned long address );
        myEDB() {pInstance = this;}
      private:
        static myEDB* pInstance = nullptr;
    ...
    };
    configDB = new EDB( myEDB::configWriter, myEDB::configReader );

When configReader or configWriter is called it checks to see if the member `pInstance` has a non null value, if it doesn't then it creates a new instance.  The then use this `pInstance` to access the functions and variables for the instance of the class.  (This is the design pattern for a single instance class or singleton).

**SO** what should **YOU** do?

Start simply, define two global functions that do what you need as per the top of this answer.  If you get stuck, if you need more info feel free to ask or comment.