body:
I have a laser security system project with a GSM SIM900 and a few sensors. I'm using an Arduino Mega 2560, and everything is working normally, except the GSM is not sending an SMS to the phone and I don't know why!

this is  my code:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <Keypad.h>
    #include <SoftwareSerial.h>

    SoftwareSerial sim900(0,1);
    String  TextForSMS;

    int dataldr =0;
    int sensorldr = A0;
    int ldrState = LOW;
    int ldrthres = 900;

    int pir = A1;
    int pirState = LOW;
    int val = 0;

    int gas = A8;
    int sensorgasThres = 400;

    #define Password_Length 8
    #define PINNUMBER ""

    int signalPin = 2;
    int led1 = 12;
    int led2 = 11;
    int led3 = 10;
    int led4 = 9;
    int led5 = 8;
    int led6 = 7;
    int laser =6;

    char Data[Password_Length];
    char Master[Password_Length] = "123A456";
    byte data_count = 0, master_count = 0;
    bool Pass_is_good;
    char customKey;

    const byte ROWS = 4;
    const byte COLS = 4;

    char hexaKeys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };

    byte rowPins[ROWS] = {30,31,32, 33};
    byte colPins[COLS] = {34, 35, 36, 37};

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    LiquidCrystal_I2C lcd(0x3F, 20, 4);

    void setup(){

      lcd.init();
      lcd.backlight();

      pinMode(signalPin, OUTPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(laser, OUTPUT);

      pinMode(gas, INPUT);
      pinMode(pir, INPUT);
      pinMode(sensorldr,INPUT);

     randomSeed(analogRead(0));
      Serial.begin(9600);
      sim900.begin (9600);
      Serial.println(" loggin time completed");
    delay(5000);

    }

    void loop(){

         digitalWrite(laser, HIGH);
         digitalWrite(led1, HIGH);

         lcd.setCursor(0,0);
         lcd.print("Enter Password:");

       char customKey = customKeypad.getKey();

      if (customKey){

        Data[data_count] = customKey;
        lcd.setCursor(data_count,1);
        lcd.print(Data[data_count]);
        data_count++;
        }

      if(data_count == Password_Length-1){
        lcd.clear();

        if(!strcmp(Data, Master)){

          lcd.print("Correct");
          digitalWrite(led3, HIGH);
          tone(signalPin, 150,200);
          delay(5000);
          digitalWrite(signalPin, LOW);
          digitalWrite(led3, LOW);
          digitalWrite(laser, LOW);
          ldrState = LOW;
          delay(5000);
          digitalWrite(laser, HIGH);
          ldrState = HIGH;

          }
        else{
                lcd.print("Incorrect");
                digitalWrite(led4, HIGH);
                digitalWrite(signalPin, HIGH);

          delay(2000);

                digitalWrite(led4, LOW);
               digitalWrite(signalPin, LOW);
     TextForSMS="\nIntruder password wrong";
      sendSMS(TextForSMS);
     lcd.setCursor(10,2);
      lcd.print("sms2sent");      }

        lcd.clear();
        clearData();
      }

      int   dataldr =analogRead(sensorldr);
         lcd.setCursor(0,3);
         lcd.print("Laser:");
         lcd.setCursor(7,3);
         lcd.print(dataldr);

      if(dataldr<ldrthres){
        digitalWrite(signalPin, HIGH);
        digitalWrite(led2, HIGH);
      TextForSMS="\nIntruder detected";
      sendSMS(TextForSMS);
      lcd.setCursor(10,2);
      lcd.print("sms1sent");

      }
      else
      {
        digitalWrite(led2, LOW);
        noTone(signalPin);

      }
      delay(100);

     int analogSensor = analogRead(gas);
      lcd.setCursor(0,2);
      lcd.print("Gas:");
      lcd.setCursor(4,2);
      lcd.print(analogSensor);
      // Checks if it has reached the threshold value
      if (analogSensor > sensorgasThres)
      {
                digitalWrite(led5, HIGH);
                digitalWrite(signalPin, HIGH);

         TextForSMS="\nIntruder GAS";
      sendSMS(TextForSMS);
      lcd.setCursor(10,2);
      lcd.print("sms3sent");
      }
      else
      {
        digitalWrite(led5, LOW);
        noTone(signalPin);
      }
      delay(100);

      val = digitalRead(pir);
      if (val == HIGH) {
        digitalWrite(led6, HIGH);

        if (pirState == LOW) {
               Serial.println("Motion detected!");
               pirState = HIGH;
        }
      } else {
        digitalWrite(led6, HIGH);
     delay (5000);
        if (pirState == LOW){
               Serial.println("Motion ended!");
          pirState = LOW;
        }
      }

    }

    void clearData(){
      while(data_count !=0){
        Data[data_count--] = 0;
      }
      return;
    }

    void sendSMS (String message){
        sim900.print("AT+CMGF=1");
        delay(1000);

      sim900.println("AT+CMGS=\"+380633965886\"\r ");
          delay(1000);
    sim900.println(message);
        delay(1000);
    sim900.println((char)26);
        delay(1000);
    sim900.println();
        delay(1000);

      }

Also on Github:

https://github.com/shiyaroo/gsm-sim900/blob/master/laser_security_system__gsm.ino

title: Problem sending SMS from a GSM SIM900

Answers: 1

body:
It’s *not* a good approach to put delay function between AT commands.

You have to parse SIM900 responses and check if module replies with OK.

If you don’t receive responses from module, could be different problems:

1. wrong baudrate
2. connection or power supply problem
3. SIM card problem (out of cash, sim lock with pin, etc..)

here you can find a useful guide:
https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/


body:
I am just a newbie, don't know how to solve this issue

    void loop()
    {
      UdpSend("Test", "192.168.0.240", 4210);
    }

    void UdpSend(const char* message, uint8_t * ipaddress, int port){
          Serial.println("Send message: ");
          Udp.beginPacket(ipaddress, port);
          Udp.write(message);
          Udp.endPacket();
    }

Arduino IDE can't compile.

The error message:  ***invalid conversion from 'const char*' to 'uint8_t* {aka unsigned char*}' [-fpermissive]***

Trying to change with this code:

    void UdpSend(uint8_t * message, uint8_t * ipaddress, int port){
          Serial.println("Send message: ");
          Udp.beginPacket(ipaddress, port);
          Udp.write(message);
          Udp.endPacket();
    }

Also doesn't work, the error message: ***invalid conversion from 'const char*' to 'uint8_t* {aka unsigned char*}' [-fpermissive]***

Please help...

title: Invalid conversion from 'const char' to 'uint8_t*'

Answers: 2

body:
Not sure why you're using `uint8_t` at all

The Udp.beginPacket function signature is

    int WiFiUDP::beginPacket(const char *host, uint16_t port)

No hint of uint8_t there

and .write is either

    WiFiUDP::write(uint8_t byte)
    WiFiUDP::write(const uint8_t *buffer, size_t size)
    WiFiUDP::write(const char *str)
    WiFiUDP::write(const char *buffer, size_t size)

So, your other attempt to use `write((uint8_t *))` is also wrong

Try this:

    void loop()
    {
      UdpSend("Test", "192.168.0.240", 4210);
    }

    void UdpSend(const char* message, const char * ipaddress, int port){
          Serial.println("Send message: ");
          Udp.beginPacket(ipaddress, port);
          Udp.write(message);
          Udp.endPacket();
    }

body:
In ESP32 Arduino package the WiFiUdp.h doesn't pull in all Print class `write` functions. As consequence the WiFiUdp class doesn't know `write(const char *str)`.

Use `Udp.print(message);` if message is a zero-terminated char array

or `Udp.write(message, size);` if message is a byte array


body:
I have searched on Google but to no avail. Perhaps you guys can help.

-Aj

title: Is there a relationship between RSSI and Power? If so, how are they connected and does it have a formula to extract one from the other?

Answers: 1

body:
> Is there a relationship between RSSI and Power?

Yes

> If so, how are they connected and does it have a formula to extract one from the other?

RSSI is in relation to the square-root of the power. See below references for the actual formula.

Holiday extra: RSSI for an RF433 module can be estimated by the time from end of transmission and noise. This is the time for the AGC circuit to increase gain from the received signal to the noise level. Please see Cosa RF433 library for an example.

References:

 1. https://en.wikipedia.org/wiki/Received_signal_strength_indication
 2. https://en.wikipedia.org/wiki/Signal_strength_in_telecommunications


body:
The code below should generate a PWM signal on digital pin 3. But know I want to see if it is even working. I was thinking about a Event triggering method like ISR. But somehow it does not work. I guess a ISR needs to a Input Pin, e.g. it would work, when I would've a PWM signal coming from somewhere.

Is it even possible to generate a PWM signal and read it to see some results on the serial monitor?

edited code:

    byte const PWM_PIN = 3;

    volatile unsigned long pwm_value = 0;
    volatile unsigned long prev_time = 0;

    void setup() {
      pinMode(PWM_PIN, OUTPUT);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
    }

    void loop() {
      digitalWrite(PWM_PIN, HIGH);
      delay(400);
      digitalWrite(PWM_PIN, LOW);
      delay(1600);
    }

    void rising() {
      attachInterrupt(digitalPinToInterrupt(PWM_PIN), falling, FALLING);
      prev_time = millis();
    }

    void falling() {
      attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
      pwm_value = millis()-prev_time;
      Serial.println(pwm_value);
    }

title: Generating and reading a PWM signal at the same time on Arduino Uno R3?

Answers: 2

body:
1. You aren’t generating a correct PWM, because Serial.println introduces a delay. The right way for generating PWM is to use **analogWrite** function.

2. You **can’t** use attachInterrupt function for detecting rising and falling edge of an **output pin**.

3. In order to detect the rising and falling edge of a PWM signal, you have to use the **timer interrupt** of PWM module. For doing this, You have to write/read directly ATmega registers without using Arduino libraries. What version of Arduino are you using?

body:
You are declaring the variables `prev_time` and `pwm_value` as `int`, which has (on a standard Arduino) 16 bits. Since you use the signed variant, you get a range of values from -32768 to 32767. But `micros()` is returning an `unsigned long`, which has 4 bytes (32 bits) and is not signed. With `int` there are only 32.767 ms (since it represents microseconds here), without letting the variable overflow. Even the full range would give you only about 65 ms. It simply cannot hold a value like 1000000. If you assign this value to an `int`, it will directly overflow (which - I think - would give you the value modulo 2^16), effectively loosing big parts of the information. You cannot get meaningful results with this in such a high time scale.

When measuring time (with `millis()` or `micros()`) you should always be sure to use `unsigned long` as type to prevent these problems.

---

Apart from the variable type, why do you use `micros()` here? You are measuring times in the hundreds of milliseconds, so why not use `millis()`? This would keep the values lower.


body:
I don't know anything about HTML, but I want to extract the % probability of the Northern lights being visible from this webpage
[http://aurorawatch.ca/][1].
  [1]: http://www.aurorawatch.ca/

I entered this into the URL field, and selected HTML version 1.

When I inspect the text element I want and copy the Xpath I get the following:

"/html/body/div[1]/div[5]/table/tbody/tr[1]/td/div[1]/table[2]/tbody/tr[2]/td/div/table/tbody/tr/td[2]/span"

and enter this into the "parse string" field of the ThingSpeak API app, but get the following error:

"Error parsing document, try a different parse string."

Most people who get this error seem to be getting data that doesn't load with the original page, so I think I must be missing something.

If there is a better solution for pulling this number to my ESP8266 than creating a thingspeak API, I would love to hear it too!

title: Can't extract basic data using ThingspeakHTTP

Answers: 1

body:
You should use this page, since the other is the front page of the site and more likely to be dynamic:

* http://www.aurorawatch.ca/index.php?option=com_content&task=view&id=28&Itemid=47

The XPath is also slightly different. The first `tbody` in the reported path doesn't actually exist. You should also add `/text()` to the end of the path to just return the textual content of the node:

* `/html/body/div[1]/div[5]/table[2]/tr[3]/td/table/tbody/tr/td[2]/span/text()`


body:
Having in my visual basic app something like:

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            *whatever* value = serialPort1.Read*whatever*();
        }

Suppose my Arduino sends in every loop, the value read by a photoresistor. Suppose my Arduino also sends a 0 if certain led is LOW or a 1 if certain led is HIGH. Finally suppose my Arduino also sends a value that is equal to the number of times the loop has been executed.

In the 25th execution, lets suppose my Arduino sends something like:

    Serial.write(LED_state) // 0 or 1 for LOW or HIGH
    Serial.write(photoresistor_value) //lets suppose 25
    Serial.write(loop_number) //25

Question: if all the values are sent using Serial.write or Serial.print, and all values are ints, how can I distinguish in my app if the value 25 received belongs to the photoresistor or to the loop? Is there any way to send something like (key, value) from Arduino so I can distinguish between the ints received so I can assign them correctly to my app variables?

title: How can I distinguish values sent from Arduino

Answers: 1

body:
> Is there any way to send something like (key, value)

Sure:

    Serial.print("LED state: ");
    Serial.println(LED_state);

You will have to modify your VB code to parse that.


body:
How can i send a (file) from PC to Arduino Yun at running time ?

There's a way to send some commands via Serial.
But how would a whole file goes ? Assuming the file can take place at RAM without any problems.

Thanks

title: Sending file from PC to Arduino

Answers: 3

body:
You can send a file, byte after byte, using Serial.
On the Arduino side, you parse serial communication and put bytes inside an array. At the end, you reconstruct the file.

body:
The first question is what do you want to do with your image : Arduino Yun has a Linux chip & an Arduino chip.
And I don't think that image treatment must happen in the Arduino side...
So you can send your image with scp to Linux side, then do what you want with it and perhaps, eventually, send the result for action to the Arduino part.

body:
Back in the mists of time (late 1990s, if anyone's counting), there existed a file transfer protocol called [XMODEM][1] that was used to send a file across a link normally used for a terminal, on small, publicly available systems known as Bulletin Board Systems, or BBSes.
XMODEM divided a file into packets of 129 bytes, sent and acknowledged one packet at a time. It had a simple 8-bit checksum to verify the file contents which was just "ok" over a reasonably reliable line, line and inadequate on a noisy one. But it was one of the first experimenter-built and widely used protocols.

As it was pushed harder and harder (larger file sizes, higher line speeds intolerant of the small, single-packet handshake) and its weaknesses became more problematic,a number of derivatives were developed to address the weaknesses.

[ZMODEM][2] was one of those, which allowed the sender a "sliding window" of packets, so it could keep sending packets (up to the window maximum) without stopping to wait for each acknowledgement, and could use larger packet sizes, among other improvements.

They are relatively easy to implement, XMODEM more-so, and source code or specs can be found by looking around.

If your files aren't horrendously large and the lines are fairly reliable, even XMODEM may be adequate.

  [1]: https://en.wikipedia.org/wiki/XMODEM
  [2]: https://en.wikipedia.org/wiki/ZMODEM


body: I purchased an Arduino Uno. I am trying to set it up, but when I got to the "port" on my MAC, there is no option to select anything related to my board. The only connections the port tab allows me to connect to is the bluetooth incoming port, which is not correct because it gives me errors when I try to set up the UNO to block on and off for 1 second. I know this is the legit Arduino Uno, so why is the bluetooth not connecting?

title: Arduino Uno will not connect to MAC computer running Sierra

Answers: 1

body: I assume you have installed Arduino IDE on your mac and connecting board to mac using USB cable. Many time it happens due to driver or OS reason. Just plug the Arduino to another USB port and it should work.


body:
So to try and speed up my project, I have moved from using two UNO's to a UNO on the receive side, and teensy 3.6 on the sender side. However, no dice. The UNO  doesn't receive any data or even try to print it. I have found it gets to the line;

    if(!digitalRead(CAN0_INT))

and then the program won't proceed. I have swapped out the teensy and run the same code on an UNO again on the sender to check all the connections work and it is fine, as soon as I plug in the teensy no messages are received.

As far as I can tell the MCP2515 module does not work on 3.3V, so I'm wondering if it is that. So, my plan is to power the MCP2515 from a 5V source, and drop the voltage on the interrupt and MISO line to 3.3V so the teensy is safe.

However I am unsure on how to do this, and I also need a quick fix as i'm away this afternoon until January and don't have a logic converter to hand. I have seen you can use a voltage divider to reduce voltage but will that be an issue as that solution is apparently only for slow signals?

Any other thoughts on why this setup won't work are welcome. So just incase I have added my code that works on UNO's but not on teensy. My only other thought why this won't work is that teensy 3.6 already has CAN bus and the code is not compatible?

Sender

    // CAN Send Example
    //

    #include <mcp_can.h>
    #include <SPI.h>
    #include <Wire.h>

    const int MPU_addr = 0x68; // I2C address of the MPU-6050

    float lastTimeSent;
    const float intervalSendMs = 0.000001; // Send period in milliseconds
    float currMillis;

    int16_t AccX, AccY, AccZ, Tmp, GyX, GyY, GyZ;
    uint8_t dataArray[32];
    uint8_t data1[8], data2[8];
    int Switch = 7;
    const int AS_Pin = 10;

    #define CAN0_INT 2    // Set INT to pin 2
    MCP_CAN CAN0(9);     // Set CS to pin 10

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

        initializeMCP2515();

        pinMode(Switch, OUTPUT);
        digitalWrite(Switch, HIGH);

        initializeMPU9250();

    }

    void loop()
    {
        currMillis = millis();

        if ((currMillis - lastTimeSent) >= intervalSendMs)
        {
            lastTimeSent += intervalSendMs;

            readFromMPU9250();

            //MPU_Data_to_CAN_Array();

            convertDataToPackets();

            // Send the two frames; if the first sending is successful send also the second, otherwise abort
            // send data frame 1:  ID = 0x100, Standard CAN Frame, Data length = 8 bytes, 'data' = array of data bytes to send
            // send data frame 2:  ID = 0x101, Standard CAN Frame, Data length = 8 bytes, 'data' = array of data bytes to send
            if (CAN0.sendMsgBuf(0x100, 0, 8, data1) == CAN_OK)
                CAN0.sendMsgBuf(0x101, 0, 8, data2);
        }

                      Serial.print(currMillis);
                      Serial.print("\t");
                      Serial.print(AccX);
                      Serial.print("\t");
                      Serial.print(AccY);
                      Serial.print("\t");
                      Serial.print(AccZ);
                      Serial.print("\t");
                      Serial.print(GyX);
                      Serial.print("\t");
                      Serial.print(GyY);
                      Serial.print("\t");
                      Serial.println(GyZ);

    }

    //===================================================================================
    //                                  FUNCTIONS
    //===================================================================================
    void initializeMCP2515()
    {
        // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
        if(CAN0.begin(MCP_ANY, CAN_1000KBPS, MCP_16MHZ) == CAN_OK)
            Serial.println("MCP2515 Initialized Successfully!");
        else
            Serial.println("Error Initializing MCP2515...");

        CAN0.setMode(MCP_NORMAL);   // Change to normal mode to allow messages to be transmitted
    }

    void initializeMPU9250()
    {
      pinMode(AS_Pin, OUTPUT);
      digitalWrite(AS_Pin, HIGH);
      SPI.setClockDivider(SPI_CLOCK_DIV4);
      SPI.setDataMode(SPI_MODE0);
      SPI.begin();
    }

    void readFromMPU9250()
    {
          digitalWrite(AS_Pin, LOW);
      SPI.transfer(0x80|0x3B);

      for(int i = 0; i < 14; i++){
      dataArray[i] = SPI.transfer(0);
      }
      digitalWrite(AS_Pin, HIGH);
    delay(50);

    AccX = dataArray[0]<<8|dataArray[1];
    AccY = dataArray[2]<<8|dataArray[3];
    AccZ = dataArray[4]<<8|dataArray[5];
    GyX = dataArray[8]<<8|dataArray[9];
    GyY = dataArray[10]<<8|dataArray[11];
    GyZ = dataArray[12]<<8|dataArray[13];
    }

    void convertDataToPackets()
    {
        long2Byte(currMillis, 0, data1);
        int2Byte(AccX, 4, data1);
        int2Byte(AccY, 6, data1);

        int2Byte(AccZ, 0, data2);
        int2Byte(GyX, 2, data2);
        int2Byte(GyY, 4, data2);
        int2Byte(GyZ, 6, data2);
    }

    void int2Byte(int16_t input, int pos, uint8_t *data)
    {
        for (int i = 0; i < 2; i++)
        {
            data[i + pos] = ((input >> (i * 8)) & 0xff);
        }
    }

    void long2Byte(uint32_t input, int pos, uint8_t *data)
    {
        for (int i = 0; i < 4; i++)
        {
            data[i + pos] = ((input >> (i * 8)) & 0xff);
        }
    }

    /*********************************************************************************************************
      END FILE
    *********************************************************************************************************/

Receiver

    // CAN Receive Example
    //

    #include <mcp_can.h>
    #include <SPI.h>

    long unsigned int rxId;
    unsigned char len = 0;
    unsigned char rxBuf[8];
    uint8_t receivedFirstFrame;

    char msgString[128];                        // Array to store serial string
    uint32_t TimeMicro;
    int16_t AccX, AccY, AccZ, GyX, GyY, GyZ;

    #define CAN0_INT 2  // Set INT to pin 2
    MCP_CAN CAN0(10);   // Set CS to pin 10

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

        initializeMCP2515();

        Serial.println("MCP2515 Library Receive Example...");
        Serial.println("waiting for data");
        receivedFirstFrame = 0;
        Serial.println("data recived?");
    }

    void loop()
    {
        if(!digitalRead(CAN0_INT))
        {
            // Received a message
            if (CAN0.readMsgBuf(&rxId, &len, rxBuf) == CAN_OK)
            {
                // Note: the above line is not like in the examples, but looking at the code the
                // function may return if no message was in the queue, so I think this is safer

                // Let's check if it is one of the known messages
                switch (rxId)
                {
                case 0x100:
                    { // Received first frame
                        // Decode the content and store that the first frame was received
                        decodeFirstFrame(rxBuf);
                        receivedFirstFrame = 1;
                        Serial.print(TimeMicro);
                        Serial.print("\t");
                        Serial.print(AccX);
                        Serial.print("\t");
                        Serial.print(AccY);

                    }
                    break;
                case 0x101:
                    if (receivedFirstFrame)
                    { // Received second frame after a first frame
                        // Decode the content
                        decodeSecondFrame(rxBuf);

                      Serial.print("\t");
                      Serial.print(AccZ);
                      Serial.print("\t");
                      Serial.print(GyX);
                      Serial.print("\t");
                      Serial.print(GyY);
                      Serial.print("\t");
                      Serial.println(GyZ);

                        //printDataToSerial();

                        receivedFirstFrame = 0;
                    }
                    break;
                }
            }
        }

        TimeMicro = 0;
        AccX = 0;
        AccY = 0;
        AccZ = 0;
        GyX = 0;
        GyY = 0;
        GyZ = 0;
    }

    //===================================================================================
    //                                  FUNCTIONS
    //===================================================================================

    void initializeMCP2515()
    {
        // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
        if(CAN0.begin(MCP_ANY, CAN_1000KBPS, MCP_16MHZ) == CAN_OK)
            Serial.println("MCP2515 Initialized Successfully!");
        else
            Serial.println("Error Initializing MCP2515...");

        CAN0.setMode(MCP_NORMAL);   // Change to normal mode to allow messages to be transmitted

        pinMode(CAN0_INT, INPUT);                            // Configuring pin for /INT input
    }

    void decodeFirstFrame(uint8_t *rxBuff)
    {
        TimeMicro = byte2Double(TimeMicro, 0, rxBuff);
        AccX = byte2Int(AccX, 4, rxBuff);
        AccY = byte2Int(AccY, 6, rxBuff);
    }

    void decodeSecondFrame(uint8_t *rxBuff)
    {
        AccZ = byte2Int(AccZ, 0, rxBuff);
        GyX = byte2Int(GyX, 2, rxBuff);
        GyY = byte2Int(GyY, 4, rxBuff);
        GyZ = byte2Int(GyZ, 6, rxBuff);
    }

    uint32_t byte2Double(uint32_t output, int pos, uint8_t data[4]){
          for (int i = 0; i < 4; i++)
        {
          output += ((uint32_t)data[i + pos]) << (i * 8);
        }
        return output;
    }

    int16_t byte2Int(int16_t output, int pos, uint8_t data[2]){
          for (int i = 0; i < 2; i++)
        {
          output += ((int16_t)data[i + pos]) << (i * 8);
        }
        return output;
    }
    /*********************************************************************************************************
      END FILE
    *********************************************************************************************************/

