message:
How do I execute some code at a certain time without RTC module?

I am building a project when I need my arduino to execute some code at two given hours of the day, for example one at 19:00 and another at 06:00. I know that with a RTC module I can do this easily, however how can I do that without a RTC module? I do not want to have to connect my arduino to a computer neither to the internet. It does not also have to be precise, a couple of minutes off would be ok.

My board is an Uno R3.

body:
If you start with the "BlinkWithoutDelay" sketch that comes with the Arduino IDE, you can execute your code alternating between 11 hours and 13 hours.

    // Power up the circuit at exactly 06:00.
    unsigned long delayInterval = 0;
    unsigned long previousMillis = 0;
    bool twoHoursAdded = false;

    void setup(){

    }

    void loop(){

      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis >= delayInterval){

        // previousMillis = currentMillis;

        // Use this "method" of incrementing the previousMillis variable
        // instead of the code used in the BlinkWithoutDelay sketch.
        previousMillis += delayInterval;

        if(twoHoursAdded == false){
          delayInterval = 1000UL * 60UL * 60UL * 13UL;
          twoHoursAdded = true;
        }
        else{
          delayInterval = 1000UL * 60UL * 60UL * 11UL;
          twoHoursAdded = false;
        }

        // Your code here that is run at 06:00 and 19:00.

      }
    }

"Down sides" to using this code.

1. If there is a "power failure", the timing will be off, WAY off until you reboot the Arduino at exactly the right time.
2. You have to power up the Arduino at exactly the right moment for "it's" timing to match your "clock" timing.

If it's within your budget, have a look at the DS3231 modules available on aliexpress.com / ebay.com. They have a lithium battery backup incase of power outage and are really easy to connect to your Arduino using I2C. There are several libraries on Github that simplify using the DS3231 modules.


sender: user

message:
Can I generate 5 sec delay within an interrupt program?

void buttonPressed()
    {
      if(ledOn)
      {
        ledOn = false;
        digitalWrite(13,LOW);
      }else
      {
        ledOn = true;
        digitalWrite(13,HIGH);
      }

      vout=analogRead(sensor);
      vout=(vout*500)/1023;
      tempc=vout; // Storing value in Degree Celsius
      tempf=(vout*1.8)+32; // Converting to Fahrenheit
      lcd.setCursor(0,0);
      lcd.print("ROOM TEMPERATURE");

      lcd.setCursor(0,1);
      lcd.print("C = ");
      lcd.print(tempc);

      lcd.print("  F = ");
      lcd.print(tempf);
      Serial.print("f ");
      Serial.print(tempf);
    }

here is the code of interrupt and i want to monitor the sensor value for about 5second.

sender: assistant

body:
It's bad practice to use a delay within a timer, and 5 seconds is a huge amount of time. Also print statements and possibly lcd print statements I would not advice.

What is better, is to calculate the value, store it in a global variable (vout?). Than set a boolean that a new value has been calculated.

Your main program checks the boolean and does all the print/lcd code.

If you think you might miss values, than create a global array where you add values in your interrupt, and let the main program process the array.


body:
You don't need interrupts for any of that. Your main loop just needs to test the switch, eg.

    void loop ()
      {
      if (digitalRead (button) == HIGH)  // assuming LOW means pressed
         return;

      // read thermocouple here

      // display results

      delay (5000);

      }

---

> I want to print the value of the thermistor on lcd using interrupts and i want the value to stay about 5 secs

You are misusing interrupts in what you are attempting. See [my page about interrupts](http://www.gammon.com.au/interrupts). You simply should **not** be attempting to print or delay inside an interrupt routine. The most you should do is detect that the switch is pressed:

    volatile bool switchIsPressed = false;

    // Interrupt Service Routine (ISR)
    void buttonPressed()
      {
      switchIsPressed = true;
      }  // end of buttonPressed ISR

Now in your main loop you detect that the switch is pressed and take your reading. If you want to do something else "remember" the time you showed the value, like this:

    unsigned long whenTemperatureDisplayed = 0;

    void loop ()
      {
      if (switchIsPressed && whenTemperatureDisplayed == 0)
        {
        // take reading ...
        // display reading ...
        whenTemperatureDisplayed = millis ();  // when we displayed the reading
        switchIsPressed = false;               // ready for next time
        }  // end of if switch was pressed

      if (whenTemperatureDisplayed != 0 &&
          millis () - whenTemperatureDisplayed >= 5000) // 5 seconds are up
        {
        // stop displaying the reading ...
        whenTemperatureDisplayed = 0;
        }  // end of if time is up

      // do other stuff here

      }  // end of loop


body:
Strictly speaking, yes you CAN generate 5 second delay in interrupt. But you really, really should NOT do it.

And if you are going to do it anyway, it could not be easily done with delay(), as Arduino supports only one level of interrupts and delay depends on interrupts enabled. (which can also be cheated away, but it should not be).

The right thing is use interrupt for fast detection of key pressed and manage other parts in loop(), see https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay how to wait in main, while doing other work.

Also using lcd and Serial inside interrupt can bring a lot of problems, especially if you are using it also in loop() (as the key can be pressed anytime and interrupt can well -interrupt- such commands in the loop and then make your output all wrong and possibly crash your program on the way too.)

---

Read http://gammon.com.au/interrupts if you want to know more about interrupts and why your idea is not the best possible way.

Question: Can I hit really hard my thumb with heavy hammer?
Answer: Yes, you can, but you really should not do it. There are much better ways for using thumbs and hammers.


message:
Use ATtiny85 to perform initial config on a Cisco router using its USB console port

We have 200+ brand new Cisco routers that have USB console ports (but not the old RJ45 serial console ports). This is quite frustrating because the routers didn't ship with console cables and Cisco wants to charge $60 for their proprietary USB->RJ45 serial adapters.

When I plug the router in to a computer using a standard USB cable (mini USBb on one end and USB on the other end), it shows up as a virtual com port and allows me to configure the router if I have a VCP driver installed. More specifically it shows up as a "CP2105 Dual USB to UART Bridge Controller". Here's the full `lsusb -v` output for the router:

    Bus 001 Device 005: ID 10c4:ea70 Cygnal Integrated Products, Inc. CP210x UART Bridge
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               2.00
      bDeviceClass            0 (Defined at Interface level)
      bDeviceSubClass         0
      bDeviceProtocol         0
      bMaxPacketSize0        64
      idVendor           0x10c4 Cygnal Integrated Products, Inc.
      idProduct          0xea70 CP210x UART Bridge
      bcdDevice            1.01
      iManufacturer           1 Silicon Labs
      iProduct                2 CP2105 Dual USB to UART Bridge Controller
      iSerial                 5 12345678
      bNumConfigurations      1
      Configuration Descriptor:
        bLength                 9
        bDescriptorType         2
        wTotalLength           55
        bNumInterfaces          2
        bConfigurationValue     1
        iConfiguration          0
        bmAttributes         0x80
          (Bus Powered)
        MaxPower              100mA
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        0
          bAlternateSetting       0
          bNumEndpoints           2
          bInterfaceClass       255 Vendor Specific Class
          bInterfaceSubClass      0
          bInterfaceProtocol      0
          iInterface              3 Enhanced Com Port
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x81  EP 1 IN
            bmAttributes            2
              Transfer Type            Bulk
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0040  1x 64 bytes
            bInterval               0
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x01  EP 1 OUT
            bmAttributes            2
              Transfer Type            Bulk
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0040  1x 64 bytes
            bInterval               0
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        1
          bAlternateSetting       0
          bNumEndpoints           2
          bInterfaceClass       255 Vendor Specific Class
          bInterfaceSubClass      0
          bInterfaceProtocol      0
          iInterface              4 Standard Com Port
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x82  EP 2 IN
            bmAttributes            2
              Transfer Type            Bulk
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0020  1x 32 bytes
            bInterval               0
          Endpoint Descriptor:
            bLength                 7
            bDescriptorType         5
            bEndpointAddress     0x02  EP 2 OUT
            bmAttributes            2
              Transfer Type            Bulk
              Synch Type               None
              Usage Type               Data
            wMaxPacketSize     0x0020  1x 32 bytes
            bInterval               0
    Device Status:     0x0000
      (Bus Powered)

Is it possible to have an ATtiny85 board (eg Digispark) interface with the router via its USB console port to send several commands over the link to perform a perform basic initial config?

body:
It's been a couple of decades since I was programming Cisco routers, firewalls and switches but I appreciate you pain. Like @Gerben says, you need a bigger processor, an ATtiny85 isn't going to be able to hold a lot of config and even the basic configs I used were about 4 to 6KB.

If there is anything in the configs that is different, you idea is going to hit problems.  Are the device names and passwords all the same? In which case you probably want the engineer to be able to set some configuration data in you "programmer", could they set this specialisation data using their mobile phone?

I doubt you will have any problem connecting an "Arduino" via serial (RS232) to a Cisco router. However you now have to encapsulate the serial in "USB", which I don't think will be straight forward for an "Arduino".

I can't think of an option that doesn't require power, but as an alternative to your idea what about using a Raspberry Pi to connect to the router via USB. Stick a touch screen on it and a battery pack to power it.


body:
Can I use a ATtiny85 board (eg Digispark) as a USB CDC device?

**Yes!**

If I have got this right, to be able to communicate with a USB serial device you need to have USB CDC support and if you want it to fake a keyboard/mouse you need HID.

The Digispark have a CDC library https://digistump.com/wiki/digispark/tutorials/digicdc

But it has its **limitations**, take a lot of RAM ( ~2K) so to use a Arduino Leonard/Arduino Micro make more sens and then you could add a SD card as well so you can have your commands easily modified on a SD card.

I have the same idea, but I fetch the config from a TFTP source so my commands needed on the Digispark/Leonardo/Micro is minimal.


message:
Trouble with NRF24L01

I've been trying on and off to try and get my nrf24l01's working for some time and they never seem to work. Right now I'm just trying to turn a led on and off over the radio and it isn't working.

Here's the code for the transmitter
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    #define button 5
    RF24 radio(7, 8); // CE, CSN
    const byte address[6] = "00001";
    boolean buttonState = 0;
    void setup() {
      pinMode(5, INPUT_PULLUP);
      radio.begin();
      radio.openWritingPipe(address);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
    }
    void loop() {

      buttonState = digitalRead(button);
      radio.write(&buttonState, sizeof(buttonState));
    }

And here's the code for the receiver

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    int led = 2;
    RF24 radio(7, 8); // CE, CSN
    boolean buttonState = 0;
    const byte address[6] = "00001";
    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openReadingPipe(0, address);
      radio.setPALevel(RF24_PA_MIN);
      radio.startListening();
    }
    void loop() {
     radio.startListening();
      while (!radio.available());
      radio.read(&buttonState, sizeof(buttonState));
      if (buttonState == HIGH)
      {
        digitalWrite(led, HIGH);
      }
      else
      {
        digitalWrite(led, LOW);
      }
    }