Thanks

title: 5V MCP2515 to 3.3V Teensy. How to reduce the MISO voltage

Answers: 0


body:
I am planning to create a project which will take a picture with OV7670 and `Arduino Uno` with `SD card` and send it to server with `ESP8266`.

is it possible to use Arduino Uno(it has only 2k RAM memory)?

title: Using an OV7670, Arduino Uno, ESP8266 and SD card

Answers: 0


body:
Attempting to flash a new firmware with FLIP results in a "AtLibUsbDfu.dll not found" error and windows says that "Arduino Uno" already has the latest drivers.

How do I fix the AtLibUsbDfu.dll error? All sources say to update the driver to fix this but I already have the latest driver and windows wont let me change it.

title: "AtLibUsbDfu.dll not found" when using FLIP on Uno R3

Answers: 0


body:
I connect gnd>gnd, 5v>5v and d1>d1 - nothing works with relay blink code

I change connection to d5 on wemos (still d1 on relay) and it works fine with code change to d5

Any ideas, as at present I can't stack the relay on the wemos? (because the d1 goes to d1)

According to pinout, D1 is "I/O, in the default mode, SCL of I2C" and GPIO5.

Thanks

Code:

    /*
     * Relay Shield - Blink
     * Turns on the relay for two seconds, then off for two seconds, repeatedly.
     *
     * Relay Shield transistor closes relay when D1 is HIGH
     */

    const int relayPin = D1;
    const long interval = 2000;  // pause for two seconds

    void setup() {
      pinMode(relayPin, OUTPUT);
    }

    void loop() {
      digitalWrite(relayPin, HIGH); // turn on relay with voltage HIGH
      delay(interval);              // pause
      digitalWrite(relayPin, LOW);  // turn off relay with voltage LOW
      delay(interval);              // pause
    }

Also on [GitHub][1].

Wemos D1 mini:

https://www.amazon.co.uk/gp/product/B071S8MWTY/ref=oh_aui_detailpage_o00_s01?ie=UTF8&psc=1

5V relay:

https://www.amazon.co.uk/gp/product/B07DK1FZF9/ref=od_aui_detailpages00?ie=UTF8&psc=1

  [1]: https://github.com/wemos/D1_mini_Examples/blob/master/examples/04.Shields/Relay_Shield/Blink/Blink.ino

title: Wemos D1 mini with relay shield (why does D1 not operate relay but D5 does)?

Answers: 0


body:
Apparently it's possible to [test the capacitance of a capacitor][1] with an arduino. In this [thread][2], someone tries to do the same on a NodeMCU but the conclusion is that it's enough to get the change in capacitantce, not the real value, and it's not "really stable" (reliable?).

I would like to get the real value of the capacitance (not just the change of the capacitance). Is there a way to do it with a [NodeMCU Lolin v3][3]?
If yes, how?
If no, will an arduino clone (like Elegoo or Geekcreit) be precise enough to give a real value of the capacitance?

  [1]: http://www.circuitbasics.com/how-to-make-an-arduino-capacitance-meter/
  [2]: https://www.esp8266.com/viewtopic.php?f=160&t=16566
  [3]: https://www.aliexpress.com/item/V2-4M-4FLASH-NodeMcu-Lua-WIFI-Networking-development-board-Based-ESP8266/32647690484.html?spm=0.8937489.0.0.2aee2e0elybUZR

title: Testing a capacitor with a nodeMUC Lolin V3

Answers: 0


body:
I used 2 relay modules. One single channel 5 volt and  another 2 channel 5 volt. On connecting 5v of arduino uno the relay modules arent getting on(led on modules not on). 2 channel once worked with 9volt dc adapter supplying to arduino board.By work i mean the led on relay blinked as per code but no clicking sound.The next time i made the exact same connection and code it didn't work..Single channel arent working with 9v adapter also.Sometimes the led on single channel module is on but no switching and most of the times its not even getting on.i used 9 volt battery to supply vcc and ground to single channel module.This turned on the led on it but no switching.i don't understand how 9 volt powered 5 volt single channel relay without burning it.
Connection :: vcc to 5 v (arduino)   gnd to gnd on arduino
Digital pin 8 to in of module.
I used the blinking led type code and tried with and without serial.begin. Arduino is working as serial monitor was giving on /off output at every 2 second.
Load::200 watt bulb from 220 volts AC...under the limit of my modules i.e. 10A 230 volts
I tried 4 different single channel modules and 1 double channel.

title: Relay module not working

Answers: 0


body:
I am trying to use Arduino as Modbus- RTU slave and Raspberry Pi as a Modbus master
I have interfaced Max485 (RS485 to TTL converter) with Arduino and Rs485 to USB converter in Raspberry Pi, Initially, I was able to send data from Arduino to Raspberry Pi, but the data seems to inconsistent and fails to read most times

I am using https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino for Arduino
Minimal Modbus for raspberry pi

Connections:
DI(max485)- TX ( Arduino),
DE(max485) -D4 ( Arduino),
RE(max485) - D4( Arduino),
Ro(max485) - RX( Arduino),
Vcc(max485) -5v( Arduino),
Gnd (max485)- GND( Arduino)

code for Arduino

    #include <ModbusRtu.h>
    uint16_t au16data[6] = {};
    Modbus slave(5,0,4);
    void setup() {
      slave.begin(19200,SERIAL_8N1 );
     }
    void loop() {
      au16data[0]=100;
      au16data[1]=200;
      au16data[2]=300;
      au16data[3]=400;
      au16data[4]=500;
      au16data[5]=600;
      slave.poll( au16data, 6 );
      delay(3000);
    }
python code

    import minimalmodbus
    from datetime import datetime
    import time

    instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 5)
    instrument.serial.baudrate = 19200
    instrument.serial.bytesize = 8
    instrument.serial.parity = minimalmodbus.serial.PARITY_NONE
    instrument.serial.stopbits = 1
    instrument.serial.timeout =5
    instrument.mode = minimalmodbus.MODE_RTU

    while(1):
        try:
            val = instrument.read_registers(0,6)
            # Registernumber, number of decimals
            print val
        except IOError:
            error_msg = "Failed to read from device"
            error_time = datetime.now()
            print "IO Error Time",error_time.isoformat(),error_msg

        except ValueError:
            error_msg = "Failed to read CRC"
            error_time = datetime.now()
            print "Value Error Time",error_time.isoformat(),error_msg
        time.sleep(2)