I have the voltage regulator which steps the 5v arduino to 3.3 to the chip so I don't think not having a capacitor (what others recommended) is a problem. I have both radio chips hooked up to arduino nanos.

For the transmitter and receiver I have CE=7,CSN=8, SCK=13, MO=11, and MI=12

I also know that my led is working and the code for my button is working. Is there a problem with my code or is there a chance that my chips are broken even if im using a voltage regulator

body:
Pretty sure your issue is you're not using the capacitor. I used a 10uF capacitor and it works great.

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

You put the capacitor on pins 1 and 2, make sure ground is on pin 1.

The capacitor is to make sure there is enough power being supplied when it needs it. Without the capacitor it causes unreliable communication.

If you have other issues this is a great summary video on using the NRF24L01+ transceivers: https://www.youtube.com/watch?v=kDTJULtFPgE

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


body:
It is not easy to find the problem remotely. Here is what I would do:

0. My first problem have always been connections. I gave up using breadboards and other connectors. Use soldering instead to be sure your circuit is properly connected.

1. Add some Serial.println() in both codes to see what exactly is going to be sent, and what has been received.

2. On the sender code, add a delay(100) to the loop. That would give the module buffers a chance to process.

3. You can improve it more by checking for the button value you read with the old value, and only send the value if the state has changed.


body:
Check these things first:

 - Is your power supply give a constant 3.3V and a minimum of
   0.5A(500mA)?
 - Are you on the right serial baud rate?
 - Is the path from the radio to the Arduino as short as possible?
 - Are your MISO and MOSI wires twined into each other?
 - Try changing your CE to pin 9 and CSN to pin 10.

If none of these things help then, please tell me what library you are using. I had a lot of issues with the RF24 library so maybe try using the NRFLite library.


body:
Interesting. I have been having an issue with nRF24L01's as well so I tried your code (modified to work toggling the transmitter and printing the output). You are possibly getting the same issue as me (https://arduino.stackexchange.com/questions/85874/nrf24l01-continuously-reading-closed-pipe) so I modified your code as follows:
```
void loop() {
 uint8_t pipeNum;
 radio.startListening();
  while (!radio.available(&pipeNum));
  radio.read(&buttonState, sizeof(buttonState));
  if (pipeNum < 2) {
    if (buttonState == HIGH)
    {
      digitalWrite(led, HIGH);
      Serial.println("ON");
    }
    else
    {
      digitalWrite(led, LOW);
      Serial.println("OFF");
    }
  }
}
```
and then it worked for me. PS: I normally add a "while (!Serial);" line after Serial.begin to hold off output until the monitor is established.


message:
Need library help for Arduino USB host shield

Recently Purchased a "TOOGOO(R) T45 USB Host Shield" from Amazon. I attempted to use the "USB Host Shield Library" from Github, but It seems like it might not support this particular shield.

I would really like to learn how to use this shield to interact with my joystick but the only tutorial information I have found to help me with this is from Circuits@home and they seem to be using a specific shield in their development of the code library.

Can anyone point me to a tutorial or Github library that can help me learn to work with this setup?

I'm using an Arduino Uno and a Thrustmaster USB joystick.

Thanks in advance.

UPDATE*

I fixed the initial problem of accessing the HIDDESC report. I now have the report, but the formatting of the report is particularly hard to understand. Using the Circuits@home articles I'm a little lost on how to read the report data I was given. It does not seem to be formatted in the same way as the example. Can anyone help with interpreting my device report?

>Start
>0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
>0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
>0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
>0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
>0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
>0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
>0060: 82 55 00 65 00 55 00 65 00 55 00 C0
>Usage Page Gen Desktop Ctrls(01)
>Usage Game Pad
>Collection Application
>Usage Pointer
>Collection Physical
>Usage X
>Usage Y
>Usage Z
>Usage Undef
>Logical Min(80)
>Logical Max(7F)
>Physical Max(FF00)
>Unit(0000)
>Unit(0000)
>Report Size(08)
>Report Count(04)
>Input(00000010)
>End Collection
>Usage Hat Switch
>Logical Min(01)
>Logical Max(08)
>Physical Min(00)
>Physical Max(3B01)
>Unit(14)
>Report Size(04)
>Report Count(01)
>Input(00000010)
>Usage Page Button(09)
>Usage Min(01)
>Usage Max(04)
>Logical Min(00)
>Logical Max(01)
>Report Size(01)
>Report Count(04)
>Input(00000010)
>Report Count(08)
>Input(00000001)
>Usage Page LEDs(08)
>Usage Slow Blk On Time
>Logical Min(00)
>Logical Max(FF00)
>Physical Min(00)
>Physical Max(FF00)
>Report Size(08)
>Report Count(04)
>Output(10000010)
>Unit Exp(00)
>Unit(00)
>Unit Exp(00)
>Unit(00)
>Unit Exp(00)
>End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
> Hat Switch(00)
> Btn0001
>(00) Btn0002
>(00) Btn0003
>(00) Btn0004
>(00)
>(00)(00)(00)(00)(00)(00)(00)(00)
> Slow Blk On Time
>

body:
The photos on Amazon show a clone of the circuit@home board so the same library should work. You may be running into the problem mentioned in the following page.

https://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html


message:
How to fade out RGB strip?

I have a NodeMCU controlling an RGB strip. I have followed a guide and used this code:

    #include <ESP8266WiFi.h>

    #define redPin 13 //D7 - Red channel
    #define grnPin 12 //D6 - Green channel
    #define bluPin 14 //D5 - Blue channel
    #define max(a,b) ((a)>(b)?(a):(b))

    WiFiServer server(80); //Set server port

    String readString; //String to hold incoming request
    String hexString = "FFFFFF"; //Define initial color here (hex value), 080100 would be a calm warm tone i.e.

    int state;
    int r;
    int g;
    int b;

    float R;
    float G;
    float B;

    int x;
    int V;

    ///// WiFi SETTINGS - Replace with your values /////////////////
    const char* ssid = "xxxxxxx";
    const char* password = "xxxxx";
    IPAddress ip(x,x,x,x);      // set a fixed IP for the NodeMCU
    IPAddress gateway(x,x,x,x);  // Your router IP
    IPAddress subnet(255,255,255,0); // Subnet mask

    void WiFiStart() {
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);
      WiFi.config(ip, gateway, subnet);
      //Set a fixed IP. You can comment this out and set it in your router instead.
      while (WiFi.status() != WL_CONNECTED) {
        delay(100);
        Serial.print("_");
      }
      Serial.println();
      Serial.println("Done");
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      Serial.println("");
      server.begin();
    }

    void allOff() {
      state = 0;
      analogWrite(redPin, 0);
      analogWrite(grnPin, 0);
      analogWrite(bluPin, 0);
    }

    //Write requested hex color to the pins (10-bit PWM)
    void setHex() {
      state = 1;
      long number = (long) strtol( &hexString[0], NULL, 16);
      r = number >> 16;
      g = number >> 8 & 0xFF;
      b = number & 0xFF;
      r = map(r, 0, 255, 0, 1023);  //added for 10-bit PWM
      g = map(g, 0, 255, 0, 1023);  //added for 10-bit PWM
      b = map(b, 0, 255, 0, 1023);  //added for 10-bit PWM
      analogWrite(redPin, (r));
      analogWrite(grnPin, (g));
      analogWrite(bluPin, (b));
    }

    //Compute current brightness value
    void getV() {
      R = roundf(r/10.23);  //for 10bit pwm, was (r/2.55);
      G = roundf(g/10.23);  //for 10bit pwm, was (g/2.55);
      B = roundf(b/10.23);  //for 10bit pwm, was (b/2.55);
      x = max(R,G);
      V = max(x, B);
    }

    //For serial debugging only
    void showValues() {
      Serial.print("Status on/off: ");
      Serial.println(state);
      Serial.print("RGB color: ");
      Serial.print(r);
      Serial.print(".");
      Serial.print(g);
      Serial.print(".");
      Serial.println(b);
      Serial.print("Hex color: ");
      Serial.println(hexString);
      getV();
      Serial.print("Brightness: ");
      Serial.println(V);
      Serial.println("");
    }

    void setup(){
      Serial.begin(9600);
      delay(1);
      pinMode(redPin, OUTPUT);
      pinMode(grnPin, OUTPUT);
      pinMode(bluPin, OUTPUT);
      setHex(); //Set initial color after booting. Value defined above
      WiFi.mode(WIFI_STA);
      WiFiStart();
    }

    void loop() {
      //Reconnect on lost WiFi connection (superfluous - will reconnect anyway)
      WiFiClient client = server.available();
      if (!client) {
        return;
      }
      while(client.connected() && !client.available()) {
        delay(1);
      }
      //Respond on certain Homebridge HTTP requests
      if (client) {
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            if (readString.length() < 100) {
              readString += c;
            }
            if (c == '\n') {
              Serial.print("Request: ");
              Serial.println(readString);
              //Send reponse
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println();

              //On
              if(readString.indexOf("on") >0) {
                setHex();
                showValues();
              }

              //Off
              if(readString.indexOf("off") >0) {
                allOff();
                showValues();
              }

              //Set color
              if(readString.indexOf("set") >0) {
                hexString = "";
                hexString = (readString.substring(9,15));
                setHex();
                showValues();
              }

              //Status on/off
              if(readString.indexOf("status") >0) {
                client.println(state);
              }

              //Status color (hex)
              if(readString.indexOf("color") >0) {
                client.println(hexString);
              }

              //Status brightness (%)
              if(readString.indexOf("bright") >0) {
                getV();
                client.println(V);
              }
              delay(1);
              client.stop();
              readString="";
            }
          }
        }
      }
    }