title: Arduino Modbus - Rtu slave with Raspberry pi using MAX-485

Answers: 0


body:
Take this motor as an example - https://www.robotshop.com/en/12v-100rpm-583-oz-in-brushed-dc-motor.html

it has torque of 42kg.cm

I know all the calculation to find the payload of dc motor from here - https://www.quora.com/How-do-I-calculate-how-much-weight-can-DC-motor-carry

My main concern is the output power. Power formula is:-

power = voltage x Stall Current
      = 12 x 2A = 24W

But the specification says that the power is 5W. Which value should I use in my calculation?

title: Doubt in choosing the right DC motor?

Answers: 1

body:
With a current rating of `0.68 A` at `12 V` you get the *normal* power requirement of `8.6 W` for a `7Kg.cm` torque.

If, for any reason, you stall the motor, your driver must be capable to output `2.2 A` or `26.5 W` to avoid a permanent damage.


body:
I have followed the instructions at https://www.arduino.cc/en/Tutorial/HelloWorld and have my LCD displaying some text. I've also connected the LED back light (LCD pins 15&16).

I wanted to replace the potentiometer used to set the contrast, with a connection to the DAC pin. It needs to be about 0.8V.

When I connect the contrast pin from the LCD to my DAC pin on my ESP32 board, it doesn't work, the contrast is too high. Using a volt meter, it measures about 2.5V.

If I disconnect the LCD contrast pin from my DAC pin, the voltage measured is 0.8V.

Any ideas or examples on how to control the LCD contrast using a DAC pin?

I wondered if I need to add a resistor or something.

title: Unable to set LCD contrast using DAC pin on ESP32

Answers: 1

body:
The DAC in the ESP32 is ok for sourcing current but not so good at sinking current, and that is what you need.

A amplifier set up as a voltage follower would work.

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

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


body:
Ive upgraded to Mojave.  I've never used Arduino before.  I was given Arduino Uno.
Arduino Uno does not find any serial ports... can't load Blink example (the first step)

In blind frustration, I tried the three ports available... None of work.

I've loaded the
CH34x_Install_V1.4.pkg
to no avail.

How do I get a serial port package that will enable serial ports in general (and more importantly for arduino)

thx,
Bruce
On a related Note: the list of things that Mojave broke is long!  To solve many problems, re-install xcode FIRST!!! and read articles on apache, there is a "new and improve" apache server embedded in mojave.

title: Arduino Uno unable to detect serial port on MAC os Mojave 10.14.2

Answers: 1

body:
If you are using a genuino or genuine Arduino, the most common cause of this is using a USB *power only* cable to connect rather than a data cable. (You only need the CH34x_Install_V1.4.pkg if you are running an Arduino clone based on that chipset)

If I ran the world, the USB standard would include some way to distinguish whether it's power only or power and data without having to [test it with a multimeter][1]. I know, I know, that's crazy talk.

  [1]: https://electronics.stackexchange.com/a/140229/171525


body:
I attached all sensor into the Wemos-D1 for uploading the sensor data to the server. but when I upload the data to the server, it connects to the server but cannot save the data into the database and after that send the second data to the server, it shows connections failed... besides, the sensor such as ultrasonic sensor and IR sensor cannot function.

here is the source code for connecting the sensor to the wemos. Not sure the connecting those sensors are correct or not to the wemos.

    #include <ESP8266WiFi.h>
    #include <ESP.h>
    #include <LiquidCrystal.h>
    //LiquidCrystal LCD(12, 11, 5, 4, 3, 2);
    LiquidCrystal LCD(D0,D1, D5, D4, D3, D2);
    const char* ssid     = "wifi username";
    const char* password = "wifi password";
    const char* host = "192.168.1.10";

    #define in  D7 //7
    #define out D8 //8
    #define trigPin D2 //10
    #define echoPin D3 //13
    #define relay D2 //2
    #define led D6 //6            //red color
    #define led2 D0           //yellow color
    #define led3 D1 //9           //green color

    int count = 0;

    int distanceCm;
    long duration;

    void IN()
    {
      count++;
      LCD.clear();
      LCD.print("Number of Item:");
      LCD.setCursor(0, 1);
      LCD.print(count);
      delay(10);
      LCD.setCursor(3, 1);
      LCD.print(distanceCm);
      delay(10);
      LCD.setCursor(6, 1);
      LCD.print(" cm");
      if (distanceCm <= 3) {
        delayMicroseconds(10);
        LCD.setCursor(10, 1);
        LCD.print("Full");
        digitalWrite(led, HIGH);
      } else {
        digitalWrite(led, LOW);
      }

      if (distanceCm > 3 && distanceCm <= 5) {
        delayMicroseconds(10);
        LCD.setCursor(10, 1);
        LCD.print("Enable");
        digitalWrite(led2, HIGH);
      } else {
        digitalWrite(led2, LOW);
      }

      if (distanceCm > 5) {
        delayMicroseconds(10);
        LCD.setCursor(10, 1);
        LCD.print("Empty");
    //    digitalWrite(led3, HIGH);
      } else {
    //    digitalWrite(led3, LOW);
      }
      delay(500);
    }

    void OUT()
    {
      count--;
      LCD.clear();
      LCD.print("Number of Item:");
      LCD.setCursor(0, 1);
      LCD.print(count);
      delay(10);
      LCD.setCursor(3, 1);
      LCD.print(distanceCm);
      LCD.setCursor(6, 1);
      LCD.print(" cm");
      if (distanceCm <= 3) {
        delayMicroseconds(10);
        LCD.setCursor(10, 1);
        LCD.print("Full");
        digitalWrite(led, HIGH);
      } else {
        digitalWrite(led, LOW);
      }

      if (distanceCm > 3 && distanceCm <= 5) {
        delayMicroseconds(10);
        LCD.setCursor(10, 1);
        LCD.print("Enable");
        digitalWrite(led2, HIGH);
      } else {
        digitalWrite(led2, LOW);
      }

      if (distanceCm > 5) {
        delayMicroseconds(10);
        LCD.setCursor(10, 1);
        LCD.print("Empty");
        digitalWrite(led3, HIGH);
      } else {
        digitalWrite(led3, LOW);
      }
      delay(500);
    }

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      delay(10);

      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      pinMode(led, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);

      LCD.begin(16, 2);
      LCD.print("Item Counter");
      delay(2000);

      pinMode(in, INPUT);
      pinMode(out, INPUT);
      pinMode(relay, OUTPUT);

      LCD.clear();
      LCD.print("Item In Box:");
      LCD.setCursor(0, 1);
      LCD.print(count);
      // ESP.restart();
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

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

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

    int value = 0;
    void loop() {

      delay(0);
      delay(5000);
      ++value;

      digitalWrite(trigPin, LOW);
      delayMicroseconds(10);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(50);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distanceCm = duration * 0.034 / 2;

      //******************************************************//
      //IR Sensor Counting Object
      if (digitalRead(in) == HIGH && digitalRead(out) == LOW) {
        IN();
      }

      if (digitalRead(out) == HIGH && digitalRead(in) == LOW) {
        OUT();
      }

      if (count <= 0)
      {
        LCD.clear();
        digitalWrite(relay, LOW);
        LCD.clear();
        LCD.print("No Item in box");
        LCD.setCursor(0, 1);
        LCD.print("box is empty");
        delay(200);
      }
      else {
        digitalWrite(relay, HIGH);
      }

      Serial.print("connecting to ");
      Serial.println(host);

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      const int httpPort = 8095;
      if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
      }
      if (WiFi.status() != WL_CONNECTED) {
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED)
        {
          Serial.println("Waiting for connection");
          delay(0);
        }
      }

      String IRCount, myDistance;
      IRCount = String(count);
      myDistance = String(distanceCm);
      // We now create a URI for the request
      String url = "/Registration/write_data.php";
      url += "?item=";
      url += IRCount;
      url += "&distance=";
      url += myDistance;

      Serial.print("Requesting URL: ");
      Serial.println(url);

      // This will send the request to the server
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n\r\n");
      int timeout = millis() + 5000;
      while (client.available() == 0) {
        if (timeout - millis() < 0) {
          Serial.println(">>> Client Timeout !");
          client.stop();
          return;
        }
      }

      // Read all the lines of the reply from server and print them to Serial
      while (client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }

      Serial.println();
      Serial.println("closing connection");
    }

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

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

Anyone has the solutions please help me

title: Sensors are not function with ESP8266 WeMos-D1R2

Answers: 0


body:
I'm working on a project using this board and wish to do so on a low level ,as in enabling certain registers to enable interrupts etc.
I can't seem to find the correct header files to support programming in this manner (Can't recognise the register names), I've tried using both Atmel Studio and the Arduino IDE but can't seem to get it to work.

Any help would be greatly appreciated

title: Low Level programming - MKR Fox1200

Answers: 0


body:
thanks for any help
I need to read a gpio expander mcp23s08 set as 8 bits input.
my code write correctly (I believe) the setup register using SPI library, with the enclosed example modified.
But I do not understand how read a gpio register (0x09)
code (with the read out routine wrong:

    #define GPIO_SEL_pin 14                         // D14 = MCP23S08 GPIO SPI select pin
    #define SCLK 18                                 // D18 SPI SCLK
    #define MISO 19                                 // D19 SPI MISO
    #define MOSI 23                                 // D23 SPI MOSI

    #include <SPI.h>

    uint8_t keyboard;

    static const int spiClk = 1000000; // 1 MHz

    //uninitalised pointers to SPI objects
    SPIClass * mcp23s08 = NULL;

    void setup() {
      Serial.begin(115200);
      pinMode(GPIO_SEL_pin, OUTPUT);                     //MCP23S08 SPI select pin
      digitalWrite(GPIO_SEL_pin, HIGH);                  //pull ss high to disable data transfer
      mcp23s08 = new SPIClass(VSPI);
      mcp23s08->begin(SCLK, MISO, MOSI, GPIO_SEL_pin);   //SCLK, MISO, MOSI, SS
      mcp23s08SetUp();
      delay(1);

    }

    void loop() {
      keyboard = mcp23s08Read();
      Serial.println (keyboard);
      delay(100);
    }

    // ================================== routines =================================
    void mcp23s08SetUp( void ) {
      uint8_t dev_adr  = 0x40;                          // MCP23S08 address 0; R/W = write
      uint8_t reg_adr  = 0x00;                          // MCP23S08 IODIR register
      uint8_t reg_data = 0xFF;                          // pin configured as input

      digitalWrite(GPIO_SEL_pin, LOW);                 //pull SS slow to prep other end for transfer
    // ============================= MCP3S08 pin as input ==============================
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      mcp23s08->transfer(reg_data);
      mcp23s08->endTransaction();

      reg_adr  = 0x01;                                 // MCP23S08 IPOL register
      reg_data = 0xFF;                                 // invert input polarity
    // ============================= MCP3S08 invert input ==============================
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      mcp23s08->transfer(reg_data);
      mcp23s08->endTransaction();

      reg_adr  = 0x06;                                 // MCP23S08 GPPU pull-up register
      reg_data = 0xFF;                                 // set pull-up register
    // ============================= MCP3S08 pullup resistor ==============================
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      mcp23s08->transfer(reg_data);
      mcp23s08->endTransaction();

      digitalWrite(GPIO_SEL_pin, HIGH);                //pull ss high to signify end of data transfer
    }

    uint8_t mcp23s08Read ( void ) {
      uint8_t dev_adr  = 0x41;                          // MCP23S08 address 0; R/W = read
      uint8_t reg_adr  = 0x09;                          // MCP23S08 GPIO register
      uint8_t reg_data;                                 // GPIO register
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      reg_data = mcp23s08->transfer(0x00);
      mcp23s08->endTransaction();
      return reg_data;
    }

title: esp32 spi library, how read a mcp23s08 register

Answers: 1

body:
You forgot to toggle SS pin in `mcp23s08Read()` function.

     uint8_t mcp23s08Read ( void ) {
          ----> digitalWrite(GPIO_SEL_pin, LOW);                 //pull SS slow to prep other end for transfer
          uint8_t dev_adr  = 0x41;                          // MCP23S08 address 0; R/W = read
          uint8_t reg_adr  = 0x09;                          // MCP23S08 GPIO register
          uint8_t reg_data;                                 // GPIO register
          mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
          mcp23s08->transfer(dev_adr);
          mcp23s08->transfer(reg_adr);
          reg_data = mcp23s08->transfer(0x00);
          mcp23s08->endTransaction();
          ----> digitalWrite(GPIO_SEL_pin, HIGH);                //pull ss high to signify end of data transfer
          return reg_data;
        }


body:
The code worked on my Ardino Uno. I plugged it up the exact same way and am now getting an error.

Here is the error I get when I try to upload my code to the due:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino Due (Programming Port)"

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In static member function 'static void SFEMP3Shield::refill()':

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:1984:7: error: 'sei' was not declared in this scope

       sei();

           ^

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2006:9: error: 'cli' was not declared in this scope

         cli(); // allow transfer to occur with out interruption.

             ^

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In member function 'void SFEMP3Shield::SendSingleMIDInote()':

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2053:7: error: 'cli' was not declared in this scope

       cli(); // allow transfer to occur with out interruption.

           ^

    C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2067:7: error: 'sei' was not declared in this scope

       sei();  // renable interrupts for other processes

           ^

    exit status 1
    Error compiling for board Arduino Due (Programming Port).

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

Here is my code:

    #include <SPI.h>
    #include <SdFat.h>
    #include <SdFatUtil.h>
    #include <SFEMP3Shield.h>

    SdFat sd;
    SFEMP3Shield MP3player;

    const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
    //10 for normal 50 for testing

    const uint16_t monoMode = 1;

    void setup() {
      initSD();
      initMP3Player();
    }

    void loop() {
      if(!MP3player.isPlaying()){
        MP3player.playTrack(1);
      }
    }

    void initSD() {
      if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
        sd.initErrorHalt();
      if(!sd.chdir("/"))
        sd.errorHalt("sd.chdir");
    }

    void initMP3Player() {
      uint8_t result = MP3player.begin();
      MP3player.setVolume(volume, volume);
      MP3player.setMonoMode(monoMode);
    }

title: Error with Sparkfun MP3 Shield and Arduino Due playing music files

Answers: 1

body:
The library is written for the Uno, not the Due. It relies on two instructions that are only available in the AVR compiler.

Newer versions of the core provide a pair of macros, `interrupts()` and `noInterrupts()` that should be used in place of `sei()` and `cli()` respectively, which should be provided by the Due's core as well to make it cross-platform. However that library has never been updated to work with those macros.

You *could* replace the `sei()` and `cli()` calls in the library with `interrupts()` and `noInterrupts()`, however that may not make it work, since it was written with the Uno and other AVR based chips in mind.


body:
I have a [EL Sequencer][1] and [FTDI 5V breakout board][2].  I have been have been unable to program it.  All my attempts get some variation of "programmer is not responding".

I was using these [instructions][3] as a starting place.  I soldered the 6 pinholes as indicated.  I have connected everything.  I am not sure if I should switch the FTDI jumper to 3.3V (it is currently at 5V).  The pin in the EL Sequencer is labelled 5V, but the instructions also say "the EL Sequencer runs an ATmega328p at 8 MHz and 3.3V".  Should I change the jumper to 3.3V?

I have downloaded the latest IDE from [here][4].  But there is no board option for the EL Sequencer.  What board should I select?

Anything else I need to do to program the EL Sequencer?

Thank you,

  [1]: https://www.sparkfun.com/products/12781
  [2]: https://www.sparkfun.com/products/9716
  [3]: https://learn.sparkfun.com/tutorials/sound-reactive-el-wire-costume
  [4]: https://www.arduino.cc/en/main/software

title: Programming an EL Sequencer

Answers: 0


body:
I'm really new to Arduino and have some doubts about how Arduino reads data. Lets suppose I have 3 variables `a,b,c`. I need these variables in my Arduino to make whatever. Since all variables are read using `Serial.read()` how can I distinguish between them in my Arduino?

Example:

`Variable a: 2`
`Variable b: 3`
`Variable c: 4`

Arduino example code:

    void loop() {
    int a = Serial.read();
    int b = Serial.read();
    int c = Serial.read();

    if(a == '0'){
    digitalWrite(yellowLed, HIGH);
    }

    if(b == '0'){
    digitalWrite(blueLed, HIGH);
    }

    if(c == '0'){
    digitalWrite(redLed, HIGH);
    }

In every loop, my Arduino does `serial.read()` 3 times, if I only send value b from my app, since `int a = Serial.read()` executes first, will my b value be assigned to a? If yes, how can I avoid that problem and force the correct assignment? Aditionally, in every loop, if `Serial.read()` doesnt read anything, will my values be changed to null or zero?

title: How to assign two or more variables incoming from app

Answers: 1

body:
This is a classic problem that is solved either by uniquely identifying each value or by agreeing on a pre-defined sequence of data.  However, it can be said that many solutions exist for this problem & that these are only 2 examples.

In the first case, the sender and receiver need to agree that all data will be sent in pairs.  A pair of bytes, for example, where the first identifies the data and the second is the data.  In this case the order of data does not matter.  And much more of one type of data can be sent than another.  This is good to use when the data rate is irregular and does not need to be fast.  Stock prices for example.

In the second case, the sender and receiver need to agree that all data will be sent in the same sequence even if there is no data to be sent.  Such a scheme may employ a special synchronizing bit to identify the beginning of a sequence of data.  Usually, when there is no data to be sent, a zero is sent.  But if zeros are significant, then special null characters will have to be agreed upon.  This is good when the data rate is regular and needs to be fast.  Digitized audio for example.


body:
First, I am a beginner for this.  I just ordered my first book on coding Arduino and I'm working through some simple applications using a DS3231 (that has a temperature reading), LCD, MicroSD card module, etc.  My board is a Uno R3.  Currently, I need a sketch to run part of a program which contains a loop to collect data and have this run when a toggle switch is turned on.  So, toggle goes on and part of program runs, toggle goes off and this part exits.
The reason I need a toggle with constant on/off is the problem with G forces and vibration.  I momentary push button input will not be reliable.  Ultimately, all the components will be in a amateur high-power rocket to run a roll control program.
If you can help, I greatly appreciate your assistance.

title: Using a toggle switch to run part of a sketch

Answers: 2

body:
There are different ways to accomplish the same thing.

The condition is a flag, or a read port.

    if(digitalRead(inPin))
         {
         // Your first code here.
         }
    else
         {
         // second code
         }

Switch contacts will bounce when opening or closing. You may want to consider that. Usually it is stable within 10 milliseconds. Depending on what you are doing it may or may not be relevant.

body:
You need a few things.
At the top of your sketch, before setup()

    byte togglePin = x; // from 2 to 19 with an Uno. Wire to connect pin to Gnd when closed.

In setup()

     pinMode (togglePin, INPUT_PULLUP);

In loop()

    if (digitalRead(togglePin) == LOW){
    // switch closed, do something - or stop doing something
    // maybe set a flag too, like
    toggleState = 0;
    }
    else {
    // switch, stop doing something - or start doing something
    toggleState = 1;
    }

The flag can be used elsewhere in your code

    if (someOtherCondition && toggleState == 0){
    // run a timer or motor or something
    }
    if (someOtherCondition && toggleState == 1){
    // turn off timer or motor or something
    }


body:
One of the requirements of my projects is to send data from my application to the Arduino robot.

I have windows 10, and my robot is Arduino Uno.
The Bluetooth I'm using on my robot is HC-06.

The app side:

* I'm writing some script (With the format I've created)
* Then converting it into JsonString
* Opening the port and sending a start communication signal.
* Sending the JsonString, each represents another command and they're separated with a special character that can't be written in the script.
Here's the problem, I tried sending string length of 256 bytes (not a JsonString) just to test the Bluetooth.

The test I did in my robot

* I read the data
* Turned the led on
* Waited (data.length() / 10) seconds
* Turned the led off

For my data of 256 bytes, the led was ON for 12.8 seconds, which is 128 bytes. And sometimes when I changed some stuff The time was 6.4 seconds.

C# (Application)

    string data = @"0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101";

    protocolBT.BTcontroller.OpenPort();
    protocolBT.BTcontroller.SendChar(ProtocolBT.COM_OpenChar);
    protocolBT.BTcontroller.SendBigData(data);
    protocolBT.BTcontroller.ClosePort();

The Bluetooth Class

    public class BluetoothController
    {
        private readonly SerialPort _serialPort;

        public BluetoothController(string portName, BaudRate baudRate)
        {
            _serialPort = new SerialPort(portName, (int)baudRate, Parity.None, 8, StopBits.One);
        }

        public static bool IsBluetoothSupported()
        {
            return BluetoothRadio.IsSupported;
        }

        public static void SetConnection()
        {
            if (IsBluetoothSupported())
            {
                if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
                    BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
            }
        }

        public void OpenPort()
        {
            try
            {
                _serialPort.Open();
            }
            catch(IOException IOex)
            {
                throw IOex;
            }
        }

        public void ClosePort()
        {
            _serialPort.Close();
        }

        public void SendData(string msg)
        {
            try
            {
                if (_serialPort.IsOpen)
                {
                    byte[] data = Encoding.UTF8.GetBytes(msg);
                    _serialPort.Write(data, 0, data.Length);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void SendBigData(string msg)
        {
            try
            {
                if (_serialPort.IsOpen)
                {
                    foreach (char ch in msg)
                    {
                        SendChar(ch);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void SendChar(char ch)
        {
            try
            {
                if (_serialPort.IsOpen)
                {
                    byte[] data = Encoding.UTF8.GetBytes(new char[]{ ch });
                    _serialPort.Write(data, 0, data.Length);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }

And this is my Arduino test code

    #include <SoftwareSerial.h>

    #define RX 10
    #define TX 11
    SoftwareSerial BT = SoftwareSerial(RX, TX);

    String startCom = "»";

    String MessageStart = "";
    bool isListen = false;
    String data = "";

    int yellow = 12;

    void setup()
    {
      // Define LED
      pinMode(yellow, OUTPUT);

      // Test yellow led
      digitalWrite(yellow, HIGH);
      delay(1000);
      digitalWrite(yellow, LOW);

      // Define Bluetooth
      pinMode(RX, INPUT);
      pinMode(TX, OUTPUT);
      BT.begin(9600);
    }

    void loop()
    {
      if(isListen == false)
      {
        readStartCommand();
      }
      else if(isListen == true)
      {
        readAllData();

        int len = data.length();
        if(len > 0)
        {
          robotLedOn(0); // Turn on the yellow led
          for(int i = 0; i < len; i++) // Wait (len * 0.1) second
          {
            delay(100);
          }
          robotLedOff(0); // Turn off the yelloe led
        }
      }
    }

    void readStartCommand()
    {
      if(BT.available() > 0)
      {
        char ch = BT.read();
        Message += ch;

        if(MessageStart == startCom)
        {
          // Blink the yellow led if the start communication command recieved
          robotLedOn(0);
          delay(1000);
          robotLedOff(0);
          delay(2000);

          MessageStart = "";
          isListen = true;
        }
      }
    }

    void readAllData()
    {

      while(BT.available() > 0)
      {
        data += BT.read();
      }
      isListen = false;
    }

I tried to put the 256 bytes data manually to string in the Arduino and the timer was on 25.6 seconds.
So I think that there is a limit for the size of the data that Bluetooth can handle.

Note:

* I need Json because I have complicated commands, not only leds. Some of the commands require multi-parameters from different types.
* Soon I will get Arduino-Mega because I don't have enough pins in my Uno.

Tried:

* Change the timeout, it still stops receiving at 128 bytes.
with read() and setTimeout(100-2000) Timer result: 12.8 seconds
With readString() and setTimeout(100-2000) Timer result: 6.4 seconds

* My WriteBufferSize in the PC Bluetooth is 2048 bytes. So I'm pretty sure that all the data is sent.

* Different Baud Rates and using the Library instead of the
The only change is that now the timer stops at 15.5 seconds...

* Use BT.flush() and all my data is sent 100% for sure, the problem is in receiving in my Arduino. I think there is a buffer limit for the data...

* Using another Bluetooth device, still the result is 15.5 seconds instead of 25.6 seconds.

title: How to send big data (long string) from PC to Arduino using Bluetooth

Answers: 0


body:
I have connected my Mega2560 Arduino to my computer; locally everything works fine - I have been able to upload and run programs.

However, on [Arduino Create][1], it shows that there's no connection to my board. I have downloaded the plugin. The [instructions][2] say to "choose a port", and in the image it displays a menu with "[board] at [port]" but in my menu there is no "at", it just says "Arduino/Genuino Mega or Mega 2560" with an option to choose a flavour, but no port.

How can I choose a port and get my Arduino connected?

  [1]: https://create.arduino.cc/editor
  [2]: https://create.arduino.cc/projecthub/Arduino_Genuino/getting-started-with-arduino-web-editor-on-various-platforms-4b3e4a?f=1

title: How to choose a port on Arduino Create

Answers: 0


body:
I found a really nice 24 bit I2C adc which was fairly cheap as well (ADS1219) but as far as I could tell there are no libraries for it so I decided to make my own. I have managed to write functions and get everything working on the arduino itself but I've been having massive issues with converting it into a library.
So I tried a very basic sketch to see if I can do something as simple as printing hello world using the library.
Here is my ADS1219.h file:

    #ifndef ADS1219
    #define ADS1219

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    class ADS1219{
    public:
     ADS1219();
     void begin();
     void printHello();
    };

    #endif

And the ADS1219.cpp:

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    #include

    ADS1219::ADS1219{
     Serial.println("New object created!");
    }

    void ADS1219::begin(){
     Serial.begin(9600);
    }

    void ADS1219::printHello(){
     Serial.println("Hello World");
    }

and my main sketch:

    #include

    ads = new ADS1219;

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

    void loop() {
      ads.printHello();
      delay(2000);
    }

but I get this really long error which basically says I've failed with creating the ads object.
I tried ADS1219 ads; as well but same error ... not sure what's wrong tbh.

    Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

    In file included from sketchADS1219.cpp:7:0:

    ADS1219.h:14:11: error: expected unqualified-id before ')' token

       ADS1219();

               ^

    ADS1219.h:12:14: error: an anonymous struct cannot have function members

     class ADS1219{

                  ^

    ADS1219.h:18:1: error: abstract declarator '' used as declaration

     };

     ^

    ADS1219.cpp:9:17: error: expected id-expression before '{' token

     ADS1219::ADS1219{

                     ^

    ADS1219.cpp:13:21: error: explicit qualification in declaration of 'void begin()'

     void ADS1219::begin(){

                         ^

    ADS1219.cpp:17:26: error: explicit qualification in declaration of 'void printHello()'

     void ADS1219::printHello(){

                              ^

    In file included from C:UsersOM222ODesktopadslibadslib.ino:1:0:

    ADS1219.h:14:11: error: expected unqualified-id before ')' token

       ADS1219();

               ^

    ADS1219.h:12:14: error: an anonymous struct cannot have function members

     class ADS1219{

                  ^

    ADS1219.h:18:1: error: abstract declarator '' used as declaration

     };

     ^

    adslib:3:1: error: 'ads' does not name a type

     ads = new ADS1219;

     ^

    C:UsersOM222ODesktopadslibadslib.ino: In function 'void setup()':

    adslib:7:3: error: 'ads' was not declared in this scope

       ads.begin();

       ^

    C:UsersOM222ODesktopadslibadslib.ino: In function 'void loop()':

    adslib:11:3: error: 'ads' was not declared in this scope

       ads.printHello();

       ^

    exit status 1
    expected unqualified-id before ')' token

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

title: Creating a library for arduino

Answers: 3

body:
Your problem stems from this line:

    #define ADS1219

You define the macro ADS1219 as empty. From that point on all references to ADS1219 get replaced with nothing. For example:

    class ADS1219{
    public:
     ADS1219();
     void begin();
     void printHello();
    };

becomes:

    class {
    public:
     ();
     void begin();
     void printHello();
    };

And

    void ADS1219::begin(){
     Serial.begin(9600);
    }

becomes:

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

By using the same name in your header guard as your class name you screw everything else up.

I always use strict rules for header guard macros to ensure that they never conflict with anything else.  You should change yours to read something else.  I would use:

    #ifndef _ADS1219_H
    #define _ADS1219_H

    // ... content

    #endif

----

You are also lacking the parenthesis in the constructor implementation:

    ADS1219::ADS1219{
     Serial.println("New object created!");
    }

should read:

    ADS1219::ADS1219(){
     Serial.println("New object created!");
    }

And you don't give your `ads` variable a type and you don't want to use new:

    ads = new ADS1219;

should read:

    ADS1219 ads;

body:
Are you sure you're compiling this for C++ and not C?

In any case, you're defining

    #define ADS1219

I'm not sure what that does to your class name. Have you tried to

    #define ADS1219_H  // <- Standard include guard

instead? Does this yield different results.

body:
I have made a lot of progress and almost everything works fine ... except I initially used strings in switch case for setting up the voltage reference and conversion modes ... it did not like it at all. I instead aimed to use enums for the same purpose but I'm getting this error now:

    Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

    In file included from sketch\LibraryExample1.ino.cpp:1:0:

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected identifier before numeric constant

     #define INTERNAL 3

                      ^

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

       INTERNAL = VREF_INTERNAL,

       ^

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected '}' before numeric constant

     #define INTERNAL 3

                      ^

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

       INTERNAL = VREF_INTERNAL,

       ^

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected unqualified-id before numeric constant

     #define INTERNAL 3

                      ^

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

       INTERNAL = VREF_INTERNAL,

       ^

    In file included from C:\Users\OM222O\Desktop\LibraryExample1\LibraryExample1.ino:2:0:

    C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:51:1: error: expected declaration before '}' token

     }adsRef_t;

     ^

    exit status 1
    Error compiling for board Arduino Nano.

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

my ADS1219.h file is:

    #ifndef ADS1219_H
    #define ADS1219_H

    #if (ARDUINO >=100)
      #include "Arduino.h"
    #else
      #include "WProgram.h"
    #endif

    #include <Wire.h>

    #define CONFIG_REGISTER_ADDRESS 0x20
    #define STATUS_REGISTER_ADDRESS 0x24

    #define MUX_MASK     0x1F
    #define MUX_DIFF_0_1   0x00
    #define MUX_DIFF_2_3   0x20
    #define MUX_DIFF_1_2   0x40
    #define MUX_SINGLE_0   0x60
    #define MUX_SINGLE_1   0x80
    #define MUX_SINGLE_2   0xA0
    #define MUX_SINGLE_3   0xC0
    #define MUX_SHORTED    0xE0

    #define GAIN_MASK     0xEF
    #define GAIN_ONE    0x00
    #define GAIN_FOUR    0x10

    #define DATA_RATE_MASK   0xF3
    #define DATA_RATE_20   0x00
    #define DATA_RATE_90   0x04
    #define DATA_RATE_330   0x08
    #define DATA_RATE_1000   0x0c

    #define MODE_MASK    0xFD
    #define MODE_SINGLE_SHOT  0x00
    #define MODE_CONTINUOUS   0x02

    #define VREF_MASK    0xFE
    #define VREF_INTERNAL   0x00
    #define VREF_EXTERNAL   0x01

    typedef enum{
      ONE = GAIN_ONE,
      FOUR = GAIN_FOUR
    }adsGain_t;

    typedef enum{
      INTERNAL = VREF_INTERNAL,
      EXTERNAL = VREF_EXTERNAL
    }adsRef_t;

    typedef enum{
      SINGLE_SHOT = MODE_SINGLE_SHOT,
      CONTINUOUS = MODE_CONTINUOUS
    }adsMode_t;

    class ADS1219  {
      protected:
     uint8_t address;
      public:
        // Constructor
        ADS1219(int drdy, uint8_t addr = 0x40);

        // Methods
        void begin();
     void resetConfig();
     long readSingleEnded(int channel);
     long readDifferential_0_1();
     long readDifferential_2_3();
     long readDifferential_1_2();
     long readShorted();
     void setGain(adsGain_t gain);
     void setDataRate(int rate);
     void setConversionMode(adsMode_t mode);
     void setVoltageReference(adsRef_t vref);

      private:
     void writeRegister(uint8_t data);
     uint8_t readRegister(uint8_t reg);
     long readConversionResult();
     uint8_t config;
     int data_ready;
    };
    #endif

and my cpp file is:

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    #include <Wire.h>
    #include "ADS1219.h"

    static uint8_t i2cRead(void) {
      #if ARDUINO >= 100
      return Wire.read();
      #else
      return Wire.receive();
      #endif
    }

    static void i2cWrite(uint8_t x) {
      #if ARDUINO >= 100
      Wire.write(x);
      #else
      Wire.send(x);
      #endif
    }

    ADS1219::ADS1219(int drdy, uint8_t addr) {
      data_ready = drdy;
      address = addr;
      config = 0x00;
    }

    void ADS1219::begin() {
      Wire.begin();
    }

    uint8_t ADS1219::readRegister(uint8_t reg){
      Wire.beginTransmission(address);
      i2cWrite(reg);
      Wire.endTransmission();
      Wire.requestFrom((uint8_t)address,(uint8_t)1);
      return i2cRead();
    }

    void ADS1219::writeRegister(uint8_t data){
      Wire.beginTransmission(address);
      i2cWrite(CONFIG_REGISTER_ADDRESS);
      i2cWrite(data);
      Wire.endTransmission();
    }

    long ADS1219::readConversionResult(){
      Wire.beginTransmission(address);
      i2cWrite(0x10);
      Wire.endTransmission();
      Wire.requestFrom((uint8_t)address,(uint8_t)3);
      byte dataMSB = i2cRead();
      byte data = i2cRead();
      byte dataLSB = i2cRead();
      long data32 = dataMSB;
      data32 <<= 8;
      data32 |= data;
      data32 <<= 8;
      data32 |= dataLSB;
      return (data32 << 8) >> 8;
    }

    void ADS1219::resetConfig(){
     writeRegister(0x00);
    }

    long ADS1219::readSingleEnded(int channel){
     if (channel > 3) return 0;
     config &= MUX_MASK;
     switch (channel){
        case (0):
          config |= MUX_SINGLE_0;
          break;
        case (1):
          config |= MUX_SINGLE_1;
          break;
        case (2):
          config |= MUX_SINGLE_2;
          break;
        case (3):
          config |= MUX_SINGLE_3;
          break;
     default:
       break;
      }
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readDifferential_0_1(){
      config &= MUX_MASK;
      config |= MUX_DIFF_0_1;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readDifferential_2_3(){
      config &= MUX_MASK;
      config |= MUX_DIFF_2_3;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readDifferential_1_2(){
      config &= MUX_MASK;
      config |= MUX_DIFF_1_2;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    long ADS1219::readShorted(){
      config &= MUX_MASK;
      config |= MUX_SHORTED;
      writeRegister(config);
      while(digitalRead(data_ready)==1);
      return readConversionResult();
    }

    void ADS1219::setGain(adsGain_t gain){
     config &= GAIN_MASK;
     config |= gain;
      writeRegister(config);
    }

    void ADS1219::setDataRate(int rate){
     config &= DATA_RATE_MASK;
     switch (rate){
        case (20):
          config |= DATA_RATE_20;
          break;
        case (90):
          config |= DATA_RATE_90;
          break;
        case (330):
          config |= DATA_RATE_330;
          break;
        case (1000):
          config |= DATA_RATE_1000;
          break;
     default:
       break;
      }
      writeRegister(config);
    }

    void ADS1219::setConversionMode(adsMode_t mode){
     config &= MODE_MASK;
     config |= mode;
      writeRegister(config);
    }

    void ADS1219::setVoltageReference(adsRef_t vref){
     config &= VREF_MASK;
     config |= vref;
      writeRegister(config);
    }

it seems to be passing Gain (or maybe hasn't compiled that yet) but failing on the reference selection ... I don't know what I should change in order to fix the issue.

Edit: I'm really hoping it's not another naming convention thing ... if it is, I'm sorry but C++ seems to waaaaayyyy too picky about names in general


body:
In the Arduino [Tutorial Page][1] named "Hello World" aimed to help people connect a 16x2 LCD Display compatible with Hitachi HD44780 driver to an Arduino Uno. The pins used to connect the Arduino Uno and LCD Module are as follows:

 - LCD RS pin to digital pin 12
 - LCD Enable pin to digital pin 11
 - LCD D4 pin to digital pin 5
 - LCD D5 pin to digital pin 4
 - LCD D6 pin to digital pin 3
 - LCD D7 pin to digital pin 2

Pins 3,5 and 11 are connected to PWM Pins, however, I'm wondering if they actually need these PWM capabilities or does this tutorial just pick random pins and the LCD's D6, D4 and Enable pins doesn't actually need the PWM capabilities available of these pins.

I'm asking this as I'm considering on using an Arduino Mega for my next project and it would be much easier and neater for all the pins of the LCD to go onto the digital pins instead of some being on the digital and others on the PWM pins.

  [1]: https://www.arduino.cc/en/Tutorial/HelloWorld

title: Which LCD Pins, if any, require PWM?

Answers: 2

body:
Likely all programmable pins on modern embedded processors are able to perform digital I/O.  In addition, many can also perform other tasks such as PWM, or Analog to Digital Conversion (ADC).  This is true for many of the different processors used on different Arduino boards.

Often, the nice people who write the C++ driver class of programs or Arduino Libraries offer the user the ability to change pin assignments used by the Arduino Libraries when instantiating an instance of the driver.  This is true for the [LiquidCrystal driver][1] in the [tutorial][2] in the question.  This can be an advantage as processor's resources are limited.  For example, if you need PWM controlled pin to dim LEDs, you can move LCD controlling pins to other non-PWM pins.

The LCD specified in the tutorial linked to in the above question uses a common [Hitachi HD44780][3] interface.  Such assemblies only need embedded processor Digital I/O pins for control.  Had the LCD no electronic driver, the segments need to be directly driven by very low alternating current (AC).  This is difficult for embedded processors.  However, it may be possible using enough PWM pins and some clever software & hardware.

  [1]: https://www.arduino.cc/en/Reference/LiquidCrystal
  [2]: https://www.arduino.cc/en/Tutorial/HelloWorld
  [3]: https://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller

body:
PWM is not used on those pins for the LCD operation. You can choose more convenient pins as long as they are general purpose pins. For example, not A/D input only.

(I thought you might appreciate a short clear answer)


body:
So - i started a project at my civil-service. I want to fill a old snack-machine with things we need in the ambulance (bandages, cool-packs, etc.)

In order to get the current amount of everything without counting everything all these things should be stored in the snack-machine.
The Arduino should be attached to the signal wires of the machine. If a signal is firing (when a button is pressed) the microcontroller should decrease the current amount of the item in the connected database.. so it is easy to see if some product is running low.

The machine itself works with AC.
 now the problem: I'm not that professional with microcontrollers/hardware and this is my first big project.

If the Arduino is connected between the motherboard of the machine and the buttons the Arduino won't interrupt when something is pressed. I attached a picture of the circuit. (The only thing what's not on the picture are resistors between arduino and the buttons). The voltage on the wires is about 7.5-8 Volts alternative current. [![enter image description here][1]][1]

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

title: Signal reading from existing snackmachine

Answers: 0


body:
I have built a set up with an Arduino UNO hooked up to a switch, so that whenever the switch goes from HIGH to LOW it saves audio to an SD card. I am using the TMRpcm Library. The problem is the current code will only be able to record 1 audio file; I want to the Arduino to run for a long period of time collecting multiple audio files as the switch is turned on and off. I need a way that will allow it so everytime the switch is pushed back down the next file saved will have a different name than the one previously saved (preferably by an increased numeric value eg "1.wav" & "2.wav"). I have tried **audio.startRecording(audiofile+".wav", 16000, A0);** and it makes it so no files save to the SD card accept an empty file simple titled 'WAV'. I have tried using a switch case but it will not allow me to reach a case over 10, without running out of RAM. Currently, my code can save 1 audio file but I want it to reach a point where it can save as many as the SD card can hold, without having to restart the software.

My current code is here. Any help would be greatly appreciated

    //////////////////////////////////////// SD CARD
    #include <SD.h>
    #include <SPI.h>
    #include <TMRpcm.h>
    #define SD_ChipSelectPin 10
    TMRpcm audio;
    //////////////////////////////////////// SWITCH CASE
    int audiofile = 0;     // # of recording
    unsigned long i = 0;
    bool recmode = 0;      // recording state
    //////////////////////////////////////// SWITCH
    int inPin = 2;         // input Switch Pin
    int state = HIGH;      // the current state switch
    int reading;           // the current reading from the switch

    void setup() {
      Serial.begin(9600);
      pinMode(A0, INPUT);  // Microphone
      pinMode(inPin, INPUT_PULLUP); // Switch
      //////////////////////////////////////// SD CARD
      SD.begin(SD_ChipSelectPin);
      audio.CSPin = SD_ChipSelectPin;
    }

    void loop() {

      reading = digitalRead(inPin);
      ////////////////////////////////////////
      while (i < 300000) {
        i++;
      }
      i = 0;
      ////////////////////////////////////////
      if (reading == LOW) {
        if (recmode == 0) {
          recmode = 1;

          Serial.println("Recording");

          audiofile++; // To move case
          audio.startRecording("1.wav", 16000, A0);
        }
      }
      ////////////////////////////////////////
      else if (reading == HIGH) {
        recmode = 0;

        Serial.println("Hung-Up");
        audio.stopRecording("1.wav");
      }
    }

title: Trying to save .wav files with new name every loop

Answers: 1

body:
I would (and do) use `snprintf` to format a string as a filename:

    // Global scope, or local static
    uint32_t myFileNumber = 1;
    char filename[12];

    // in your function - results in 00000001.WAV
    snprintf(filename, 12, "d.WAV", myFileNumber);

d will allow between 00000000.WAV and 99999999.WAV and always with 8 digits. Any more and it will get truncated and corrupted (100000000.WA) but won't cause a buffer overrun. You will have to take precautions that you never have more than 100 million files ;)


body:
I'm basically trying to make a device that pulls the GPS information from a SIM808 and pushes it to a server online via GPRS.

I am sorry as I am not good at programming so ive spent days trying to debug this but i have not been able to figure out whats wrong.

Ill get the basics out of the way.

Board: Mega2560 (I know its overkill but its what i had in hand)
SIM+GPS sensor: SIM808 Module  TinyGPS v13
RTC: DS1307
Arduino IDE v1.8.8

Down to the specifics,
I started with SoftwareSerial Library but i heard it was inefficient so i switched to AltSoftSerial.
The serial library is working as I do get output using AT commands.
The problem is that when i load up the stock TinyGPS example sketch sometimes it works sometimes it gives me error saying the GPS module wasn't detected.

i tried using AT commands directly or a different GPS library but i cant figure out how to pass on data to a database over GPRS.

but basically I am sure the wiring isn't faulty nor is the GPS module (i hope) as it gives an output at ATCommands, even the RTC module is confirmed working. I know the URL in the ATCommand is fake but that is for demonstration purposes.

Coming to the code below. If i change the bool newData = false; to bool newData = true; the the code works just once with wrong GPS information.

any help would be greatly appreciated. Thank You

Edit 1: The problem has been solved, it wasn't working when i used both GPS and GPRS on SIM808 i switched to NeoGPS 6m module and GPRS from SIM800/808 it worked. Thank You.

    #include <AltSoftSerial.h>
    #include <TinyGPS.h>

    #include <Wire.h>
    #include <DS1307new.h>

    TinyGPS gps;

    SoftwareSerial sGPS (46,48);

    uint16_t startAddr = 0x0000;  //Start address to store in NVRam
    uint16_t lastAddr;        //New address to store in NVRam
    uint16_t TimeIsSet = 0xaa55;  //Helper that time must not be set again

    int currentDay = 0;
    int currentMonth = 0;
    int currentYear = 0;
    int currentHour = 0;
    int currentMinute = 0;

    float flat, flon;
    float previousFLat = 0.0;
    float previousFLon = 0.0;

    void setup()
    {

      Serial.begin(9600);
      sGPS.begin(9600);

      /*
      Control the clock.
      Clock will only be set if NV-RAM Address does not contain 0xaa.
      DS1307 should have a battery backup.
      */

      RTC.getRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
      if (TimeIsSet != 0xaa55)
      {
        RTC.stopClock();

        RTC.fillByYMD(2011,4,8);
        RTC.fillByHMS(22,7,0);

        RTC.setTime();
        TimeIsSet = 0xaa55;
        RTC.setRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
        RTC.startClock();
      }
      else
      {
        RTC.getTime();
      }

      /*
       Control Register for SQW pin which can be used as an interrupt.
    */
      RTC.ctrl = 0x00;                      // 0x00=disable SQW pin, 0x10=1Hz,
                                            // 0x11=4096Hz, 0x12=8192Hz, 0x13=32768Hz
      RTC.setCTRL();
      delay(5000);
      }

      void loop()
    {
        RTC.getTime();

        currentDay = RTC.day;
        currentMonth = RTC.month;
        currentYear = RTC.year;
        currentHour = RTC.hour;
        currentMinute = RTC.minute;

      bool newData = false;

      //For one second we parse GPS data and report some key values

      for (unsigned long start = millis(); millis() - start < 1000;)

      {
      while (sGPS.available())
        {
          char c = sGPS.read();
          Serial.write(c); // uncomment this line if you want to see the GPS data flowing
          if (gps.encode(c)) // Did a new valid sentence come in?
          newData = true;
        }

      }

      if (newData)
      {
        unsigned long age;
        gps.f_get_position(&flat, &flon, &age);

        if ((flat !=previousFLat)||(flon !=previousFLon))
        {
          previousFLat = flat;
          previousFLon = flon;
          Serial.print (previousFLat,6);
          Serial.println(previousFLon,6);
          SendSQL();
        }
      }

    }

      void SendSQL()
      {

        //Serial.println("Start Send");
        Serial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
        delay(500);
        Serial.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"");
        delay(500);
        Serial.println("AT+SAPBR=1,1");
        delay(500);
        Serial.println("AT+SAPBR=2,1");
        delay(3000);
        Serial.println("AT+HTTPINIT");
        delay(500);
        Serial.println("AT+HTTPARA=\"CID\",1");
        delay(500);
        Serial.print("AT+HTTPARA=\"URL\",\"www.google.com/add_data.php?");
        Serial.print("addDay=");

          if (currentDay <10)
            {
            Serial.print("0");
            Serial.print(currentDay);
            }

          else
            {
            Serial.print(currentDay);
            }

          Serial.print("/");

          if (currentMonth < 10)
            {
              Serial.print("0");
              Serial.print(currentMonth);
            }

          else
            {
              Serial.print(currentMonth);
            }

          Serial.print("/");
          Serial.print(currentYear);
          Serial.print("&addHour=");

          if (currentHour <10)
            {
              Serial.print("0");
              Serial.print(currentHour);
            }

            else

            {
              Serial.print(currentHour);
            }

            Serial.print(":");

            if (currentMinute <10)

            {
              Serial.print("0");
              Serial.print(currentMinute);
            }

            else

            {
              Serial.print (currentMinute);
            }

              Serial.print ("&addLati=");
              Serial.print(previousFLat, 6);
              Serial.print("&addLongti=");
              Serial.print(previousFLon, 6);
              Serial.println("\"");
              delay(3000);
              Serial.println("AT+HTTPACTION=0");
              delay(15000);
              Serial.println("AT+HTTPTERM");
              delay(500);
              Serial.println("AT+SAPBR=0,1");
              delay(500);
              Serial.println("Finish");
            }

title: Code getting stuck waiting for GPS Output

Answers: 3

body:
You have a Mega with 4 hardware serial ports. Use of those - Serial1, Serial2, Serial 3 - to talk to the GPS.

I did a project with a SIM808 module from DF Robotics.  I spent some time just powering the GPS part of it up and watching what came out.  Do the same with some simple serial print statements.

    if (Serial1.available() >0){
    Serial.print(Serial1.read());
    }

Then when you understand what comes out, you can watch in setup() for the end of messages that indicate you have good GPS data, or just send AT commands until you get a good reply back. My module took I think 7-8 seconds before it would talk, so I just waited in setup() until I started getting messages. I knew what to expect from the above testing, it was always a fixed amount, so I grabbed all that, looked at the last few to make sure it was as expected, then started the GPS commands to see if it had good data from the satellites before continuing. I suspect the TinyGPS library does similar, but the SIM808 module added some extra characters, or you had to add extra characters, to identify GPS commands from the text message commands the SIM808 expected.

body:
I agree with above answer use the Serial ports available and do something in your setup to probe the sim808 until you get some feedback I am using SIM868 in one of my projects and had the same problem of not getting any feedback until i set a while loop up in the setup that was probing by only sending 'AT' to the module (I did not use tinyGPS i only used Serial and sent it AT commands)

[Here the application notes with the AT commands for the GPS side of SIM808][1]

  [1]: https://cdn-shop.adafruit.com/datasheets/SIM808_GPS_Application_Note_V1.00.pdf

This approach will give you a better idea of what is happening and where you are going wrong

body: The problem has been solved, it wasn't working when i used both GPS and GPRS on SIM808 i switched to NeoGPS 6m module and GPRS from SIM800/808 it worked. Thank You.


body:
What should one expect when the following program runs on Arduino Uno?

    void setup()
    {
        Serial.begin(9600);
        DDRD |= 0b11;
    }

    void loop()
    {
        PORTD |= 0b11;
        delay(100);
        Serial.print("ABCD");
        PORTD &= ~0b11;
        delay(100);
        Serial.print("DEFG\n");
    }

When Serial.begin() is used, the pins PD0, PD1 might be configured as UART pins. After that if DDR is used, are the pins configured as GPIO, or are they still UART Rx, Tx pins?

title: toggling Rx, Tx pins after Serial.begin

Answers: 1

body:
As always, the answer is in the datasheet:

> * TXD/PCINT17 – Port D, Bit 1
>
> TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output **regardless of the value of DDD1.**
PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
>
> * RXD/PCINT16 – Port D, Bit 0
>
> RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input **regardless of the value of DDD0.** When the USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.

As to what trying to set the output level on the TX pin would have, only experimentation can show.  It's not defined in the datasheet (because who would do it?)