I have tried to fade out by putting my code below in the `allOff()` function, but it only fades out then comes back white. I would also be interested in fading between different colours in the `setHex()` function.

    void allOff() {
      state = 0;
      for (int i=r; i <= 1023; i--){
      analogWrite(redPin, i);
      analogWrite(grnPin, i);
      analogWrite(bluPin, i);
      }
    }

I would appreciate it if anyone could give me the right way to do this. Thank you.

body:
>     for (int i=r; i <= 1023; i--){
        analogWrite(redPin, i);
        analogWrite(grnPin, i);
        analogWrite(bluPin, i);
        }

[analogWrite](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/) expects a range of 0 to 255, not 0 to 1023.

In any case, why are you starting with the `r` value and decreasing that? What about `b` and `g`?

And why not stop at zero? Your code will reach zero, and then keep going down to -1, -2 etc. I think you mean `i >= 0` not `i <= 1023`.

Let's assume that the previously set values of r, g and b are what you want to fade. Make a loop that decreases them at the same rate:

    for (float fade = 1.0; fade >= 0.0; fade -= 0.01)  // 100 steps
        {
        analogWrite(redPin, (float) r * fade);
        analogWrite(grnPin, (float) g * fade);
        analogWrite(bluPin, (float) b * fade);
        delay (10);  // short delay so you notice it
        }

---

> So how could I apply this code to fade between colours in my setHex function?

Well, fading to black is a special case of fading from one colour to another. To do it in (say) 100 steps you need to work out a "delta" - that is the difference, for each of r/g/b from the initial colour to the new one. So for example if the old red value was 10 and the new red value is 50, then the delta is 40 (50 - 10). So over your 100 steps you need to change the red value by 40 / 100. Using floating point arithmetic lets you handle numbers which aren't integers (in this case 40 / 100 would be 0.4). Example code:

      const float STEPS = 100;

      // save old values of r/g/b
      byte oldR = r;
      byte oldG = g;
      byte oldB = b;

      // calculate new values
      long number = (long) strtol( &hexString[0], NULL, 16);
      r = number >> 16;
      g = number >> 8 & 0xFF;
      b = number & 0xFF;

      // work out deltas
      float deltaR = (r - oldR) / STEPS;
      float deltaG = (g - oldG) / STEPS;
      float deltaB = (b - oldB) / STEPS;

      // fade from old to new
      for (float f = 0; f < STEPS; f++)
        {
        analogWrite(redPin, oldR + (deltaR * f));
        analogWrite(grnPin, oldG + (deltaG * f));
        analogWrite(bluPin, oldB + (deltaB * f));
        delay (10);
        } // end of for


message:
Arduino-compatible micro-controller with both I2C and CAN

I am looking for a controller that works with Arduino (i.e. there is official or third-party support for the controller in the Arduino IDE and core libs) and has both built-in CAN and I2C buses. I was looking at the ATMega automotive series (16M1, 32M1, 64M1, 32C1, 64C1) but it does not mention I2C/TWI in the datasheet at all.

(I know I can bitbang I2C, I know there is MCP2515 for CAN over SPI.)

Thanks!

**EDIT:** The application in mind is a bridge between a few I2C sensors and CAN, no complex logic. High performance is not necessary, plus it will drive costs upwards.

body:
Many options come to mind:

* Bluepill board
* Literally any board with I2C and CAN buses from the STM32 series, as searchable on their website (https://my.st.com/content/my_st_com/en/products/microcontrollers.html)
* ESP32

A Bluebill board is programmable with mbed, STM32HAL (CubeMX) and Arduino, all of which have either CAN libraries for the CAN peripheral or have it even built-in in the OS (mbedos).

The Bluepill board is extremely low cost ($1.81 with free shipping from aliexpress) and features an STM32F103C8 microcontroller with 128kB Flash and 20kB RAM. Its peripherals include two I2C and one CAN bus.

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

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

Infos & Datasheet: http://www.st.com/en/microcontrollers/stm32f103c8.html, http://wiki.stm32duino.com/index.php?title=Blue_Pill

For flashing and debugging the chip you should have one cheap ST-Linkv2 clone (~3$ from china).

For programming environments you can use:

* Arduino IDE (STM32Duino Arduino Core for STM32F1/F3/F4 chips: http://wiki.stm32duino.com/index.php?title=Boards_Manager_package)
* PlatformIO, more general purpose and more powerful (https://platformio.org:443/boards?count=15&filter[mcu]=STM32F103C&page=1&sorting[name]=asc)

As frameworks you can use:

* Arduino (see above)
* ARM mbedos (builds upon STM32HAL, natively supported by PlatformIO)
* STM32HAL (e.g. with project files for an IDE generated by STM32CubeMX)

Documentation references:

* https://os.mbed.com/docs/v5.8/reference/can.html
* https://www.st.com/resource/en/user_manual/dm00154093.pdf (Chapter 8)
* https://github.com/Locoduino/Commanders

8 Bit microcontrollers from STM8AF series have a few micros with 1 I2C and 1 CAN bus: See http://www.st.com/en/microcontrollers/stm8af-series.html?querycriteria=productId=SS1583

[![enter image description here][3]][3]

Ready buyable evaluation board: http://www.st.com/en/evaluation-tools/stm8a-discovery.html (you want the STM8AF5288 one)

The toolchain changes then, of course. See [https://my.st.com/content/my_st_com/en/extended-query.html?querycriteria=productId=LN1759$$associatedTo=SS1584][4]

  [1]: https://i.stack.imgur.com/M0LlQ.png
  [2]: https://i.stack.imgur.com/yjzq0.png
  [3]: https://i.stack.imgur.com/QZpvC.png
  [4]: https://my.st.com/content/my_st_com/en/extended-query.html?querycriteria=productId=LN1759$$associatedTo=SS1584


message:
Why do you need to shift bits when reading from an analog sensor?

I was playing around with some analog grove sensors and looking at examples (https://github.com/DexterInd/GrovePi/blob/master/Software/Go/grovepi/grovepi.go - this specific example is in go and for raspberry pi, but it's the same on arduino) I realised that you need to "(int(val[1]) << 8) | int(val[2])" before getting the result.

Why is that so? Why do the second 8 bits need to be left shifted by 8 and why is there then an OR with the third group of bits?

body:
You read bytes in the order:

- Most significant byte   (let's call this msb)
- Least significant byte  (let's call this lsb)

The formula to get to real value is msb * 256 + lsb
256 because this is the value of the maximum value of one byte, + 1. which is bits (2 ^ 8 = 256).

However, a CPU is normally faster in bit operations than in arithmetic operations.

    Assume msb is 10101010
    and lsb is    11001100

Now below is the table with the calculation order

    sensor value             msb         lsb
    00000000 00000000        10101010    11001100
    00000000 10101010                                sensor value = msb
    10101010 00000000                                msb << 8, or msb * 256
    10101010 11001100                                (msb << 8) + lsb, or (msb * 256) + lsb

Actually I would expect a cast to an unsigned byte type (8 bits). However, if the values msb or lsb would be floating points/doubles, than the remainder will be removed, leaving an integer (whole) number.


message:
Uno R3 connected via Ethernet shield becomes unreachable after a few minutes

I'm setting up an Elegoo Uno R3 with a Seeed 5200 ethernet shield to monitor water flow and temperature. It needs to run unattended for weeks at time (being called several times a day by a remote script).

I'm normally able to send and receive UDP packets for a few minutes when I've just reset/power-cycled the Arduino. After that, it stops responding to UDP messages. By adding some serial output I can see that it hangs unpredictably at different parts of loop(). Sometimes it seems that physically shifting the device will get it to wake up; or it will wake up on its own after a minute or two. Most of the time it works until it quits, then doesn't work until I reset it.

It does respond to ping while it's otherwise unresponsive.

Is there anything wrong with my code? This is my first Arduino project. Otherwise could it be a hardware problem? If I buy another, I'll buy a genuine Arduino. Is Seeed a reliable source for the ethernet shield?

(By the way--I think it's safe to disregard the PACKETLEN thing, which is a leftover artifact. In the end it's unnecessary to read the incoming message anyway, so the packetBuffer array is superfluous but doesn't seem to change anything one way or another.)

Thanks in advance. Best wishes,
Dan

    #include <SPI.h>
    #include <EthernetV2_0.h>

    #define PACKETLEN 48

    //Flow and temp globals
    byte sensorInterrupt = 0;  // 0 = digital pin 2
    byte flowPin       = 2;
    byte tempPin = 0;

    float calibrationFactor = 45; // we're going to measure for 10s intervals
    float minFlow = 270;          // minimum 6 L/min, measured for 10 s
    volatile byte pulseCount;
    unsigned long startTime, timeDelta;

    int tempReading;
    float tempVoltage;
    float temperature;

    //Communication globals
    IPAddress ip(xxx, xxx, xxx, xxx);
    byte mac[] = {
      0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx
    };
    EthernetUDP Udp;

    unsigned int localPort = xxxx;
    char packetBuffer[PACKETLEN+1];  //buffer to hold incoming packet,

    int packetSize;
    byte flowOk, tempOk;
    IPAddress remoteIP;
    unsigned int remotePort;

    void pulseCounter()
    {
      pulseCount++;
    }

    void setup()
    {

      //Serial.begin(9600);
      Ethernet.begin(mac,ip);
      Udp.begin(localPort);

      pinMode(flowPin, INPUT);
      digitalWrite(flowPin, HIGH);

      // attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
    }

    void loop()
    {

        delay(2000);

        if(packetSize = Udp.parsePacket())
        {
            remoteIP = Udp.remoteIP();
            remotePort = Udp.remotePort();

            //Measure the flow for 10 seconds
            flowOk = 0;
            pulseCount = 0;
            startTime = millis();
            attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
            while((timeDelta = millis() - startTime) <= 10000) ;
            detachInterrupt(sensorInterrupt);
            if (pulseCount >= minFlow)
                flowOk = 1;

            //Check the temperature
            tempOk = 0;
            tempReading = analogRead(tempPin);
            tempVoltage = tempReading * 5.0 / 1024.0;
            temperature = (tempVoltage - 0.5) * 100;
            if (temperature < 35.0)
                tempOk = 1;

            Udp.beginPacket(remoteIP, remotePort);
            if (flowOk && tempOk)
                Udp.write("Ok");
            else
                Udp.write("Not ok");
            Udp.endPacket();
        }

    }

body:
I don't know where my compiler was finding the UDP code in the above sketch, because it's not in EthernetV2_0.h. The problem was fixed by adding the following lines, from the example sketch UDPSendReceiveString written by Michael Margolis and included with the Ethernet_Shield_W5200 library:

    #include <EthernetUdpV2_0.h>

    #define SDCARD_CS 4

    void setup():
        //...//
        pinMode(SDCARD_CS, OUTPUT);
        digitalWrite(SDCARD_CS, HIGH);


message:
NodeMCU successfully uploaded sketch but it does not work from Arduino IDE

NodeMCU successfully compiled and uploaded a simple blink sketch on board, no errors at all, but the LED stays on constantly and does not blink. Also I have checked the power is enough. I have checked this with all pins but the red LED only stays on and doesn't blink. I have no idea what could have gone wrong. And how to fix this?

body:
Fixed it....
turns out that in the tools, the board was selected to be NodeMCU 0.9
when it should actually have been NodeMCU 1.0
so i just changed it to NodeMCU 1.0 and it worked!


message:
Merge two Arduino projects (change build process)

I'm working on a big software project consisting of several Arduino sketches.
I have one Arduino project providing general functionality, such as TCP/IP communication, parsing queries, handling errors, and some more. This part is fundamental for several devices, which extend this fundamental part by specific functionalities. E.g. one device needs to read temperature sensors and manage a loop to control the temperature and has its own sketch. Another device is driving a servo motor and measuring sun light and also has its own sketch. (And there are some other devices with specific sketches.)

I want to maintain the fundamental part in ONE sketch and the specific parts of the different devices each in OTHER sketches, so I can code both separately.

The problem is, those specific parts can not be compiled if not merged with the fundamental sketch, as this provides basic functions. So if I compile any specific part, I want the fundamental part to be added to the specific one and afterwards the whole code should be compiled.

Is there a way to manipulate the makefile used by the Arduino IDE? Then I could use whatever I want (bash or Python script) to merge in the desired way first.

body:
Assuming that each separate hardware device (ESP32?) must run self-contained with both the fundamental parts, and the use-specific parts, then you would do well to separate out the fundamentals into a library, and then include that library in each use-specific sketch.

The [Adafruit Unified Sensor Driver][1] would be one project that shows this. Each of the sensor libraries based on this driver must `#include` the unified sensor driver library, and that provides some basic properties and interfaces, while each sensor's individual code handles the specifics for communicating to/from that particular unique hardware device.

  [1]: https://github.com/adafruit/Adafruit_Sensor


body:
In my opinion, you don't need another Arduino. Most of the time, Arduino is fast enough to handle all the things you mentioned. It highly depends on your programming skills. For example, don't make your Arduino do nothing while waiting for a communication to complete and so on. The techniques you require are:

1) No delay functions at all in your programming. Go Arduino's examples and look for 'blink without delay' sketch.

2) Organize your programming. Make use of creating your own functions. Your void loop() should be a to-do-list.


message:
Will I destroy my Arduino Uno if I connect a 600-mA DC motor to the +5V pin?

I know that if I connect an electronic component that consumes more than 20 mA, my Arduino Uno will be destroyed. I don't know if that refers only to digital pins or refers to +5V pins too.

body:
If you connect a motor to the +5V pin, it will always be on. Is that what you want?

The +5V pin on the Arduino Uno gets power from the on-board 5V linear voltage regulator **OR** from the USB jack, and thus the host computer. This allows the board to have a fixed 5V source even when applying 9 or 12 V to the barrel jack or the RAW pin, and to be powered by a USB host.

When you draw 600mA for your motor (ignoring what the other devices on the Arduino draw), you are drawing 600mA from the regulator's output. You are also drawing 600mA from the regulator's input, which supplies a higher voltage. Excess power is dissipated as heat. 5V * 600mA is 3W. If you power the board from 9V, you are discarding [(9V-5V)=4V] * 600mA = 2.4W of power. 2.4 Watts is probably too much for the little regulator to handle. It will get too hot and burn up.

If you do this, you will *probably* be able to still operate it powered by the USB port, as only the 5V regulator is damaged.

However, if you try to draw 600mA and power the board from a USB device like a computer, you may burn up the computer's USB chip and make it useless forever.

For high-power devices like motors, always power them from a sufficient external supply of the appropriate voltage. Be sure to connect the ground of the external power supply to the GND pin of the Arduino. Don't send high current through the Arduino board. The Arduino should handle *signals*, not power.

Use the signals to activate switching devices like MOSFETs, which are designed to control higher currents by low-power signals.


body:
No, it shouldn't destroy it.  Although you are getting close to the current limit.

The on-board regulator (depending on the board version) can supply up to about 800mA to 1A.

However, the actual maximum current is dependent on the voltage you are supplying the board with - the higher the voltage the hotter the regulator gets and the lower the current that it can supply without shutting down (or burning out).

As long as you run the board from the lower end of the input voltage (7V, say) it should be fine.

It would be better, though, to use an external power supply for the motor anyway, just to reduce the amount of heat the regulator will pump out.

Powering from the USB won't be possible, however: the USB port has a 500mA fuse in the supply circuit.


message:
Can't upload to my Nano after updating to Arduino AVR Boards 1.6.21

I recently had the Arduino IDE notify me of available boards updates, so I updated. Since then when I try to upload to my Nanos it fails:

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

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

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I installed Arduino IDE 1.0.6 and found that I can upload to all my Nanos with that IDE version.

How can I upload to my Nanos using Arduino AVR Boards 1.6.21?

body:
Arduino recently changed the bootloader they ship on their official Nano boards. This required a [change in the hardware definition for the Nano](https://github.com/arduino/ArduinoCore-avr/commit/1b14cc07331268e95eddcce2cc67e29ed667e62f), which was the sole reason for the Arduino AVR Boards 1.6.21 release.

The new Nano hardware definition is not backwards compatible with Nanos that use the previous ATmegaBOOT bootloader. For this reason a new menu option was added: **Tools > Processor > ATmega328P (Old Bootloader)**. If you select that option the uploads to your Nanos will work again.


body: Check weather your arduino nano is Chinese having CH340G chip. If the chip is there then you have to install CH340G drivers in your computer..


body:
I also had similar issues after upgrading my Ubuntu system.

Selecting 3.3V for the Mini board did the trick, For the Nano, the old loader worked.


message:
Detect button press inside a for() cycle

I was working on a project with an LED strip, where I'd like to cycle through various effects with just a press of a button. The problem is that I don't know how to detect the press of the button to change effect while in for() cycling colors to have a rainbow effect (so it's a multitasking problem, I think).
Could you help me? :)

    #include <Adafruit_NeoPixel.h>

    #define pin 5
    #define led 15
    #define button 7
    Adafruit_NeoPixel strip = Adafruit_NeoPixel (led,pin,NEO_RGB+NEO_KHZ800);

    int doggo=0;

    void setup(){
     strip.begin();
     pinMode(button,INPUT);
    }
    void loop(){

     int buttonVal=digitalRead(button);

     if(buttonVal==HIGH){
      doggo++;
      delay(300);
     }
     if (doggo>2){
      doggo=0;
     }
     while (doggo==0){
      //whole strip red
      for (int i=0;i<led;i++){
       strip.setPixelColor(i,255,0,0);
       strip.show();
      }
     }
     while (doggo==1){
      //rainbow effect
      uint16_t i, j;
      int rainbowSpeed=10;
      for(j=0; j<256*5; j++) {

       for(i=0; i< strip.numPixels(); i++) {

        strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        strip.show();

       }

      }

     delay(rainbowSpeed);

     }

     while (doggo==2){
      //whole strip blue
      for (int i=0;i<led;i++){
       strip.setPixelColor(i,0,0,255);
       strip.show();
      }
     }

    }

    uint32_t Wheel(byte WheelPos) {
     WheelPos = 255 - WheelPos;

     if(WheelPos < 85) {
      return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
     }
     if(WheelPos < 170) {
      WheelPos -= 85;
       return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
     }
     WheelPos -= 170;
     return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
    }

body:
You should use a hardware interrupt. Depending on your microcontroller, you have different pins available.

[Here is a reference for more details and syntax][1]

  [1]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/


body:
You could use the [Bounce2][1] library.

Call the update() method regularly and then check the state with read().

e.g.

    for (...) {
      button.update();
      if (button.read() == HIGH) {
         //change pattern
         break;
      }
      // Do strip stuff.
    }

As an added bonus the bounce library will debounce your button.

  [1]: https://github.com/thomasfredericks/Bounce2/wiki


body:
I finally solved!

I tried the Bounce2 library, but it acted really strange (the effects passed from the first one, then the third one, then the first one again for a fraction of second and automatically to the second one, plus other things :/ )

It looks like I just needed to add a normal digitalRead inside for() and a return, I don't usually make those errors xD


message:
One of the LEDs on my Arduino is very dim

I made a vibration sensor using an Arduino. It is connected to an Android app. When the start button is pressed on the app, a red light LED turns on (stand by), and after 2 - 5 seconds, the red LED turns off and a green LED turns on (meaning the system is ready). The green LED turns off if the sensor detects a vibration. The green LED works perfectly. However, the red LED is always dim. I've tried testing the red LED separately, it works fine. I've tried changing the pin it's connected to, it's still dim. I've included my code below if it helps.

Thanks in advance.

    int ledPin = 13;
    int ledPin2 = 9;
    int EP = 7;
    int cal = 500;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(EP, INPUT); //set EP input for measurement
      Serial.begin(9600); //init serial 9600
    }

    void loop() {
      if (Serial.available()) {
        char c = Serial.read();
        if (c == '1') {
          cal = 100;
        }
        if (c == '2') {
          cal = 200;
        }
        if (c == '3') {
          cal = 300;
        }
        if (c == '4') {
          cal = 400;
        }
        if (c == '5') {
          cal = 500;
        }
        if (c == '6') {
          cal = 600;
        }
        if (c == '7') {
          cal = 700;
        }
        if (c == '8') {
          cal = 800;
        }
        if (c == '9') {
          cal = 900;
        }
        if (c == '0') {
          int randm = random(2, 6);
          int x = randm * 1000;
          digitalWrite(ledPin2, HIGH);
          delay(x);
          unsigned int tm = millis();
          digitalWrite(ledPin, HIGH);
          digitalWrite(ledPin2, LOW);
          while (1) {
            long measurement = TP_init();
            char br = Serial.read();
            if (br == 'x') {
              break;
            }
            if (measurement > cal) {
              digitalWrite(ledPin, LOW);
              unsigned int out = millis() - tm;
              unsigned char i = out;
              Serial.print(out);
              break;
            }
          }
        }
      }
    }

    long TP_init() {
      delay(0);
      long measurement = pulseIn (EP, HIGH);
      //wait for the pin to get HIGH and returns measurement
      return measurement;
    }

body:
You need to add this line for the other LED pin:

    pinMode(ledPin2, OUTPUT);


body:
You need this same line for the other LED pin:

pinMode(ledPin**2**, OUTPUT);


message:
Problem using Optiga Trust X I2C

Did someone ever used the Infineon Optiga Trust X module with Arduino using any I2C library ?

Here is the [technical documentation][1] of the Trust X module.

I'm trying to get the I2C_STATE register data but I don't receive anything after the Wire.requestFrom().

I also tried with the [DSS Circuits I2C Master Library][2], same results.

Thanks

Full code :

    #include <Wire.h>
    #define PIN_RST 8
    #define PIN_VDD 9

    void setup() {
      pinMode(PIN_RST, OUTPUT);
      pinMode(PIN_VDD, OUTPUT);
      digitalWrite(PIN_RST,LOW);
      digitalWrite(PIN_VDD,LOW);

      Serial.begin(115200);
      delay(2000);
      Wire.begin(); // join i2c bus (address optional for master)

      digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
      digitalWrite(PIN_RST,HIGH);

      delay(15);  // startup min delay
    }

    long val = 9999;

    void loop() {
      Wire.beginTransmission(48); // transmit to device #48 (0x30)
      Wire.write(byte(0x82));            // sends instruction byte
      Wire.endTransmission();     // stop transmitting

      Wire.requestFrom(48, 4);
      while(Wire.available()==0){}

      val = Wire.read(); // Reads the data from the register
      Serial.print("val = ");
      Serial.println(val);

      delay(5000);

    }

  [1]: https://www.infineon.com/dgdl/Infineon-OPTIGA TRUST X SLS 32AIA-DS-v12_17-EN.pdf?fileId=5546d462602a9dc801606f1c2ebb7fe9
  [2]: http://dsscircuits.com/articles/arduino-i2c-master-library

body:
So I finally succeeded to read a register value. I don't really know where was the problem. Here is the code if it can help someone (the scanner still does not work btw) :

    #include <Wire.h>

    #define DEVICE_ADDRESS 0x30

    #define PIN_RST 8
    #define PIN_VDD 9

    void printOutput(byte *out, int out_len){
       int y=0;
      Serial.print("out = ");
      for(;y<out_len;y++){
        Serial.print(out[y],HEX);
      }
      Serial.println("");
    }

    void coldReset(){
      pinMode(PIN_RST, OUTPUT);
      pinMode(PIN_VDD, OUTPUT);
      digitalWrite(PIN_VDD,LOW);
      digitalWrite(PIN_RST,LOW);
      delayMicroseconds(2000);
      digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
      digitalWrite(PIN_RST,HIGH);
    }

    int I2C_get(byte reg, byte *out, int out_len){
      int i=0, nbSend=0, nbAvailable=0, ret=0;
      Wire.beginTransmission(DEVICE_ADDRESS); // transmit to device #48 (0x30)
      nbSend=Wire.write(reg);            // sends instruction byte
      Wire.endTransmission();     // stop transmitting
    //  Serial.print("nb send = ");
    //  Serial.println(nbSend);

      delayMicroseconds(50);
      Wire.requestFrom(DEVICE_ADDRESS, out_len);

    //  nbAvailable=Wire.available();
    //  Serial.print("nb available = ");
    //  Serial.println(nbAvailable);

      if(Wire.available()==out_len){
        for(;i<out_len;i++){
          out[i]=Wire.read();
        }
      }
      else ret=-1;

      return ret;
    }

    void setup() {

      Serial.begin(115200);
    //  Wire.begin(); // join i2c bus (address optional for master)
    //  coldReset();
    //  delayMicroseconds(15000); // Startup time
    }

    void loop() {
      int y=0, out_len, ret;
      byte res1[]={0x00,0x00,0x00,0x00};

      Wire.begin(); // join i2c bus (address optional for master)
      Wire.setClock(400000);
      coldReset();
      delayMicroseconds(15000); // Startup time

      out_len=4;
      ret=I2C_get(byte(0x84),res1,out_len);
      if(ret!=-1){
        printOutput(res1,out_len);
      }
      else{
        Serial.println("Error I2C_get");
      }

      Wire.end();
      Serial.println("");
      delay(5000);
    }


body:
It looks like the answer is a bit delayed, but if somebody else sees this issue once again.

It might not be directly visible in the [documentation](https://github.com/Infineon/optiga-trust-m/tree/trust_m1_m3/documents) (Datasheet or Solution Reference Manual), but here what you can find in the Trust M Datasheet Annex B (Section 11):
"The OPTIGA™ Trust M will not acknowledge the slave address sent by a host if it is either busy or in idle state. Hence the host must retry or repeat the transaction until it is successful or timed out for 100 milliseconds (extreme case).
The specified guard time must be applied between each attempt of write / read operation by the Host I2C driver."

The chip always goes into an idle or sleep state if no command is issued in a defined time period, unless a Sleep Activation Delay isn't changed.


message:
No Matching Function for call to Ultrasonic:Ultrasonic(int,int)

Good Day! I am trying to code the distance of Ultrasonic Sensor but the problem is it gives me this error. Any idea? Please help.

    #include <Ultrasonic.h>

    // HR-SC04 SENSOR
    #define TRIGGER_PIN   5
    #define ECHO_PIN      6

    Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);

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

    // Global variables
    int lastDistance = 0;
    int thisDistance = 0;

    void loop()
    {
      // Copy over last distance
      lastDistance = thisDistance;

      // Get new this distance
      thisDistance = ultrasonic.Ranging(CM);

      if (outlierCheck(lastDistance, thisDistance)) {
        Serial.println("Outlier found: " + String(thisDistance));
      } else {
        Serial.println(String(thisDistance) + " cm");
      }

      delay(10);
    }

    // Check for significant jumps and outliers in sensor reading
    bool outlierCheck(int lastDistance, int thisDistance) {

      // if the difference between measures is greater then 20cm, outlier found
      if ((lastDistance - thisDistance) > 20) {
        return true;
      } else {
        return false;
      }
    }
[![enter image description here][1]][1]

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

body:
You are very likely to have confused the libraries.

When using your code with the library at https://github.com/JRodrigoTech/Ultrasonic-HC-SR04, the code compiles perfectly fine. The constructors match up with your code.

    //Constructor 1
    Ultrasonic(int TP, int EP);
    //Constructor 2
    Ultrasonic(int TP, int EP, long TO);
    //methods.. (used in your source)
    long Timing();
    long Ranging(int sys);

I think you have installed this Ultrasonic library: https://github.com/ErickSimoes/Ultrasonic. It has the same header file and class name but the class is constructed differently

    //Constructor 1
    Ultrasonic(uint8_t sigPin) : Ultrasonic(sigPin, sigPin) {};
    //Constructor 2
    Ultrasonic(uint8_t trigPin, uint8_t echoPin, unsigned long timeOut = 20000UL);
    //Note that a constructor with only 2 arguments is not directly visible

You should go into the Arduino IDE and uninstall your current "Ultrasonic" library from the library manager. Then download the zip file from the first given github repository and add that ZIP file to your libraries.

Alternatively of course, you can use the second library and its correct example code.

Also note that your Arduino IDE 1.0.6 is extremely outdated, current one is [1.8.5][1]

  [1]: https://www.arduino.cc/en/main/software


message:
How to get location of the hand indoors

I made a glove that tracks the positions of the fingers, but I don't know how to get the location of the hand relative to the person using them. Any suggestions? It should be quite accurate but I would really like to make even a rough prototype of it.

Ps. I'm using a Arduino Nano (atmega328p) to send and process the positions of the finger to a Java application through serial if you wanted to know.

body:
The only way to check the relative position is, first to define, what is the absolute position of a person, is it his other hand, his heart, his head, his foot?

When you defined the absolute position of the person, then you need to use a sensor at that absolute position that can measure the current position, e.g. GPS (if outside), but this is not accurate.

You also can use a gyroscope or device similar to what you use for the glove. When you initially keep them together you now the relative position (around 0.0). Than you can track movement differences of both the glove and the absolute position, send it to the glove (or vice versa) and calculate the difference. There might be calibration issues.

Another way is to use a camera and continueously check for a line of sight signal (IR, led), but this also can have issues (like distance measurement, what if there is no line of sight etc).


message:
Get UUID from Arduino Nano, ATmega328

I need to know how to obtain the UUID from an Arduino Nano ATmega328 for a project.

body:
You don't have a UUID.

You only get a UUID in the USB-enabled chips, like the ATMega32U4.

You would have to create your own UUID and store it in EEPROM, or embed it within your sketch.


message:
Is it possible to use LCD (the 16 pins) without potentiometer?

look, I don't have any potentiometer lying around, and I don't have any variable resistor.
So is it possible to instead use a fixed resistor for the LCD display ?

body:
Sure. You can use two resistors in series to be a "fixed value" potentiometer.

The "wiper" of the potentiometer is the junction between the two resistors.

I can't tell you what values to use, so you'll have to experiment. You want them to add up to somewhere in the tens of kilo-ohms though, ideally, though the value isn't that critical - it's the ratio between the two values that is of interest, and it's that which gives you your contrast setting.


message:
this code is not printing anything on the serial moniter. the code is in setup()

Serial.println("CLEARDATA"); //clears up any data left from previous projects
    Serial.println("LABEL,time,load reading(gm),microwave output,CO sensor,sound data,magnetic sensor "); //always write LABEL, so excel knows the next things will be the names of the columns (instead of Acolumn you could write Time for instance)
    Serial.println("RESETTIMER"); //resets timer to 0

    //pinMode(AOUTpin, INPUT);//sets the pin as an input to the arduino
    // pinMode(ledPin, OUTPUT);//sets the pin as an output of the arduino
    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");

body:
There can be different reasons, among:

- The speed of the serial port does not match with the serial 'monitor'
- The speed of the serial port is not set at all (can cause first problem)


body:
I don't see this before the print statements:
Serial.begin(9600); // or some other speed

That will prevent anything from printing.


message:
Sending Data from ESP8266 to PHP

I want to display the RFID tag value to a html file.

I am using ESP8266 ESP-01 module, EM-18 Reader Module, Arduino Uno and Xampp for hosting PHP.

Right now, I am getting a value of "255" in Arduino whenever I scan a RFID tag. But I am supposed to get the 12-digit alphanumeric RFID tag value.

I have attached the Arduino and also the output screen of the Serial Monitor.

I have my college submission next week so it's urgent. Any help would be appreciated.

    #include "SoftwareSerial.h"
    String ssid ="Home";
    String password="****";
    SoftwareSerial esp(2, 3);// RX, TX
    String data;
    String server = "192.168.0.182"; // www.example.com
    String uri = "/testget.php";// our example is /esppost.php
    int DHpin = 0;//sensor pin
    byte dat [12];
    String tag;

    void setup() {
      pinMode (DHpin, OUTPUT);
      esp.begin(9600);
      Serial.begin(9600);
      reset();
      connectWifi();
    }

    //reset the esp8266 module

    void reset() {
      esp.println("AT+RST");
      delay(1000);
      if(esp.find("OK") )
        Serial.println("Module Reset");
    }

    //connect to your wifi network

    void connectWifi() {
      String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
      esp.println(cmd);
      delay(4000);
      /*
      if(esp.find("OK")) {
        Serial.println("Connected!");
      }
      else {
        connectWifi();
        Serial.println("Cannot connect to wifi"); }*/
    }

    byte read_data () {
      byte data;
      for (int i = 0; i < 13; i ++) {
        if (digitalRead (DHpin) == LOW) {
          while (digitalRead (DHpin) == LOW); // wait for 50us
            delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'
          if (digitalRead (DHpin) == HIGH)
            data |= (1 << (12-i)); // high front and low in the post
          while (digitalRead (DHpin) == HIGH);
    // data '1 ', wait for the next one receiver
        }
      }
      return data;
    }

    void start_test () {
      digitalWrite (DHpin, LOW); // bus down, send start signal
      delay (30); // delay greater than 18ms, so DHT11 start signal can be detected
      digitalWrite (DHpin, HIGH);
      delayMicroseconds (40); // Wait for DHT11 response
      pinMode (DHpin, INPUT);
      while (digitalRead (DHpin) == HIGH);
        delayMicroseconds (80);
      // DHT11 response, pulled the bus 80us
      if (digitalRead (DHpin) == LOW);
        delayMicroseconds (80);
      // DHT11 80us after the bus pulled to start sending data
      for (int i = 0; i < 13; i ++)
        // receive tag value data, the parity bit is not considered
        dat[i] = read_data ();
      pinMode (DHpin, OUTPUT);
      digitalWrite (DHpin, HIGH);
      // send data once after releasing the bus, wait for the host to open the next Start signal
    }

    void loop () {
      start_test ();
      // convert the bit data to string form
      tag= String(dat[12]);
      data = "tag=" + tag;// data sent must be under this form //name1=value1&name2=value2.
      Serial.println(data);
      httppost();
      delay(1000);
    }

    void httppost () {
      esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
      if( esp.find("OK")) {
        Serial.println("TCP connection ready");
      }
      delay(1000);
      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=";//determine the number of caracters to be sent.
      esp.print(sendCmd);
      esp.println(postRequest.length() );
      delay(500);
      if(esp.find(">")) {
        Serial.println("Sending..");
        esp.print(postRequest);
        if( esp.find("SEND OK")) {
          Serial.println("Packet sent");
          while (esp.available()) {
            String tmpResp = esp.readString();
            Serial.println(tmpResp);
          }
          // close the connection
        esp.println("AT+CIPCLOSE");
        }
      }
    }

Output :

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

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

body:
I got it working using the code below:

    #include "SoftwareSerial.h"
    String ssid ="Home";

    String password="%Qwerty@123%";
    char input[12];
    int count = 0;
    SoftwareSerial esp(2, 3);// RX, TX

    String data;

    String server = "192.168.0.182"; // www.example.com

    String uri = "/testget.php";// our example is /esppost.php

    int DHpin = 0;//sensor pin

    byte dat [12];

    String temp;

    void setup() {

    pinMode (DHpin, OUTPUT);

    esp.begin(9600);

    Serial.begin(9600);

    reset();

    connectWifi();

    }

    //reset the esp8266 module

    void reset() {

    esp.println("AT+RST");

    delay(1000);

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

    }

    //connect to your wifi network

    void connectWifi() {

    String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";

    esp.println(cmd);

    delay(4000);
    }

    byte read_data () {

    byte data;

    for (int i = 0; i < 8; i ++) {

    if (digitalRead (DHpin) == LOW) {

    while (digitalRead (DHpin) == LOW); // wait for 50us

    delayMicroseconds (30); // determine the duration of the high level to determine the data is '0 'or '1'

    if (digitalRead (DHpin) == HIGH){

    data |= (1 << (7-i)); // high front and low in the post
     }
    while (digitalRead (DHpin) == HIGH);

    // data '1 ', wait for the next one receiver

    }

    } return data; }

    void start_test () {

    digitalWrite (DHpin, LOW); // bus down, send start signal

    delay (30); // delay greater than 18ms, so DHT11 start signal can be detected

    digitalWrite (DHpin, HIGH);

    delayMicroseconds (40); // Wait for DHT11 response

    pinMode (DHpin, INPUT);

    while (digitalRead (DHpin) == HIGH);

    delayMicroseconds (80);

    // DHT11 response, pulled the bus 80us

    if (digitalRead (DHpin) == LOW);

    delayMicroseconds (80);
    while(count<12){
    input[count] = Serial.read(); // Read 1 Byte of data and store it in the input[] variable
          count++;          // increment counter
          delay(5);}
    // DHT11 80us after the bus pulled to start sending data

    //for (int i = 0; i < 4; i ++)

    // receive temperature and humidity data, the parity bit is not considered
    /*for(int x=0;x<12;x++)
    for(int i=0;i<12;i++)
    //dat[i] = read_data ();
    dat[x]=input[i];*/

    pinMode (DHpin, OUTPUT);

    digitalWrite (DHpin, HIGH);

    // send data once after releasing the bus, wait for the host to open the next Start signal

    }

    void loop () {

    start_test ();

        count = 0;      // Reset the counter to zero
        temp = "";
        // convert the bit data to string form
    for(int i=0;i<13;i++)
    temp += input[i];
    Serial.println(temp);
    //Serial.println(temp);

    data = "tag=" + temp;// data sent must be under this form //name1=value1&name2=value2.

    httppost();

    delay(200);

    }

    void httppost () {

    esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

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

    Serial.println("TCP connection ready");

    } delay(100);

    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=";//determine the number of caracters to be sent.

    esp.print(sendCmd);

    esp.println(postRequest.length() );

    delay(500);

    if(esp.find(">")) { Serial.println("Sending.."); esp.print(postRequest);

    if( esp.find("SEND OK")) { Serial.println("Packet sent");

    //while (esp.available()) {

    //String tmpResp = esp.readString();

    //Serial.println(tmpResp);

    //}

    // close the connection

    esp.println("AT+CIPCLOSE");

    }

    }}


body:
You can follow this awesome tutorial if you want to connect your RFID RC522 module to PHP. Source Code and a step by step tutorial are provided. You only need NodeMcu and RC522 RFID module.
https://devcraze.com/tutorials/connecting-rfid-scanner-to-php-using-nodemcu-wifi-module/


message:
Strange behavior on bitwise operation

i am trying to write a simple program that writes the outputs of an accelerometer (which comes down to 3 analog inputs) onto an SD-Card.

I got the hole thing working fine (sending the values as simple strings), however i wanted to increase the frequency at wich the data is taken and therefore tried to send the data to the SD card encoded in binary, and therefore i am doing some bitwise manipulation.

Unfortunately some (as i think) strange things happen. When i add a simple bitwise manipulation the data on the SD card is pretty messed up. (I was unable to detect a pattern but it seems some Bytes are missing or or are there twice without any regularity):

Here is an example of a working version:

    // Get raw accelerometer data for each axis
    unsigned int rawX = analogRead(A0);
    unsigned int rawY = analogRead(A1);
    unsigned int rawZ = analogRead(A2);

    byte b1 = (byte) (rawX>>2);
    byte b2 = (byte) (rawY>>4);
    b2 = b2 + (byte) (rawX<<6);
    byte b3 = (byte) (rawZ>>6);
    b3 = b3 + (byte) (rawY<<4);
    byte b4 = (byte) (rawZ);
    b4 = (byte)b4*4;
    //b4 = (byte)b4<<2;

    // get pressure
    //temp = BMP180_getTemp();
    //float a = 0;
    //float a = pressure.altitude(BMP180_getPressure(), baseline);

    unsigned long t = millis();

    byte writeB[] ={
        b1,
        b2,
        (byte) (rawZ>>6), //replacing this with '(byte) ((rawZ>>6)|(0b11110000 & rawY))' will cause the error
    //also replacing with b3 creates the error as well
        b4,
        (byte) (t>>16),
        (byte) (t>>8),
        (byte)t, (byte)0};

    dataFile.write(writeB,8);

    dataFile.flush();

As mentioned as a comment in the code changing the way the byte is calculated messes up my data on the SD card. I tried several other things however it seems that the following operations are causing the error: | & << >>  (However i am using some of them to calculate e.g. b2)

What i don't get is how changing how a byte is calculated affect the data output.

Maybe (probably) i overlooked some easy mistake but i cant figure out what is happening. Any help would be greatly appreciated since im working on this since quite a while.

(I am aware that the program does currently not transmit all necessary data but i startet from scratch and programmed step by step to locate/identify the error)

body:
Your way of sharing the bits between the three values seems a bit confusing. Your code for saving the bits is correct in the meaning of that you save all relevant information. Your bytes are shared in this way (H means high portion of value, L is the low portion of value):

         ____HX_____
    b1: | 0000 0000 |
         _LX_ ___HY___
    b2: | 00 | 000000 |
         __HZ__ __LY__
    b3: | 0000 | 0000 |
         __LZ____
    b4: | 000000 | XX |

This is a rather complex way of dividing the space. Also, since you are not using the remaining 2 bits of `b4` you don't have to shift there.

When you are getting garbled values from your SD card, it wildly depends on how you are reading the bytes (you haven't shown us the code for that). As a suggestion I will explain how I would do it.

----------

We have 3 values from `analogRead()`, which each have 10 bits. So in total we have 30 bits, which can be transmitted in 4 bytes (or 32 bits). When adding bits from another value, I think you can use the `+` operator (opposing to my comment) if the bits of the different values don't overlay (which should be anyway). For my part I like to use the bitwise or `|` to show more clearly, what is done there and to easier check for errors in alignment (easy to see in binary representation). Do as you like. I will use the `|` operator for now.

<!-- language: c -->

    // Get raw accelerometer data for each axis
    unsigned int rawX = analogRead(A0);
    unsigned int rawY = analogRead(A1);
    unsigned int rawZ = analogRead(A2);

    byte b1 = rawX & 0xFF;
    byte b2 = rawY & 0xFF;
    byte b3 = rawZ & 0xFF;
    byte b4 = (rawX & 0x0300) >> 2
              | (rawY & 0x0300) >> 4
              | (rawZ & 0x0300) >> 6;

The low portion of the values are saved in the bytes `b1` to `b3`. The upper 2 bits of every value is saved left-aligned to `b4` (The `& 0x0300` isolates the upper portion, bit 9 and 10, in the values.).

You can read these values in this way:

<!-- language: c -->

    rawX = b1 | (( b4 & 0b11000000) << 2);
    rawY = b2 | (( b4 & 0b00110000) << 4);
    rawZ = b3 | (( b4 & 0b00001100) << 6);

`b1` to `b3` are the start for our retrieved raw values. Then we add the other 2 bits to the raw values. For this we first isolate the bits from `b4` from the positions we used in the upper code. Then we shift them to the left, until they are directly above the 8 bits of the start values.


message:
Digital Pins reads 1 when configured with internal_pullup

I work with Arduino DUE. I would like to configure few of my digital pins as INPUT pins. When the µc sets these particular 4 pins , the DUE must be activated. Something like a DATAREADY pin in the SPI,where the data will be sent to the slave only,when it sets the pin to 1.

According to the datasheet , the external µC would set the pin state from 0 to 1. I tried this program for experimenting the effect of digital pins,

    int RDY = 52;
    void setup() {

     Serial.begin(9600);
    pinMode(RDY,INPUT_PULLUP);
    pinMode(50,INPUT);
    digitalWrite(RDY,HIGH);

    }

    void loop() {

    digitalRead(RDY);
    digitalRead(50);
    digitalRead(11);
    digitalRead(12);

    Serial.println(digitalRead(RDY));
    Serial.println(digitalRead(50));
    Serial.println(digitalRead(11));
    Serial.println(digitalRead(12));

    delay(100);
    }

Results obtained are; 1,1,0,0 as expected. I cannot find a proper way to detect the change of state of the pin (from 0 to 1). To make detect changes, I connected/disconnected the 5V output pin of DUE to the particular digital pins. The results never changed with connection and disconnection of the 5V wire for any pin.

Is there any possible way to detect the change of the pin state as in INPUT mode in Arduino DUE?
Most examples are dealing with switches,but in my case I need a pin as a input.

Thanks

body:
There is no difference between a switch and a "pin" for input. All are either HIGH or LOW. You tie it HIGH with the pullup, and then try giving it a HIGH with +5V (**Caution: The Due is a 3.3V device, not 5V!**).

At no point do you ever give it a LOW signal (connect the input to GND), so how can it ever read LOW?


message:
This error is shown continuosly after first time it compiles successfully

I got this error:

Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

    Multiple libraries were found for "LiquidCrystal.h"  Used: C:\Program
    Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal
    Not used:
    C:\Users\siddh\OneDrive\Documents\Arduino\libraries\libraries readlink
    C:\Users\siddh\OneDrive\Documents\Arduino\libraries\SimpleDHT\SimpleDHT.cpp:
    The system cannot find the file specified. Error compiling for board
    Arduino/Genuino Uno.

    This report would have more information with "Show verbose output
    during compilation" option enabled in File -> Preferences.

This is the code i use:

    //We'll start by adding our libraries

     #include <LiquidCrystal.h>

     #include <SimpleDHT.h>

    //Declaring digital pin no 6 as the dht11 data pin

    int pinDHT11 = 6;
    SimpleDHT11 dht11;

    //Declaring the lcd pins

    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    void setup() {
    // Don't forget to choose 9600 at the port screen

      Serial.begin(9600);

    //Telling our lcd to start up

      lcd.begin(16, 2);

    }

    void loop() {

      //These serial codes are for getting readings on the port screen aswell as the LCD display, since they'll offer us a more detailed interface

      Serial.println("=================================");
      Serial.println("DHT11 readings...");
      delay(2000);

      byte temperature = 0;
      byte humidity = 0;
      int err = SimpleDHTErrSuccess;

      //This bit will tell our Arduino what to do if there is some sort of an error at getting readings from our sensor
      if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
        Serial.print("No reading , err="); Serial.println(err);delay(1000);
        return;
      }

      Serial.print("temp: ");
      Serial.print((int)temperature); Serial.print(" Celcius, ");
      Serial.print("humidity:");
      Serial.print((int)humidity); Serial.println(" %");

      //Telling our lcd to refresh itself every 0.75 seconds
      lcd.clear();

     //Choosing the first line and row

     lcd.setCursor(0,0);

    //Typing Temp: to the first line starting from the first row
      lcd.print("Temp: ");

    //Typing the temperature readings after "Temp: "
      lcd.print((int)temperature);

    //Choosing the second line and first row
      lcd.setCursor(0,1);

    //Typing Humidity(%): to the second line starting from the first row
      lcd.print("Humidity(%): ");

    //Typing the humidity readings after "Humidity(%): "
      lcd.print((int)humidity);

      delay(750);
    }

body:
There is a [bug](https://github.com/arduino/arduino-builder/issues/254) that causes this error when you use the Arduino IDE with files located under OneDrive.

The simplest solution is to move any files that will be used with the Arduino IDE out of OneDrive to any other convenient location on your computer. It looks like you have your sketchbook folder located in the OneDrive so you will want to change that via the Arduino IDE's **File > Preferences > Sketchbook location**. The Arduino IDE does not automatically move the files from the previous sketchbook folder to the new folder so you will need to either move any files to the new sketchbook folder or else reinstall them.

There are some possible workarounds if you want to to continue using the Arduino IDE with OneDrive listed in the issue report:
https://github.com/arduino/arduino-builder/issues/254


body:
I have had this problem as well and I concur with [per1234][1] that the solution (for now) is that you have to move your sketches out of the OneDrive folder.

You used to be able to have your sketches within OneDrive (I did for many years). Since release 1.6.6 things have changed and you can no longer compile files that you once used to be able to compile inside a OneDrive folder.

In addition to [per1234][1]'s great answer (ie move the sketches outside of the Ondrive folder) there are 2 other options. Firstly you could download and install [version 1.6.5][2] which was before the Arduino Builder was incorporated. The other option is to use the [Beta V1.9.0 avalable from the Beta Channel][3].

----------
**UPDATE:**

The issue with OneDrive folders has been resolved as of version 1.8.6.

[https://www.arduino.cc/en/Main/ReleaseNotes][2]

> ARDUINO 1.8.6 2018.08.23
>
> [ide]
>
> * Updated arduino-builder to 1.4.0:
>  - parallel build (improve compile speed)
>  - better reuse of already compiled files
>  - **Windows: fixed build for sketch stored under OneDrive cloud folders**

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.

  [1]: https://arduino.stackexchange.com/a/51825/19409
  [2]: https://www.arduino.cc/en/Main/OldSoftwareReleases#previous
  [3]: https://www.arduino.cc/download_handler.php?f=/ide_beta/arduino-1.9.0-beta-windows.zip


message:
Button isn't working properly

I am new in arduino trying to make race game. My problem is that my button (all buttons) is working sometimes and sometimes not. I am pretty sure that it's because of my code. Could you please help me with it?
Here is my code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int pausebetween = 1;
    int spaceBetween = 1;
    int maxElemnets = 4;
    int obstacleArray[4][2];
    int obstacles[4] = {3,3,2,3};
    bool gameStart = false;
    byte player[8] =
    {
     B00000,
     B00000,
     B10100,
     B11110,
     B11111,
     B11110,
     B10100,
     B00000
    };
    byte obstacle[8] =
    {
     B11111,
     B11111,
     B11111,
     B11111,
     B11111,
     B11111,
     B11111,
     B11111
    };
    byte enemy[8] =
    {
     B00000,
     B00000,
     B00101,
     B01111,
     B00101,
     B00000,
     B00000
    };
    byte empty[8] =
    {
     B00000,
     B00000,
     B00000,
     B00000,
     B00000,
     B00000,
     B00000
    };
    byte fire[8] =
    {
     B00000,
     B00000,
     B00000,
     B11111,
     B00000,
     B00000,
     B00000
    };
    int mat[2][24] = {
      {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
      {1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
      };
    int up = 0;
    int down = 0;
    int reset=0;
    int atack=0;
    void setup() {
     pinMode(9, INPUT);
     pinMode(8, INPUT);
     pinMode(7, INPUT);
     pinMode(6, INPUT);
     Serial.begin(9600);
     lcd.createChar(0, player);
     lcd.createChar(1, empty);
     lcd.createChar(2, enemy);
     lcd.createChar(3, obstacle);
     lcd.createChar(4, fire);
     lcd.begin(16, 2);
    }
    void loop() {
      up  = digitalRead(9);
      down  = digitalRead(8);
      atack  = digitalRead(7);
      reset  = digitalRead(6);
      if(atack){
        for(int i = 0; i<2;i++){
            for(int j = 0; j<23; j++){
                if(mat[j][i]==1){
                  mat[j+1][i]=4;
                  Serial.println(mat[j+1][i]);
                }
            }
          }
      }
      if(reset){
        clearStage();
        gameStart = true;
      }
      if(gameStart){
        generateObstacles();
        redrawGame();
        moveObstacles();
      }
      delay(1000);

     }

    void generateObstacles(){
      int obscount = random(1,4);
      int types[4][2] = {{1,3},{2,1},{1,1},{2,1}} ;
      int type = random(0,4);
      for(int i = 0; i< obscount; i++){
        mat[0][16+i] = types[type][0];
        mat[1][16+i] = types[type][1];
      }
      int spacecount = random(2,5);
      pausebetween = obscount + spacecount;
    }
    void redrawGame(){
       for(int j = 15; j >= 0; j--){
        for(int i = 0; i < 2; i++){
          lcd.setCursor(j,i);
          lcd.write(mat[i][j]);
        }
      }
    }
    void clearStage(){
      for(int i = 0; i<2;i++){
            for(int j = 0; j<23; j++){
                if(i!=1 && j!=1){
                   mat[i][j] =1;
              }
            }
          }
    }
    void moveObstacles(){
       for(int i = 0; i<2;i++){
            for(int j = 0; j<23; j++){
               if(mat[i][j]!=0){
                mat[i][j] = mat[i][j+1];
              }else{
                mat[i][j-1]=1;
              }
              if(mat[i][j]==4){
                mat[i][j-1]=0;
                mat[i][j-2]=1;
               }
            }
          }
    }

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

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

body:
I have two suggestions.

1. Get rid of the delay(1000); in the loop and replace it with code from the BlinkWithoutDelay example that comes with the Arduino IDE: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.

2. Debounce the buttons. There are several libraries on Github that simplify this, for example: https://playground.arduino.cc/Code/Bounce.


message:
How can I declare global array with its length stored in EEPROM?

I am working with Arduino UNO connected with BV4612 display.
I am working on a simple code that controls several water pumps. Each pump has several modes it can run in. I store these modes in an array.
The number of water pumps may vary, and I'd like to store that value in EEPROM (either arduino's or display's).

When the pump count is fixed, I use fixed value, defined by macro:

    #define     PUMP_COUNT      18      //How many pumps we have

    uint8_t pumpModes[PUMP_COUNT];

    void setup(){...}
    void loop(){...}

I'd like to get rid of fixed defined value of PUMP_COUNT, and rather load it from EEPROM, or save the new pump count into the EEPROM if needed.
However, I can't declare an array if I can't read from EEPROM before setup() function like this (from address 32 for example):

    uint8_t pumpModes[EEread(32)];

    void setup(){...}
    void loop(){...}

Is there a solution to get the value from EEPROM so I can declare global array's length with it?

Thanks.

body:
You can't create variable length arrays in C. That's not how C works.

Instead you have to create an array that is big enough to store the *maximum* number of pumps you want to be able to deal with.

The array "size" is then just a number in a variable obtained from wherever you like (including EEPROM).

It doesn't matter if you don't use all of the array. The rest just sits there twiddling its metaphorical thumbs.

The other option, if you are only going to define the array once at startup, or very rarely change the size, is to use `malloc()`:

    uint8_t *pumps;
    uint8_t nPumps = 0;

    void setup() {
        nPumps = EEPROM.read(32);
        pumps = (uint8_t *)malloc(nPumps);
    }

You can change the array size then with:

    nPumps = 8; // for example
    pumps = realloc(pumps, nPumps);

And dispose of the array with:

    nPumps = 0;
    free(pumps);

It's best to try not to change the array size once created, since that can make swiss cheese of your heap, and is not a friendly thing to do on a small microcontroller. If you can decide the array size once in setup and keep it the same all the time the program is running this is a safe operation. Otherwise it becomes risky.


body:
It is possible to use a dynamically allocated array, with malloc and free.

To create such an array use:

    uint8_t* pumpModes;

Somewhere in setup (preferably):

    pumpModes = malloc(sizeof(uint8_t) * PUMP_COUNT);

Freeing the memory is not needed if you need it throughout the entire program, otherwise you can use

    free(pumpModes);

However, take in mind that if you continuously malloc and free memory in the loop() function, you can get memory 'gaps' and you run out of memory really quickly since the Uno has only a few KB of RAM memory.


message:
4WD rover not moving

I am trying to make a 4WD vehicle. I have uploaded the code, all connections are OK and I have used L298N and HC-05. But when running the Bluetooth app, the motors do not rotate. I tried with both an Uno and a Nano and nothing happens. Could anyone help me spot the errors?

I used this code in Arduino Uno:

    #include <SoftwareSerial.h>

    SoftwareSerial BT(0, 1); //TX, RX respetively
    String readvoice;

    void setup() {
      BT.begin(9600);
      Serial.begin(9600);
      pinMode(4, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
    }
    //-----------------------------------------------------------------------//
    void loop() {
      while (BT.available()) {  //Check if there is an available byte to read
        delay(10);              //Delay added to make thing stable
        char c = BT.read();     //Conduct a serial read
        readvoice += c; //build the string- "forward", "reverse", "left" and "right"
      }
      if (readvoice.length() > 0) {
        Serial.println(readvoice);

        if (readvoice == "*forward#")
        {
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(100);
        }
        else if (readvoice == "*back#")
        {
          digitalWrite(3, LOW);
          digitalWrite(4, LOW);
          digitalWrite(5, HIGH);
          digitalWrite(6, HIGH);
          delay(100);
        }
        else if (readvoice == "*left#")
        {
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(800);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(100);
        }
        else if (readvoice == "*right#")
        {
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(800);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(100);
        }
        else if (readvoice == "*stop#")
        {
          digitalWrite(3, LOW);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(100);
        }
        else if (readvoice == "*keep watch in all direction#")
        {
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(100);
        }
        else if (readvoice == "*show me Garba#")
        {
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);

          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(400);
          digitalWrite(3, HIGH);
          digitalWrite(4, HIGH);
          digitalWrite(5, LOW);
          digitalWrite(6, LOW);
          delay(600);
          digitalWrite(3, LOW);
          digitalWrite(4, HIGH);
          digitalWrite(5, HIGH);
          digitalWrite(6, LOW);
          delay(500);
          digitalWrite(3, HIGH);
          digitalWrite(4, LOW);
          digitalWrite(5, LOW);
          digitalWrite(6, HIGH);
          delay(500);
        }
        readvoice = ""; //Reset the variable
      }
    }

This is the wiring diagram of the rover:

![Wiring diagram][1]

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

body:
If you have the wiring right, which you have probably checked 100 times by now, then its probably the fact that you aren't supplying enough current to break the stall of the motor. Search the web for the motor's datasheet and look up the "Stall current" then see if you are supplying enough current.

Have you checked the motor without the gearbox attached, if that's possible?

The motor will have both voltage and current requirements. You are using a 6V motor but we also need to know the running current and stall current so you can workout if your batteries are capable of supplying that. Are you trying to run one motor or 4? Get one motor working first and then move up to 4 when you need to supply 4 times the power.

Also can I just check that you have the batteries in series (to give you 7.4V). This probably isn't enough if the motors require exactly 6v because of the 2V drop through the IC.

Measure the voltage into the bridge and into the motor, as shown in the web page. Also measuring the current would help, but you will have to search to see how best to do that.