texts: SIM800L and Arduino Sleep - getting whimsy Serial output after 5 calls

texts:
i'm working on project where i'm trying to achieve that arduino parse caller ID so i can use it later to send SMS with sensor reading data.

Somehow i made that code (with much googling) and it works great... But when i include arduino sleep part, it does work at beginning, but after i call SIM800 4-5 times with distinct of 30 seconds, i get unusable data on Serial, so i can't no longer parse correct number.

I tried many things, dropping baud rate to 1200, changing delay, but still i get strange characters after few calls.

Can anyone help me?

P.S. ATMEGA328P ic MCU

Thank you,
Matija

#include <SoftwareSerial.h>
#include <avr/sleep.h>

SoftwareSerial SIM800(8, 7);

String buffer1;
unsigned int current_millis = 0;
String phone;

void setup() {
     buffer1.reserve(200);
     phone.reserve(20);

     Serial.begin(19200); //
     SIM800.begin(9600);
     delay(1000);
     SIM800.write("AT\r");  // because of SIM800L autobounding mode
     delay(1000);
     SIM800.write("AT+IPR=9600\r");  // set baud at 9600, i tried with 1200
     and  other, and with autobauding but still got same problem
     delay(1000);
     SIM800.write("AT+CMGF=1\r");  // set SMS mode to text
     delay(1000);
     SIM800.write("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     Serial.print(SIM800.readString());
     SIM800.write("AT+CLIP=1\r\n");
     delay(1000);
     SIM800.write("AT+SGPIO=0,7,1,0\r");
     delay(1000);
     SIM800.write("AT+CSCLK=2\r"); //power saving mode of SIM800L
     delay(1000);
     current_millis = millis();
}

void loop() {
   // put your main code here, to run repeatedly:
   if (SIM800.available() > 0) {
      buffer1 = SIM800.readStringUntil('\n'); //Saving string then parsing
           caller number from it
      Serial.println(buffer1);
      parse();
      current_millis = millis();
      }

    if ((millis() - current_millis) > 10000) { //Putting atmega tu sleep
       sleepNow();
       delay(1000);// tried many delays
       current_millis = millis();
     }

 }

void parse() {
    if (buffer1.indexOf("CLIP:") > 0) {
        phone = buffer1.substring(buffer1.indexOf("+CLIP: ") + 8,
        buffer1.indexOf("+CLIP: ") + 21); //parsing caller number
        Serial.println(phone);
        SIM800.write("ATH\r"); //hang out phone call
        delay(500);
        SIM800.write("ATH\r");
        delay(500);
  }

}

void sleepNow() { //PIN CHANGE INTERRUPT ON PIN 7,8 BECAUSE SOFTWARE SERIAL
                   LIBRARY USE IT AND IT WILL WAKE UP ATMEGA
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set herethe
                                          sleep bit in the mcucr register
    sleep_mode();            // here the device is actually put to sleep!!
                         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable
                                sleep...
    }


texts: Need lot GPIO pins on arduino mega - what are restrictions?

texts:
I would like to use as much as possible GPIO pins on Arduino Mega especially with (mis)using pinMode(x,INPUT); and pinMode(x,INPUT_PULLUP); to achieve two things at the same time - drive something else by the pin weakly down or up and measure the logical level there with digitalRead(x) to detemine, if that "something else" is input, or outputting some logical level.

Also I need I2C, Serial over USB and nothing else.

On Arduino UNO/nano/micro/pro it works just fine for Digital pins (except D0/D1 (RX/TX), D13 (LED as strong pull-down), A4/A5 (I2C) and A6/A7 which are not digital IO). The problem is limited number of pins, so I bought ArduinoMega.

The question is - which pins can be used that way there?
So far I am aware of D0/D1 (RX/TX), D20/D21 (I2C) and D13 (LED).
The rest (D2-D12, D14-D19, D22-D52 and A0-A15) seem aviable and usable.
Or I am missing something else?

Are there some libraries/objects I should disable to not interfere with my script?

Thank you.


texts:
I am trying to upload the Marlin Firmware to my 3D printer's Arduino Mega 2560 and I am experiencing a problem. It keeps saying:

qr_solve.cpp:7:18: fatal error: time.h: No such file or directory
 #include <time.h>
                  ^
compilation terminated.
Error compiling.

Please help as I'm lost as how to fix it, because I try to scroll up to see what is highlighted in red and I can't find anything.


texts:
I have the strange pb.
My esp8266 was working fine with my DHT22 and then failed every time.
I loaded an example sketch in a other ESP8266 and I have the same pb.... until I shut down -> up the DHT22 when the ESP8266 is working.
To check more, I added this at the setup before dht.begin() :

      digitalWrite(0, LOW); // turn the LED on (HIGH is the voltage level)
  delay(1000); // wait for a second
  digitalWrite(0, HIGH);

And it works. But I don't know why I need to do this "pull up".
PS : I already tried with or without the 10K resistor, same pb.
PS2 : I already tried with 3.3v or 5V for DHT22. Same pb.

Any idea ?


texts: how do i fill an array from a grayscale sensor (SKU:SEN0147)?

texts:
I'm designing a safe lock of 4 digits, but the password is in terms of colors, I have 3 colors. we are obliged to use a grayscale sensor (SKU: SEN0147).

The assignment is as follows:

Write a program on Arduino that will be used as a safe lock. Consider having 3 colors black white and grey. Black = 0, Red = 1 and White = 2.

• When the microcontroller is turned on, the safe is locked. The Serial Monitor should display: “System is online.”

• The combination lock should be saved in an array of integers called arr_code.

• The user has 3 trials to open the safe

• The system will wait for the user to enter 4 colors. To enter a color, the grayscale sensor should be place on top of the desired color. Once ready the push button is pressed. Once released, the color is saved in another array called arr_user_code.

• Once 4 colors are entered, the system should test automatically if the code entered by
the user is equal to the code saved in arr_code.

• If the wrong code is entered, the serial monitor displays: “Wrong Code. Try Again.”

• If the user enters the wrong code 3 times in a row the system is locked and a message is
displayed: “System Locked.”

• If the correct code is inserted, the Led on pin 13 is turned on.

• The combinations entered by the user should be displayed on the Serial Monitor. The Arduino program should be clear, separated into functions and documented.

The program I wrote is the following:

char led_pin = 13;
char pb_pin = 4;
int gs_pin = A3;

int arr_code[4] = {14, 14, 14, 14};//color im testing on
int arr_user_code[4];

int counter;
int Lock_Interval = 2500;
bool compare;

bool equal = true;

bool Array_Compare(int *a, int *b) {//function for comparision
  for (int i = 0; i < 4; i++) {
    if (a[i] != b[i]) return false;
  }
  return true;
}

void Button_Wait(int buttonPin) {//function to sense if button is pressed
  int curr_state;
  int prev_state;

  while (1) {
    prev_state = curr_state;
    curr_state = digitalRead(buttonPin);
    if (curr_state != prev_state) {
      if (curr_state == false) {
        delay(10);
        return;
      }
    }
  }
}

int GS_Value(int gsPin) {//function to get GSsensor value
  Button_Wait(pb_pin);
  int gs_value = analogRead(gs_pin);
  return gs_value;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(led_pin, OUTPUT);
  pinMode(pb_pin, INPUT);

  Serial.begin(9600);//sync

  digitalWrite(led_pin, false);//start with a turned off LED
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("System Online");
  Serial.println("Please Enter Passcode: ");

  for (counter = 0; counter < 3; counter++) {
    for (int i = 0; i < 4; i++) {
      arr_user_code[i] = GS_Value(gs_pin); //uploading GSsensor values to array !!!the problem is here!!!

      Serial.print('GS_Value');//printing GSsesnor values on monitor
      Serial.print(" ");//inserting space
    }
    Serial.println(" ");//skipping a line after every attempt

    compare = Array_Compare( arr_code[4], arr_user_code[4]); // compare arrays and return false if not equal

    if (compare == true) {//in case arrays are equal
      Serial.println("System UNLOCKED!");
      digitalWrite(led_pin, true);
    }

    else if (compare == false) {//in case arrays arent equal
      Serial.println("Wrong Passcode. Try Again");
    }
  }

  if (compare == false) {
    Serial.println("System LOCKED");
    while (1) {
      Lock_Interval = Lock_Interval * 2;
      delay(Lock_Interval);
      return;
    }
  }
  delay(100);
}

the issue is that the arr_user_code isnt actually filling with the correct sensor values but a value between 20000 and 30000. Thank you in advance.


texts:
I'm using PROTOCENTRAL ADS1262 32-BIT PRECISION ADC BREAKOUT BOARD to read the voltage in simple a load cell.

The connections follows the instructions on its library

But I cannot make it work, the readings has lots of spikes and i cannot discover what is happening.

Can someone help?


texts:
#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt = random(0, 101);
};

#endif

I have a header file with a struct like above but when I compile I get this error:

'random' was not declared in this scope

How can I use random() in a header file?


texts:
I've mounted an Ethernet Shield on top of an Arduino UNO. The Arduino is connected via usb to my pc and to the network via ethernet through a switch.
I'm running a simplified verison of the WebServer example and the function to Ethernet.begin() always returns EthernetNoHardware.
I've tried different setups changing the ethernet cables and connecting directly to the router. I also tried adding specific ip, gateway and subnet parameters to Ethernet.begin() however the output doesn't change and the server can't be reached:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xCC, 0x1E }; //mac address on the sticker
IPAddress ip(192, 168, 1, 134);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
IPAddress DNSserver(192,168,1,1);
EthernetServer server(80);

void setup() {
  Ethernet.init(10);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Ethernet.begin(mac, ip, gateway, subnet);

  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield not found.");
  }

  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

output:
Ethernet shield not found.
server is at 192.168.1.134

Any idea on what the issue might be?


texts: how can i achieve a TTL pulses with duration of 1ns and what board do I need

texts:
Hi I need to supply TTL pulses to my driver to get a 1ns pulse with 20KHz.

Is that possible with Arduino? what is the board and setting I need?

thanks


texts: Arduino Uno rev 3 toggling a 230 V submersible pump on intervals

texts:
I am software programmer and hobby farmer. While I was working on a hydroponic farming stuff, I had to use submersible pumps with timers. I don't want to buy timers that are actually a tedious scheduling process. so I am making one myself.

I want to toggle 230 V for turning a submersible pump(150-230 V and 18 W) ON/OFF. I read that Arduino may not able to supply enough input current that the relay requires. I am not sure about what transistor to use to amplify the input current. I came across a circuit diagram and a relay board. Do I still need to use a transistor and diode if I use this relay with an Arduino?

This is the two-channel relay I am about to use and the circuit is below.

Should I follow the circuit if I am using this relay? The relay has a tolerance of 250 V. What if the voltage fluctuates above 250 V? I am going to use a 9 V battery to power the Arduino. Feel free to explain anything that I may have to know.

UPDATE

Thanks marla for making it clear that I don't need diodes and transistors. Andy, as you said, I can't keep changing batteries often, and it will limit the system. Shall I use an adapter which reads output 5 V and 1 amperes? Will that drive the Arduino and be sufficient for both the relays?


texts: NEO-6M is working but it doesnt show data

texts:
So I'm having a little bit of difficulty here in my NEO-6M. The problem is it doesn't show any data in my serial monitor. My NEO-6M Led is already blinking so its already ok.

RX -> Pin3 , TX -> Pin4 , VCC -> 3.3v , GND -> GND

  Serial Monitor:

Code:
https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino


texts: Monitoring Power Down Using Arduino UNO and ZMPT101B

texts:
I am in the process of implementing power down alerting system suing Arduino UNO and ZMPT101B Single phase relay.

My code as follows,

#include <Filters.h> //Easy library to do the calculations

float testFrequency = 50;                     // test signal frequency (Hz)
float windowLength = 40.0/testFrequency;     // how long to average the signal, for statistist

int Sensor = 0; //Sensor analog input, here it's A0

float intercept = -0.04; // to be adjusted based on calibration testing
float slope = 0.0405; // to be adjusted based on calibration testing
float current_Volts; // Voltage

unsigned long printPeriod = 1000; //Refresh rate
unsigned long previousMillis = 0;

void setup() {
    Serial.begin( 9600 );    // start the serial port
}

void loop() {

    RunningStatistics inputStats;                //Easy life lines, actual calculation of the RMS requires a load of coding
    inputStats.setWindowSecs( windowLength );

    while( true ) {
        Sensor = analogRead(A0);  // read the analog in value:
        inputStats.input(Sensor);  // log to Stats function

        if((unsigned long)(millis() - previousMillis) >= printPeriod) {
            previousMillis = millis();   // update time every second

            Serial.print( "\n" );

            current_Volts = intercept + slope * inputStats.sigma(); //Calibartions for offset and amplitude
            current_Volts= current_Volts*(40.3231);                //Further calibrations for the amplitude

            Serial.print( "\tVoltage: " );
            Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

            if (current_Volts <229) {
                test_loop();
            }
        }
    }
}

void test_loop(){
    Serial.print( "Warning!! Server Room Power Down" );
    delay(1000);
}

I am getting the correct voltage reading. When power down it says power down. But when power got up, it still shows power down with older reading. I think the reason for this because my code unable to stop the loop. And if I remove the delay (1000) in test_loop function it works, But my intention to use this sms alerting system and for that I need this delay to stop unnecessary alerts.

My code for SMS Alerting,

Serial.print( "\tVoltage: " );
Serial.print( current_Volts ); //Calculation and Value display is done the rest is if you're using an OLED display

if (current_Volts <229) {
    SendMessage();
}

void test_loop() {
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
    delay(1000);  // Delay of 1000 milli seconds or 1 second
    mySerial.println("AT+CMGS=\"xxxxxxxxx\"\r"); // Replace x with mobile number
    delay(1000);
    mySerial.println("Warning!! Server Room Power Down");
    delay(100);
    mySerial.println((char)26);// ASCII code of CTRL+Z
    delay(150000);
    mySerial.println("AT+CMGD=2");
}

This code works for the very first outage but after power up also it send power down. First part of serial priniting in test_loop code of Serial.print is used for debugging.


texts: How to modify current driver files in USB_Host_Shield2.0 on github for Arduino Mega ADK USB driver for Epson LQ-310 printer?

texts:
At the moment, I am engaged in a project in which I have to drive Epson LQ-310 printer with Arduino Mega ADK (USB Host). There is already a library  USB_Host_Shield_2.0 on Github which includes usb drivers for keyboard, flash drive etc. but not for a printer.

I am thinking to modify the current header files (adk.h and adk.cpp) based on Android drivers to suit for a printer. Do the things workout in this way?

Could anyone of you please suggest me the things to modify to achieve the required functionality?

Thank You


texts:
I am trying to make some data logging conserining physiological data coming from a bitalino.
My problem is that I would like to collect samples at something like 1 kHz, that is the rate that the bitalino can read the sensors, but I think that the time needed
to write this data to the SD card can't keep up with the speed, and here is why i think that:

I put in the script some timers to check what was consuming the time causing to low sample rate, resulting:

Bitalino: 0, SD: 27
Bitalino: 0, SD: 28
Bitalino: 2, SD: 26
Bitalino: 0, SD: 29

Being that the time in miliseconds.

void loop() {
    time = millis();
    readBIT();
    time2 = millis();
    printDataSD();
    time3 = millis();
    printData();
}

void printData() //Send the data acquired to the pc through the serial port
{
  Serial.print("Bitalino: ");
  Serial.print(time2-time);
  Serial.print(", SD: ");
  Serial.println(time3-time2);
}

void printDataSD() //Send the data acquired to the SD Card
{
    if (myFile) {
    //Bitalino
    myFile.print(_ECG);
    myFile.print(",");
    myFile.print(_EMG);
    myFile.print(",");
    myFile.print(_EEG);
    myFile.print(",");
    myFile.print(_EDA);
    myFile.print(",");
    //Time
    myFile.println(time);
    myFile.flush();

    } else {
    Serial.print("error opening file, ");
    SD.begin(10);
    delay(1000);
  }
}

I would like to know if there is a way to improve my sample rate.

Thank you!

Here is the readBit() like asked:

void readBIT() //Read IMU data
 {
  _ECG = analogRead(ECG);
  _ECG = ((_ECG/1024) - 0.5)*Vcc*1000/gECG; //mV

 _EMG = analogRead(EMG);
 _EMG = ((_EMG/1024) - 0.5)*Vcc*1000/gEMG; //mV

 _EEG = analogRead(EEG);
 _EEG = ((_EEG/1024) - 0.5)*Vcc*1000000/gEEG; //uV

 _EDA = analogRead(EDA);
 _EDA = (_EDA/1024*Vcc-0.259388)/gEDA; // revolution
 }


texts: Is there a sketch that supports the receiving of email using the Arduino environment on the ESP8266? I can only find support for sending email. I know it's possible because the NodeMCU environment supports it. Any help is appreciated!


texts: avrdude: stk500_recv(): programmer is not responding: lilypad arduino

texts:
i realise this is probably the most common error that is asked about on this forum, but it is a major issue for me. i have an arduino lilypad main board (with the ATMega328P, boot loader already burned), and a generic FTDI serial to usb adapter plugged into my windows 10 laptop. When i try to upload the Blink program from the Arduino IDE, it fails with the error:

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

i am using a windows 10 laptop, the Arduino IDE from the windows store. this is a new lilypad, and i have never been able to upload to it. take note that when i reset the board, the pin13 light does flash (but  not the way the Blink program specifies, obviously.

i have already tried:

Rebooting my computer
Restarting the IDE
Turning the COM port on and off
Taking out the RX/TX wires from the FTDI converter
Pressing the reset button right before uploading (or during uploading)
Changing which board it is set as in the IDE
Unplugging and re-plugging the USB-Serial converter

if you have any other possible solutions they would be appreciated, thanks


texts: How to program the joystick button to reset everything?

texts:
In this project, I'm making a stickman rush game with a joystick. Where when the joystick moves up and down, the stickman also moves up and down. And there are obstacles, that when the stickman touches one of them it prints out "Game Over.."
Now I'm trying to make the button in the joystick (SM) programmed, that whenever it is clicked, everything resets. In other words, everything goes back to the original screen where the stickman and obstacle first started.
Code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

byte customChar[] = {
  B01110,
  B01110,
  B01110,
  B00100,
  B01110,
  B10101,
  B00100,
  B01010
};

byte gameObstical[] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111
};

int vX = A0;
int vY = A1;
int sw = 8;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

int screenWidth = 16;
int screenHeight = 2;

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

  pinMode(vX, INPUT);
  pinMode(vY, INPUT);
  pinMode(sw, INPUT_PULLUP);

  lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();
  lcd.write(byte(0));

  lcd.createChar(1, gameObstical);

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManRow = 0;
  int obsticalRow = 0;

  int obsticalPosition2 = 0;
  int obsticalRow2 = 0;

  for (obsticalPosition = 15; obsticalPosition >= 0; obsticalPosition--) {
    lcd.setCursor(obsticalPosition, obsticalRow);
    lcd.write(byte(1));
    lcd.print(" ");
    delay(150);

    xPosition = analogRead(vX);
    yPosition = analogRead(vY);
    SW_state = digitalRead(sw);
    mapX = map(xPosition, 20, 1003, -500, 500);

    Serial.println("-----------");
    Serial.println(mapX);
    Serial.println(SW_state);
    Serial.println("-----------");

    if (mapX > 200) {

      lcd.clear();
      lcd.setCursor(stickManPosition, stickManRow);
      lcd.write(byte(0));

    } else if (mapX < -200) {

      stickManRow = 1;

      lcd.clear();
      lcd.setCursor(stickManPosition, stickManRow);
      lcd.write(byte(0));
    }

    if (stickManPosition == obsticalPosition) {
      if (stickManRow == obsticalRow) {

        lcd.clear();
        lcd.print("Game Over...");
        delay(10000);

      }

      if (obsticalPosition == 12) {

        for (obsticalPosition2 = 11; obsticalPosition2 >= 0; obsticalPosition2--) {
          obsticalRow2 = 1;

          lcd.setCursor(obsticalPosition2, obsticalRow2);
          lcd.write(byte(1));
          lcd.print(" ");
          delay(150);
        }
      }
    }
  }
}

Any ideas? Thanks for reading


texts: Is it correct to use a 9V 1A transformer to power my project?

texts:
I have a quick question:

I have a small alarm project running on an ArduinoNanoV3 (a chinese clon). Counting sensors, actuators and the arduino itself the consumed current (theoretically speaking, calculated by the data provided by the datasheets) doesn't approach to a max of 300mA. Now, the way I plan to feed the project is using a 110V (AC) transformer that gives me 9V output with 1A maximum output. My fear is the output of this transformer (that says 1A) when in all places recommend not to use sources that give currents greater than 500mA when you are going to feed it by the pin VIn with 9V.

My question is: if my project is not going to consume more than 300mA, is there any danger/trouble when connecting the 9V ~ 1A transformer for energize my Arduino based project?


texts:
My code: https://pastebin.com/UmdK33U2

I made a menu so I can send commands. First I connect to the wifi and then I send the command to send a request.

Then when it detects the key datos(); goes true, so the loop detects that and it starts sending requests.
After 2 requests it just doesnt continue.

What I can do?

Btw im using a ESP32.

Thank you!

boolean datos = false;

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "ssid";
const char* password = "pass";

//removed the password and ssid for security, it was there before.
void setup() {
  pinMode(2, OUTPUT);
  Serial.begin(115200);

  while (!Serial)
    ;
  Serial.println("===================================================");
  Serial.println("Welcome to the menu, choose what do you want to do:");
  Serial.println("1º Connect to the Wifi | W");
  Serial.println("2º Scan Wifi | S");
  Serial.println("3º Send data to Website | D");
  Serial.println("===================================================");
  Serial.println("Made by Francine and Javi.");
  Serial.println("===================================================");
}

void scanwifi() {
  int n = WiFi.scanNetworks();
  Serial.println("===================================================");
  Serial.println("Scan have been finished.");
  Serial.println("===================================================");
  if (n == 0) {
    Serial.println("===================================================");
    Serial.println("No networks have been found.");
    Serial.println("===================================================");
  } else {
    Serial.print(n); // imprimir en el puerto serial el # de redes encontradas
    Serial.println(" networks have been found.");
    for (int i = 0; i < n; ++i) {
      // SSID: Nombre de la red; RSSI: Potencia de la red en dBm
      Serial.print(i + 1); //iniciamos en la red # 1...
      Serial.print(": ");
      Serial.print(WiFi.SSID(i)); //Imprime el nombre de la red
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i)); //Imprime la potencia de la señal en dBm
      Serial.print(")");
      byte encryption = WiFi.encryptionType(i); // en la variable encryption, guardamos el tipo de encriptación de la red
      Serial.print(" Encryption Type: ");
      Serial.println(encryption, HEX); // imprimimos el tipo de encriptación: 2: WPA, 5: WEP, etc.
      delay(10);
    }
  }
}

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);

    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");
  delay(1000);
  setup();
}

void loop() {
  if (Serial.available()) {
    char ch = Serial.read();
    if (ch == 'w' || ch == 'W') {
      conectarsealwifi();
    }
    if (ch == 'S' || ch == 's') {
      scanwifi();
    }
    if (ch == 'd' || ch == 'D') {
      datos = true;
      Serial.println(datos);
    }
    if (datos == true) { // si esta habilitado el sending de datos haz
      //randomN = random(200);
      if (WiFi.status() == WL_CONNECTED) {
        digitalWrite(2, HIGH);
        HTTPClient http;

        http.begin("removedtheurl"); //Specify the URL
        int httpCode = http.GET();                            //Make the request

        if (httpCode > 0) { //Check for the returning code

          String payload = http.getString();
          Serial.println(httpCode);
          Serial.println(payload);
          Serial.println("===================================================");

        } else {
          Serial.println(
              "Error on HTTP request, reminder maybe its cloudflare shit.");
        }
        http.end(); //Free the resources
        digitalWrite(2, LOW);
      }
      delay(2000);

    } else {

    }
  }
}


texts: DHT11 Module and I2C LCD coding error on Arduino Uno

texts:
This isn't my first time using an Arduino, but it has been a while, so I've been reviewing using a study kit. It has a DHT11 humidity-temperature sensor module, and an I2C LCD module. The included manual has instructions for it but it just gives the circuit layout and the code. It doesn't really explain anything. So when I tried uploading the code, I got a "expected primary-expression before '.' token" error message. Can anyone help me deciphering the error so it can be fixed? I would greatly appreciate it.
I've attached the code below.
/*****************************************************
 * name:Humiture Detection
 * function:you can see the current value of humidity and temperature displayed on the I2C LCD1602.
 ******************************************************/
//Email:support@sunfounder.com
//Website:www.sunfounder.com

//include the libraries
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

//dht DHT; //create a variable type of dht

const int DHT11_PIN= 4;

void setup()
{
  Serial.begin(9600); //initialize the serial monitor
//  lcd.init();  //initialize the lcd
  lcd.backlight();  //open the backlight
}

void loop()
{
  // READ DATA
  //Serial.println("DHT11:");
  //read the value returned from sensor
  int chk = DHT.read11(DHT11_PIN);
  switch (chk)
  {
    case DHTLIB_OK:
        //Serial.println("OK!");
        break;
    case DHTLIB_ERROR_CHECKSUM:
        //Serial.print("Checksum error,\t");
        break;
    case DHTLIB_ERROR_TIMEOUT:
        //Serial.print("Time out error,\t");
        break;
    default:
        //Serial.print("Unknown error,\t");
        break;
  }
 // DISPLAY DATA
lcd.setCursor(0, 0);
 lcd.print("Tem:");
 Serial.print("Tem:");
 lcd.print(DHT.temperature,1); //print the temperature on lcd
 Serial.print(DHT.temperature,1);
 lcd.print(char(223));//print the unit" ℃ "
 lcd.print("C");
 Serial.println(" C");
 lcd.setCursor(0, 1);
 lcd.print("Hum:");
 Serial.print("Hum:");
 lcd.print(DHT.humidity,1); //print the humidity on lcd
 Serial.print(DHT.humidity,1);
 lcd.print(" %");
 Serial.println(" %");
 delay(200); //wait a while
}


texts: New Microcontroller - programmer is not responding -

texts:
I got an Arduino and after I was playing with it, I noticed that its internal micro controller si removable and decided to buy another micro controller. After I got the new one (atmega328P) and replaced with the original which came with the Arduino, I started to upload a sketch but it does not work.

I get the following:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

If I use the Original MC which came with the Arduino works fine, but with the new one it does not.

Did I buyed a bad/wrong MC, or I need to make something else?
Both have the same name :

ATMEGA328P-PU

The new micro controller has already a boot loader installed.


texts: Teensy4.1 with 2x 8MB PSRAM Chips: external_psram_size=0 but EXTMEM char[] works as expected?

texts:
So I got 2x PSRAM chips from PJRC with my Teensy4.1 and soldered them on (it's a hideous job as I lost my tips) but it's all tested with a multimeter and the connections are solid.
I ran the memtest sketch from here compiled in both Teensyduino and PlatformIO:
https://www.pjrc.com/store/psram.html
Aaaaand external_psram_size is reading 0 for both cases. Setting the memory size manually in the program also fails (even with 8MB).
However... EXTMEM vars work as expected. I'm not sure how the mem addressing actually works with the provided memtest program, either - it certainly doesn't seem to use EXTMEM anywhere.
Here's my memory tester (run to crash):
EXTMEM char bigBuf[10000000];
//char bigBuf[10000];
int c = 0;
void setup() {
  c = 0;
}

void loop() {
  bigBuf[c] = 'a';
  Serial.println(bigBuf[c]);
  Serial.println(String(c));
  c = c + 1000;
  delay(1);
}

Output with EXTMEM char[]: (as expected overflowed until 16MB)
a
0
a
100
...
a
16777100
a
16777200

Output with internal mem char[]: (as somewhat expected overflowed at 512K - max of RAM1)
a
0
a
100
...
a
488081
a
489081

Anyway, I'm glad EXTMEM works.. But can someone explain what's going on with the provided memtest? I admit I didn't read it over very well, but I thought that PSRAM could only be accessed via EXTMEM; how is it addressing otherwise?


texts: Can I improve this code (replacing delays with something else)?

texts:
Building upon my previously solved question Ultrasonic Sensor range finder help (Solved).

Is there a better way to make the LED blink than using a delay and stopping all the rest of the code? For example, the LED is set to turn on, then shortly after turn off. Is there a better way to do this?

For example, if the LED is turned on, it then delays the code, which means it has to wait for the delay to be over, turn off, then change its pattern. For example, allow the Arduino to interrupt the blink with a new interval blink, mid blink? I'm sorry if this is confusing, it's tough to explain.

Simply put, is there a better function than delay() that can allow the Arduino to suddenly change the state of the LED while it is waiting on a delay() to finish?

The code I'm working on is this:

#include <NewPing.h>
#define TRIGGER_PIN  15
#define ECHO_PIN     2
#define MAX_DISTANCE 500
int LED1 = 3;
int LED2 = 16;
int LED3 = 9;
int LED4 = 6;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
}

void loop() {
  delay(50);
  unsigned int uS = sonar.ping_median(10);
  int IN = sonar.convert_in(uS);
  if (IN <= 5) {
    analogWrite(LED4, 255);
    delay(100);
    analogWrite(LED4, 0);
  } else if (IN >= 5 && IN <= 12) {
    analogWrite(LED4, 1);
    delay(200);
    analogWrite(LED4, 0);
  } else if (IN >= 13) {
    analogWrite(LED4, 100);
    delay(300);
    analogWrite(LED4, 0);
  }
}


texts:
Hey guys I have a led grid. it's 8 sides that are addressable with the bytes '1' through '8'. (a Kinect is sending these bytes through processing)  I have also creates three buttons in processing that change the colour of the leds. ('R','G','B').

I'm stuck in the code, my code now when receiving the bytes: 'R', 'G' or 'B' changes all leds to that colour. instead of remembering the colour and only lighting up the sides determined by the '1', '2', '3', '4', '5', '6', '7', '8' values.

I need it to remember the chosen R,G,B colour until another colour is chosen and only  use the bytes '1', '2', '3', '4', '5', '6', '7', '8' to select what side of the grid to light up.

Here is my code so far:

#include <FastLED.h>

#define LED_PIN     6
#define NUM_LEDS    360

CRGB leds[NUM_LEDS];
CRGB saved_color;

void setup()
{
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);

  Serial.begin(9600);

  FastLED.clear();
  FastLED.show();

}

void loop()
{

  if (Serial.available() > 1)
  {
    int incomingByte = Serial.read();

    if (incomingByte > '0' && incomingByte < '9')
    {
      FastLED.clear();
    }

    if (incomingByte == 'R') {
      saved_color = CRGB(255, 0, 0);
    }
    else if (incomingByte == 'G') {
      saved_color = CRGB(0, 255, 0);
    }
    else if (incomingByte == 'B') {
      saved_color = CRGB(0, 0, 255);

    }

    if (incomingByte == '1')
      for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '2')
      for (int i = 44; i <= 89; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '3')
      for (int i = 90; i <= 134; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '4')
      for (int i = 135; i <= 179; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '5')
      for (int i = 180; i <= 224; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '6')
      for (int i = 225; i <= 269; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '7')
      for (int i = 270; i <= 314; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '8')
      for (int i = 315; i <= 359; i++) {
        leds[i] = saved_color;

      }

    FastLED.show();
  }
}

I'll describe the project a bit more to elaborate. It's a lamp (octagon shape) with 45 leds on the 8 sides. each side is triggered by movement and  sends a byte ('1', '2', '3', '4', '5', '6', '7', '8') to turn on one side of the lamp.

I want to be able to select the colour before sending the bytes. so I need arduino to remember the 'R', 'G', 'B' bytes and only change when I send the other byte.


texts: Digispark Micro (ATTINY85) not working on Macbook Pro 2016

texts:
I just bought 2 Digispark Micro to start learning some Arduino things.

But when I try to upload the code to my Digispark, it just send me an "Device search timed out" error.

My Digispark is plugged with an USB-C to USB connector and the Red dot on the Digispark is working. The connector is working well with any other device.

Arduino app (1.8.9) settings:

Tools

Board → Digispark (Default - 16.5 mhz)
Programmer → Micronucleus

I tried using the micronucleus CLI, but, even if I try plug/unplug several times (~10s between each unplug/plug) I got this :

> Please plug in the device ...
> Press CTRL+C to terminate the program.


texts: How would i capture and split serial data?

texts:
How would i capture the following serial data, and split it into parts?
<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

the parts i need from this is
Alarm - This is a state. i.e Alarm, Idle, Paused, Working
MPos: - This is a series of positions X,Y,Z
WPos: - This is a series of positions X,Y,Z

What i want to do is capture the string from serial (See above for formatting)
Then display the information on the LCD.

i.e.
X: 0.000  Y:0.000
Z: 0.000  Idle

I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.


texts:
Is it garanteed (with some precision) that the phase of a PWM-signal generated by tone is the same on each pin? Can it be altered (by internal means of Arduino) so that it's different on different pins?

I'm looking for a way to adjust phases of signals from several pueso-buzzers by either adjusting distances (least preferrable) or programmaticaly (most preferrable) or by external components (if they're not very complicated).


texts:
I have a Problem with my code.

My Goal is to receive a Ethernet message via UDP and send the message back via CAN.

It works fine but only with the first packet I send. When I send the same packet again there is no Response as you can see in the screenshot.
I´m using the Arduino Due with a Transceiver. The Programm which sends and reads the Messages is Vector Canoe

#include "variant.h"
#include "due_can.h"
#include "Arduino.h"

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

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

EthernetUDP Udp;

void setup() {

Can0.init(250000);
Serial.begin(9600);

Ethernet.begin(mac, ip);
Udp.begin(localPort);

}

void loop() {

    int packetSize = Udp.parsePacket();
    Udp.read(packetBuffer,packetSize);

   if (packetSize)
  {

    int Canframestosend= packetSize/8;    //Divides the Ethernet packet by 8 to match with CAN packet
    int count =0;
    int Rest=packetSize%8;                //Needed if the Ethernet packetsize isn´t a multiple of 8

    for(int j=0;j<=Canframestosend;j++){

    CAN_FRAME NewFrame;                   //CAN frames which are sent
    NewFrame.id=0xFA;                     //ID of the frames
    NewFrame.length=8;                    //Maximum of bytes a Can frame can have

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

       NewFrame.data.byte[i] = packetBuffer[count]; //Write the Ethernet info byte by byte on the CAN frames
       count++;
       }
    if(packetSize<count){
      NewFrame.length=Rest;                         //Shortens the last frame to avoid unnessecary zeros
      }
       Can0.sendFrame(NewFrame);

      }

   }
   delay(10);
}

Maybe there is an endless Loop but I don´t know which and why.

Hope anybody can help me with that!


texts: How do I sense that the serial monitor is started?

texts: When starting the serial monitor in IDE I want to save important data to EEPROM before the Arduino Uno restarts. I do not have physical access to the Arduino so a "press button" solution does not work here.


texts: Fail getting readings from Radar sensor HW-MS03

texts:
I try to work with a new sensor - HW-MS03 v.06 sensor. Connecting it pin to pin (v+ to 5v, Sig to digital-input, and GND to GND ), both to Arduino Uno and ESP8266 Wemos mini, and got same results:
Only once on every port I got proper readings ( 1 for detection for 2 sec, and 0 for no- detection). Most of the time it was a solid 1.
Code was very simple , just printing its digitalRead of the designated pin.
When tried to pull-down the signal, using a 1K resistor, It never got 1 again.
To be sure it is not a malfunctioned sensor I tried with the other one I have, but again- same results.
link to purchased product
Appreciate any help.
Guy


texts:
I bought some 'lucky dip' IR sensors from China, no idea what they are, but they appeared to get lost in the post so instead I bought some of these from a reputable place in the UK that come with a datasheet.

The next day, both items arrived together!

I'm trying to build a very simple proximity sensor for a robot, I built the following circuit:

simulate this circuit – Schematic created using CircuitLab

and stole this code to test it out:

#define IRledPin 8
#define D13ledPin 13
#define IRsensorPin 9

void IR38Write() {
  for(int i = 0; i <= 384; i++) {
    digitalWrite(IRledPin, HIGH);
    delayMicroseconds(13);
    digitalWrite(IRledPin, LOW);
    delayMicroseconds(13);
  }
}

void setup(){
  pinMode(IRledPin, OUTPUT);
  digitalWrite(IRledPin, LOW);
  pinMode(D13ledPin, OUTPUT);
  digitalWrite(D13ledPin, LOW);
}

void loop(){
  IR38Write();
  if (digitalRead(IRsensorPin)==LOW){
    digitalWrite(D13ledPin, HIGH);
  } else {
    digitalWrite(D13ledPin, LOW);
  }
}

If I hold my hand in front of it, nothing happens (LED on-board arduino should light up), however if I point a TV remote at it and press a button, the LED lights up. I tested 2 of the 'fancy' sensors that I got and both behaved the same.

Then I tried one of the 'lucky dip' sensors, swapped it straight in and the whole thing works perfectly - point a TV remote and the LED lights, hold my hand ~10cm in front of it and the LED lights!

So, where have I gone wrong?


texts: ESP32 in Arduino-IDE with FS.h and SPIFFS

texts:
I'm working on a webserver on ESP32 in Arduino IDE and would like to load an html-file. Tried to use SPIFFS.open from the library FS.h from github.
Errormessage says SPIFFS was not declared in this scope. (As far as I can see, there's no bracket in the wrong place.)

I did not find any example for ESP32 and FS.h and desperately hope for some help. Thanks in advance.

Here is my code:

    #include "FS.h"
    #include "WiFi.h"

/Wifi Access data/
const char* ssid_ap = "AccessPoint";
const char* password_ap = "12345678";

const char * ssid_sta     = "";
const char * password_sta = "";

/* set global variables */
byte WiFiMode = 0;  // WIFI_STA = 1 = Workstation  WIFI_AP = 2  = Accesspoint
int request_counter;
String sHTML;
String sHTMLRequest;

/* Create instance of server on Port 80 */
WiFiServer server(80);
WiFiClient client;

/*
 * ******SETUP*******************************************************
 */
void setup() {

/initialize GPIO/

/*start serial communication */
  Serial.begin(115200);
  SPIFFS.format();
  Serial.println("Spiffs formatted");

/* start WiFi as workstation (STA), if not possible
   start as Acess Point
   initialize server */
  WiFi_Start_STA();
  if (WiFiMode == 0) WiFi_Start_AP();
}

/*
 * **LOOP*************************************************************
 */
void loop() {

/* Check if a client has connected */
  client = server.available();
  if (!client)
  {
    return;
  }

/*Wait for the client to send data */
  Serial.println("neuer Client verbunden");
  /*Count Aufruf der Seite: */
  request_counter ++;
  unsigned long clTimeout = millis()+250;
  while(!client.available() && (millis()clTimeout)
  {
    Serial.println("time-out bei Client-Verbindung!");
    return;
  }

/****** open html files  *******/
 SPIFFS.begin();
 File f = SPIFFS.open("/home.txt", "r");
    if (!f) {
    Serial.println("file open failed");
    }
    f.close();

}

/**********************************************************************
 *
 **************** FUNCTIONS ********************************************
 *

*/

/*
 * Fct tries to start WiFi in workstation mode,
 * if not possible sets WiFiMode=AP
 * starts server
 */
void WiFi_Start_STA() {
  unsigned long timeout;

WiFi.mode(WIFI_STA);   //  Try to start WiFi as Workstation

WiFi.begin(ssid_sta, password_sta);
  timeout = millis() + 12000L;
  while (WiFi.status() != WL_CONNECTED && millis() < timeout) {
  delay(10);
  }

if (WiFi.status() == WL_CONNECTED) {
    server.begin();
    WiFiMode = WIFI_STA;

Serial.print("Verbunden mit IP - Addresse: ");
    for (int i = 0; i < 3; i++) {
      Serial.print( WiFi.localIP()[i]);
      Serial.print(".");
    }
    Serial.println(WiFi.localIP()[3]);

}
  else {
    WiFi.mode(WIFI_OFF);

Serial.println("WLAN-Verbindungsaufbau fehlgeschlagen");
}

}

/*
 *starts WiFi in AP-mode
 *starts server
 */
void WiFi_Start_AP() {
  WiFi.mode(WIFI_AP);   // Access Point mode
  WiFi.softAP(ssid_ap, password_ap);
  server.begin();       // start server
  IPAddress ApIP = WiFi.softAPIP();   //read IP of Access Point
  WiFiMode = WIFI_AP;

Serial.print("ESP-Netzwerk: ");
  Serial.print(ssid_ap);
  Serial.print(" aufgebaut. ");
  Serial.print( " IP-Addresse: ");
  Serial.println(ApIP);
}

    <code>


texts: Restoring all fuse bits on AtMega328P-PU

texts:
I'm worked with Low Fuse bits in AVRDUDEPROG 3.3. Fuses was non-inverted. And by mistake I enabled SUT1 and SUT0, when SUT0 was enabled. And when I programmed avr,
it shows me error that avrdude.exe: initialization failed, rc=-1. I have read I can restore it with Avr Fuse Doctor, but I can't buy or make with pcb. Can I recover avr with:

#include <avr/io.h>

int main(void) {
    DDRB = 0xFF;
    while(1) {
        PORTB ^= 0xFF;
    }
}

and load it to another avr and connect it to broken avr?

Can I make doctor on breadboard or Can I do it with usbasp/isp?

Can I load a new bootloader in it?


texts: How can I get additional Slave Select pins?

texts:
I have a project where I want to connect a number of SPI devices, and I'm running out of Slave Select pins (SPI) on the Arduino. So I thought that I could use something like an MCP23S17 to get additional pins and use those as SS pins, but most libraries require to pass the pins when initialising, and it seems that I can't pass the MCP's pins as a function/class argument (or can I?). For example:

U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /*cs*/ 12, /*dc*/ 4, /*rst*/ 6);

So my question is: How can I get more SS pins? Thank you


texts: Arduino Wifi Works one way but not the other? (ESP32) (Possible Variable Type Problem)

texts:
I am working on a code that accepts input from serial monitor and connects to Wifi, and have been getting issues.

my SSID for my wifi is "SamF" but for some reason arduino only likes it when I initialize at the top, not when I accept it from serial monitor even though they are the same..

Example The below code works:

#include <WiFi.h>

char ssid[] = "SamF"; //OR const char* = "SamF"
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);
}
void loop () {}

The Code Below Does not work..

#include <WiFi.h>
char pass[] = "secretPassword";
void setup()
{
ssidSerial = my code that receives Serial input and converts to char

for(int k=0;k<=3;k++){
ssidPlaceHolder[k]=ssidSerial[k];
}
const char* ssid = ssidPlaceHolder;
WiFi.begin(ssid, pass);
}
void loop () {}

Everything compiles fine, I debugged by using Serial.print and they are both displaying "SamF" and sizeof(ssid) for both is 4... so I am not sure why one works and the other doesn't? any ideas?

Thanks in advance for any help, and if anyone needs the code after I am done I will be more than glad to share it on git!


texts: Can a video game potentially detect arduino leonardo?

texts: If I automated an action in a video game through arduino leonardo, can it be detected? Things like autohotkey can be easily detected, however i would expect an arduino would be far more difficult. How easy/difficult would it be detect?


texts: Arduino boards are not working with powerbanks!

texts:
I have used many Arduino boards with adapters and other power supplies. While connecting with a powerbank for portable projects I have noticed that the power goes off after a couple of seconds and then turn on again after sometimes. Why this is happening with power bank?
I have used following powerbanks:

Basus
Xiaomi


texts: Trying to communicate data received with nRF24L01 module to API using ESP8266 in arduino UNO

texts:
I have been trying to push data into my API from Arduino UNO with ESP8266. The device connects to WiFi but fails in performing the data push after acquiring from remote sensor node with the nRF24L01 module attached to the Arduino. Here is the receiver node code

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Wire.h>
#include <printf.h>
#include <SoftwareSerial.h>

#define RX 10
#define TX 7 //for SoftwareSerial to communicate with the Tx and Rx of the WiFi module

RF24 radio(8,9); //CE,CSN

const byte address[6] = "00001";

String AP = "*****";
String PASS = "******";

String API = "9O1EQOC9QR5LMSS9";
String HOST = "api.thingspeak.com";
String PORT = "80";
String field1 = "field1";

int countTrueCommand;
int countTimeCommand;
boolean found = false;

int data = 0;
int value = 1;

SoftwareSerial esp8266(RX, TX);

void setup() {
  Serial.begin(9600);
  Serial.println(F("This is the central receiving node"));

  esp8266.begin(115200);
  sendCommand("AT",5,"OK");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+AP+"\",\""+PASS+"\"",20,"OK");
  countTrueCommand = 0;

//  radio.begin();
//  radio.openReadingPipe(0, address);  //setting the address at which we will receive the data
//  radio.setPALevel(RF24_PA_MAX);  //can set this as minimum or maximum depending on the distance between the transmitter and the receiver
//  radio.startListening(); //it sets the module to receiver mode
//  Serial.print("Radio set for communication");
//  radio.printDetails();
}

void loop() {
    String getData1 = "GET /update?api_key="+ API +"&"+ field1 +"="+String(data);

    Serial.println(getData1);
    switch (countTrueCommand)
    {
      case 0: {
        sendCommand("AT", 5,"OK");
        break;
      }
//      case 1: {
//        sendCommand("AT+RST", 10, "invalid");
//        break;
//      }
      case 1: {
        sendCommand("AT+CIPMUX=1",10,"OK");
        break;
      }
      case 2: {
        sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
        break;
      }
      case 3: {
        sendCommand("AT+CIPSEND=0," +String(getData1.length()+4),4,">");
        break;
      }
      case 4: {
        esp8266.println(getData1);
        delay(1500);
        countTrueCommand++;
        break;
      }
      case 5: {
        sendCommand("AT+CIPCLOSE=0",5,"OK");
        break;
      }
      case 6: {
        Serial.println(data);
        Serial.print(getData1);
        Serial.print(",");
        if (radio.available())
        {
          radio.read(&value, sizeof(value));
          data = value;
        }
        else{
          data = data;
        }
        countTrueCommand = 0;
        delay(10000);
        break;
      }
    }
  delay(2000);
}

void sendCommand(String command, int maxTime, char readReply[])
{
  Serial.print(countTrueCommand);
  Serial.print(". at command => ?");
  Serial.print(command);
  Serial.print(" ");
  //Serial.print("inside sendCommand loop");
  while(countTimeCommand < (maxTime*1))
  {
    esp8266.println(command); //at+cipsend
    if(esp8266.find(readReply)) //ok
    {
      found = true;
      break;
    }
    countTimeCommand++;
  }
  if(found == true)
  {
    Serial.println("Found!");
    countTrueCommand++;
    countTimeCommand = 0;
  }
  if(found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }
  //delay(500);
  found = false;
}

The code with the commented setup function works fine and updates the API. If I remove the comments from the setup function and try to setup the radio, further WiFi communication fails


texts: Identifying a counterfeit or authentic Arduino

texts:
I would like to know how I can identify a fake or counterfeit Arduino board.  For example this product, which is shown below.

I am concerned that it is cheap (about $12 when converted) and I was wondering if it is like a 'legal cheap version' or is it an unauthentic one?  If it is not authentic, would it be legal to purchase it?


texts: Arduino Switching Between Loops IR Remote

texts:
I've been working on an LED strip project. However, I've come to a stand still at the moment. Within the program I am wanting to assign different lighting effects to each button on my IR remote. I am wanting the program to work on the basis that each lighting effect will run, until another button is pressed, to start another effect.

Currently with my code I have made it so each effect will run, once, when the corresponding button on the IR remote is pressed.

I am fairly new to C++ / Arduino but from my understanding I need to have a variable which would hold the current value of the IR remote. I am unsure on how to actually implement this. I will post my code below and if anyone could give me tips or even amendments to my code it would be to a great help.

Thank you in advanced.

#include "IRremote.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(20, PIN, NEO_GRB + NEO_KHZ800);

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
int Remote = 0;

/*-----( Function )-----*/
void translateIR() // takes action based on IR code received

// describing Remote IR codes

{
  switch(results.value)
  {
  case 0xFFA25D: Serial.println("POWER");
  ArrowRight(strip.Color(25, 0, 0), 100); //Red
  ArrowRight(strip.Color(0, 0, 25), 100); //Blue
  break;

  case 0xFFE21D: Serial.println("FUNC/STOP");
  ArrowLeft(strip.Color(25, 0, 0), 100); // Red
  ArrowLeft(strip.Color(0, 0, 25), 100); // Blue
  break;

  default:
  Serial.println(" other button   ");

  }// End Case

  delay(0); // Do not get immediate repeat

} //END translateIR
void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  strip.begin();
  strip.show();
  Remote = 0;

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}/* --(end main loop )-- */

void ArrowRight(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 1; j++) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(50);
    }
    for (uint16_t i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(50);
  }
}

void ArrowLeft(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 1; j++) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2-1; i + 1 > 0 ; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(50);
    }
    for (uint16_t i = strip.numPixels(); i + 1 > 0 ; i--) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(50);
  }
}


texts: 5V DC Mini Water Pump with Arduino Mega 2560?

texts:
First of all, it is my first topic and i want to say hi to you all!! Secondly, i am really a terrible noob and sorry for that  :(

I need to make a smart greenhouse project with Arduino Mega 2560, and i found a video to help me with my servomotor(MG996R) which will start working when raindrops module detect rain and 12v DC Fan which will start working when LM35 sensor calculates the weather as hot. However, my third actuator, 5V DC Mini Water Pump, which needs to become turned on when soil humidity sensor measures the soil as dry, is where i am left without an opinion. All the water pumps people use is 12 V, so i dont know which specific components i should use. I researched a bit and found that people use transistors and diodes for it. Which ones should i use and how to make the connections?

I would appreciate if someone helps me what components, specifically, should i buy and how to connect them together with Arduino 2560? It would be great if you can draw it, like with fritzing or something.

Thanks if you read this far :)


texts:
Connecting my ESP8266 device to an IOT cloud service. When I push a button in the dashboard, it sends either 1 or 0. Then my ESP should turn a pin HIGH if signal received was 1 or Low if it was 0. Here is the code of the method in question:

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

  if ( (byte)payload[0] == 0) {
    digitalWrite(13, LOW);
    Serial.println("Setting PIN on to LOW");
  } else {
     digitalWrite(13, HIGH);
     Serial.println("Setting PIN off to HIGH");
  }

}

When sending a 1 signal, serial monitor displays:

  Message arrived [/v1.6/devices/esp8266/relay/lv] 1
  Setting PIN off to HIGH

When sending a 0 signal, serial monitor displays:

  Message arrived [/v1.6/devices/esp8266/relay/lv] 0
  Setting PIN off to HIGH

So it seems like it always goes into the else clause. Similarly, if casting the value as char:

if ( (char *)payload[0] == 0)

Then it will always go into the first condition payload[0] == 0 regardless of the value received.


texts:
I want to Create a battery Charger with the Arduino with real time battery status. I don't have any idea how to do that same time as the charging.

  I know to use a serial monitor to get battery status but not to charge.

I would like to know how to do that simultaneously so that I don't over charge the battery.

This is the battery for Lumia 822
Nokia BP-4W 1800mAh 3.7v 6.7Wh


texts: Best strategy to parse 5 byte arrays to find a pattern

texts:
Ok here it goes, my first ever question posted to stackexchange! Please be gentle on me!
I am using an Arduino UNO (at the moment, will move to a faster micro later - but still use an Arduino sketch) to read in data as an SPI slave to extract the display data off of a commercial product that has no other exploitable data output that I can use. I am using a very generic sketch that Nick Gammon posted for the purpose of demonstrating the capability - and I can read the SPI data coming in ok. (Thanks Nick!)
The data is being pulled from a commercial product that has a 8 character, 5X7 dot matrix LED display that was specially made for this product and after exhaustive searches and emails to Broadcom/Avago - has no datasheet, but there are slightly similar products that I was able to use to get a bit of a handle on how the part works, I just went on the assumption that even if the interfaces are not the same, they probably didn't reinvent their command structure. However; the display doesn't have a nice driver chip embedded like your typical parallel LCD display.
I had to do a bit of reverse engineering using a logic analyzer to figure out:

It is SPI data at 4MHz.
The gist of the commands coming in and in what order
Used excel to convert the pixel mapping of the display to the font actually getting displayed on the device.
That the displayed font/text for each of the 8 characters is made up of 5 bytes - where the bit positions of those bites end up lighting a tiny LED in the display so the letter 'H' looks like 0x7F, 0x08, 0x08, 0x08, 0x7F. Each byte controls a column of 7 LEDs, ignoring a row.

Right now:

I am using a modified version of Nick's slave sketch to simply extract the first 44 bytes of the command string to display something on the display
all that is important to me is the 40 bytes after the first 4
because those bytes are what get displayed. I am taking 5 elements of the 44 byte array that I know correspond to a character and spitting them out on the serial monitor such as:
0x00, 0x01, 0x5F, 0x11, 0x00 // i
0x7F, 0x08, 0x08, 0x08, 0x7F // H
etc...

And now after a lengthy introduction - my actual question:
I need to parse the patterns of each of the 5 bytes that makes up a letter and convert it to ASCII text so that the actual word is displayed on the serial monitor.
Back when I used to use another programming language / environment on PICs we had things like LOOKUP and LOOKDOWN which made comparing patterns a bit more abstracted, which is weird considering Arduinos...
I need help coming up with a function that takes the 5 bytes that I need to build each letter from and maybe compares it to an array that represents each possible letter and then maybe passes the matching result to another function to build / concatenate the displayed word out of those characters? That method sounds wildly inefficient, but it's all my little brain can come up with and I'm drawing a blank on how to even do that... I don't need a lot of error checking because thus far the data I'm getting is spot on with what I see on the actual display - we are also talking one 8 character word (max) at a time and it is fairly static, no scrolling words or a lot of chatter - just a single word or some data that changes relatively infrequently. But the displayed data can be different enough than the last to make trying to match entire words out of the question unless it's a side feature to speed things up. I think work properly it needs to work on one character out of 8 - one at a time. Another thought is maybe summing the 5 bytes to determine if we have a match or not, but I'm not sure if two different characters might end up having the same sum? Math is not my strong suit. Thanks for any and all help.


texts:
Thank you for seeing my post.

I am trying to write a code that lets "A" displayed on row 1 and row 0 alternately on the LCD. starting from (0,1) then (1,0)  then (2,1), then (3,0) etc..
when it reaches the last point is becomes "B" and bouncing back the other way until reaching the starting point when it becomes "A" again and repeat again..

I wrote this code but I got stuck at the end, I don't know how to bounce it back:

// include the library code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);   // initialize the library with the numbers of the interface pins

int x = 0;
int y = 1;

void setup()
{
    lcd.begin(16, 2);
    lcd.clear();
}

void loop()
{
    {
        {
            while (x < 15)
            {
                lcd.setCursor(x, y);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x = x + 1;
                lcd.setCursor(x, y - 1);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x + x++;
            }
        }
        {
            while (x = 15)
                lcd.setCursor(15, 0);
            lcd.print("B");
            delay(2000);
            x--;
        }
    }
}


texts: Sending Data between two boards using SoftwareSerial

texts:
I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests!

The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).

The idea, is to get Serial TX on the "MWC" FLIP 1.5 to Serial RX on the UNO.

These are my connections thus far:

MWC Pin ------->UNO Pin

Digital 3 (TX)--->Digital 6 (RX)

Digital 9 (RX)--->Digital 9 (TX)

This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)

#include "attout.h"
#include "SoftwareSerial.h"

SoftwareSerial altSerial(9,3); // RX=9 TX=3

void startaltserial(){

  altSerial.begin(9600);

}

void attout(){

pinMode(3,HIGH);
pinMode(9,HIGH);

  altSerial.print('1');

}

NOTE: I also tried altSerial.write('1'). Same result (or lack of one).

Then, the RX Code on the UNO Board:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); // RX=6 TX=9

void setup()
{
  // Open serial communications:
  Serial.begin(9600);

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

}

void loop()
{
  while (mySerial.available()>0) {
    Serial.println(mySerial.read());
  }
}

When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!

This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.

Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.

Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...


texts: Will Funduino Joystick Shield work on a Mega?

texts: I am trying to get a Funduino Joystick Shield working with an Arduino Mega and I need to use the WiFi capability. The specs I have found for the Funduino (see https://protosupplies.com/product/funduino-joystick-shield-v1-a/) use the standard UNO pins for the RF24: 9..13, The Mega uses pins in the high 40s for this interface. Is there a way to make this work?


texts: "function" was not declared in this scope (called in setup)

texts:
I have this bit of code I'm trying to execute only once. but I seem to get this error every time I try to compile: "calcOppervlakte' was not declared in this scope" when it's being called in the setup.

I've looked at code examples where calling functions like this works, and I cannot wrap my head around this problem.

google isn't really helpful either since the search for something-something not declared in this scope gets me thousands of results.

double pi = 3.14159265359;

void setup() {
  Serial.begin(9600);
  for(int r = 1; r <11; r++){
    Serial.print(calcOppervlakte(r)); <----
  }
}

void loop() {

}

double calcOpppervlakte(float radius){
  double result = pi * pow(radius, 2);
  return result;
}


texts:
I learned, that SPI-code uses interrupts. So is it true then, that I can't use SPI related code inside an ISR?

Background: I want to capture one or more revolution speeds with an MCP23S17. I rewired the interrupt lines to INT1 and INT2 accordingly to get the interrupts at the Arduino.

I thought it was good to fetch the port registers from the MCP23S17 inside the ISR, but this apparently doesn't work.

Is the only thing I can do in my ISR set a flag for another test in the main loop? And let a routine called from lood() then poll the registers from the port expander? This opposes the idea to fetch the relevant data which issued the interrupt ASAP.


texts: I am making a simple Li-Ion battery Tester. Basically its two 5R1 resistor in series and a relay (used to cut off the battery when it reaches cutoff voltage). Arduino is connected with ground to the battery and with A3 to the end of the resistors. But when I try to read the analog value, I receive something like 870, which is about 4.24V. BUT the real voltage is about 3.90V (according to my multimeter). How is that possible? Thanks for any suggestions.


texts:
I'm rewriting a personal project and it doesn't compile under UECIDE 0.9.1, but it does with Arduino IDE 1.8.5.

Target is NodeMCU 0.9 with default options.

Arduino IDE 1.8.5

Archiving built core (caching) in: /tmp/arduino_cache_347503/core/core_esp8266_esp8266_nodemcu_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_4a642491bde0820b9be0f8ad42686d29.a
Sketch uses 299199 bytes (28%) of program storage space. Maximum is 1044464 bytes.
Global variables use 37372 bytes (45%) of dynamic memory, leaving 44548 bytes for local variables. Maximum is 81920 bytes.

UECIDE 0.9.1

• Error at line 231 in file Monitor.ino:
‣ expected '{' before ';' token

• Error at line 231 in file Monitor.ino:
‣ expected ')' before ';' token

• Error at line 190 in file Monitor.ino:
‣ redefinition of 'CronEntry cronBlink'

• Error at line 231 in file Monitor.ino:
‣ 'CronEntry cronBlink' previously declared here

Project is too large to post here, so I zipped it and uploaded to Google Drive, where anyone can download it with this link

https://drive.google.com/file/d/1BGvqtPx0547fPfX1Nucwhd_a-MO__vWX/view?usp=sharing

EDIT
(After lambda comment by Majenko)

I was using a struct to hold cron entries, using lambdas:

struct CRON_ENTRY {
  boolean active;       // Task is active.
  unsigned long start;  // Start time (ms uptime).
  unsigned long repeat; // Repeat every (ms).
  fcncron fcn;          // task.
};

CRON_ENTRY cronBlink = {false, 0,   500, [](CRON_ENTRY * c)
{
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();
}

and then replace CRON_ENTRY struct with CronEntry class:

CronEntry cronBlink(false, 0,   500, []() {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();});

I really like lambas because they made code shorter.


texts: Different behavior than in simulator: 5V pin works instead of GND. Why is that?

texts:
I use this simulator to check if what I want to do works. This is how it looks like:

I've recently realised that I've connected my RGB LED to 5V pin instead of GND like on schema. It worked perfectly that way (led worked and chanaged colors). When I connected it back to GND pin, it didn't worked.

When I went back to simulator and changed things to those that worked physically (using 5V pin) it didn't worked, but GND did.

Why do you think there are some differences? Can I use 5V pin instead of GND if it works?

My Arduino: Arduino Leonardo.


texts: Dc motor backvoltage, how to place the diode correctly?

texts:
My previous questions have been anwsered, so thank you all for that!

I make a new question post because I have some other problems with my setup. I use a esp12s 8266 chip. It sends a PWM signal to a n-channel mosfet, so I can regulate the speed of the dc motor that is attached to the drain of the mosfet. The DC motor has extra power from a 9v battery and this battery negative is connected to the GND of the 8266. I can control it with bluetooth hc-05 module, it has 3 options, 40%, 0% (off) and 100% (full power).

Here's the problem:
I can control everything and it seems like it works all fine, but when the motor starts spinning I see a yellow led flashing on my 8266 chip and I can't control it anymore. I read about backvoltage from the motor. So I think maybe the backvoltage is causing the chip not to function anymore. To make it work again I need to disconnect and reconnect the chip for it to work again.

So my question is: could this be the backvoltage or something else?
And if it's the backvoltage how do I need to connect the diode (1n4001) in this circuit?

I read when a motor stops then the backvoltage happens, but in my case the led on the 8266 starts flashing when it spins. So maybe I hooked something the wrong way. here I have some pictures of the different setups I tried.

Of course I will solder everything nicely, but for now it's just to get a quick impression of the hookup.

Hopefully someone can help me out, thanks in advance!


texts: How can I automatically get the time from the computer into an alarm clock (starts at 00:00 when plugged in)?

texts:
Okay so I did this project from Fritzing first in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.

But here is what I wanted to add, as you can see when you plug the arduino in it will set the time to 00:00 and you can adjust it yourself to the time right now, let's say 12:57. Then you put in the alarm so let's say you want to sleep an hour u put the alarm on 13:57.

Is there a way to automatically get the time from the computer? So you don't have to adjust it yourself everytime and start from 00:00.

Thanks for all the help!


texts: Voltage from batteries in series operating on 3 ATTiny, 3 Buttons, and 3 Piezo buzzers

texts:
I intend to power three ATTiny45 chips (each requiring around 3.5V) in parallel with 2 pill batteries (namely Maxwell's CR2032) in series (which would come to around 6V). They will each play a sound with a piezo buzzer when a button is pressed.
Now maybe my thinking is wrong but I think dividing the power between the three chips may result in only around 2V delivered to each chip? Does the other components play a role?
So my question is this:

How much voltage is delivered across elements in parallel?
What changes should I do to the wiring to make the most of the voltage?
What kind of resources should I get to make sense of what to do? Cause I thought I was more advanced but this stomped me.

In any case I've added the schematic of what's intended.
[This schematic used to contain resistors to pull the switch but this need was removed with the help of jsotola's input_pullup comment]

simulate this circuit – Schematic created using CircuitLab


texts: Arduino Uno WebClient program not returning the exepected output

texts:
I have connected the Ethernet Shield to the Arduino Uno Board and do get the following error when I execute the WebClient program. Look like it's getting connected to the internet, because I am getting a response back. But, this is not the response I was expecting in the Serial console.

Can someone please help me?

connecting...
connected
HTTP/1.0 302 Found
Location: http://www.google.co.in/search?q=arduino&gws_rd=cr&ei=ap_2VJL0JqW_mwWc7IG4DQ
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=8d5e7471bdf891d2:FF=0:TM=1425448810:LM=1425448810:S=-gaX4w3RUPOn7YjK; expires=Fri, 03-Mar-2017 06:00:10 GMT; path=/; domain=.google.com
Set-Cookie: NID=67=WNjkn45lMWxFTVOlW_qv6YQonIaJjd3_Aakemy7ddZ7_JqmPgaZPv_aGdqE8OptRIeV2vrYlFZRo1us7JgmnSJlmO0mfGdSNxEckDkAsqXcL7r-S7jU04eiH_zl8Q39_; expires=Thu, 03-Sep-2015 06:00:10 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Date: Wed, 04 Mar 2015 06:00:10 GMT
Server: gws
Content-Length: 281
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic,p=0.08

<meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE>

302 Moved

The document has moved
here.

disconnecting.


texts: Unable to find/connect I2C devices (SHT31 & SGP30)

texts:
I have recently purchased an Arduino Nano 33 IOT together with two sensors:

Adafruit SHT31-D (https://learn.adafruit.com/adafruit-sht31-d-temperature-and-humidity-sensor-breakout)
Adafruit SGP30 (https://learn.adafruit.com/adafruit-sgp30-gas-tvoc-eco2-mox-sensor/)

However, so far I have not succeeded in reaching any of these two sensors. For example I connect the SHT31 sensor like this:

+3.3V to Vin
GND to GND
A4 to SDA
A5 to SCL

I have tried the default Adafruit  SHT31-D example without success, the program appears to hang. I have tried a standard I2C scanner but it does not find any devices with the sensor connected. When the sensor is disconnected, it does find two devices (the IMU and something else I guess).

I believe there is something funky going on with the I2C connection of the internal sensors and the external ones but I have no idea how to troubleshoot this issue. I read some stuff about TwoWire (extern TwoWire Wire1; after the #include) but I am having a hard time figuring out if this is what I need and how to implement it.

I found these topics myself:

https://forum.arduino.cc/index.php?topic=639188.0

https://forum.arduino.cc/index.php?topic=658967.0

edit: I haven't had success dealing with these issues so far and I am still looking for some help with my problems!


texts: How do I connect Arduino directly to MySQL server using the URL?

texts:
I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, https://launchpad.net/mysql-arduino, and this library allows me to connect to a server using the IP address, and it worked on localhost.

This is the code:

/* Setup for all libraries */
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>
#include <OneWire.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address
IPAddress server_addr( 177, 156, 122, 113 ); // Server addr

/* Setup for all others variables */
int DS18S20_Pin = 2; // Temperature sensor
float temperature;
float placasTensao;
float placasCorrente;
float geradorEolicoTensao;
float geradorEolicoCorrente;
float bateriaTensao;
float bateriaTemp;
float correnteSaidaControlador;
float correnteSaidaConsumo;

OneWire ds(DS18S20_Pin);  // On digital pin 2

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

/* Setup for connection and all variables of the database */
char user[] = "";
char password[] = "";
char INSERT_SQL[1000];
char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10],
     geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10],
     correnteSaidaConsumo_convt[10];

void setup(){
  Ethernet.begin(mac_addr);
  Serial.begin(9600);
  delay(1000);
}

void loop(){
  temperature = getTemp();
  convert(temperature, temperature_convt);
  snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt);
  sendData();
  delay(20000);
}

// Convert a float variable to string
void convert(float data, char *value){
  dtostrf(data, 7, 3, value);
}

// Saves all data on database
void sendData(){
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)){
    delay(500);
    Serial.println("Starting SQL!");
    Serial.println(INSERT_SQL);
    my_conn.cmd_query(INSERT_SQL);
    Serial.println("Query Success!");
    my_conn.disconnect();
    Serial.println("\n");
  } else {
    Serial.println("Connection failed!");
    Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n");
  }
}

// Returns the temperature from one DS18S20 in degree Celsius
float getTemp(){
  byte data[12];
  byte addr[8];
  if (!ds.search(addr)) {
      // No more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }
  ds.reset();
  ds.select(addr);
  ds.write(0x44,1);
  // Start conversion, with parasite power on at the end
  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad
  for (int i = 0; i < 9; i++) { // We need 9 bytes
    data[i] = ds.read();
  }
  ds.reset_search();
  byte MSB = data[1];
  byte LSB = data[0];
  float tempRead = ((MSB << 8) | LSB); // Using two's complement
  float TemperatureSum = tempRead / 16;
  return TemperatureSum;
}

Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?

All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.


texts:
I am setting up a page on NodeMCU running as a web server and I want to be able to turn on and off a light based on the url being clicked.

I want to know how I can get the status so that I can set the URL based on the pin status as well as pass  the GPIO pin status in the JSON from the NodeMCU web server.

The code is here.


texts:
I am working on an Arduino project, that would use HardwareSerial object reference stored in a class and call methods on it. However, there is problem with writing output using the reference.

Minimal use case to demonstrate behavior is in following files:

main.ino

#include <Arduino.h>
#include "testclass.h"

TestClass testClassInstance(Serial);

void setup() {

}

void loop() {
    testClassInstance.print("Hi There\r\n");
    delay(1000);
}

testclass.h

#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <Arduino.h>

class TestClass {
public:
    TestClass(HardwareSerial &serial);
    void print(const char * text);

private:
    HardwareSerial _serial;
};

#endif

testclass.cpp

#include "testclass.h"

TestClass::TestClass(HardwareSerial &serial) : _serial(serial) {
    _serial.begin(9600);
    _serial.print("Initializing\r\n");
}

void TestClass::print(const char *text) {
    _serial.print(text);
}

After reset, there are only two characters sent: "In"

In the example above, initialization is done before setup() method and Serial's state is probably reset before calling it. Having changed that to dynamic allocation in setup method did not change this behavior as well.

modification of main.ino

TestClass *testClassInstance;

void setup() {
  testClassInstance = new TestClass(Serial);
}

There might be problem with passing the reference to Serial, but in that case I would expect to not have any output at all.

Any help is greatly appreciated.


texts: How do you wire a ssr relay to a arduino nano

texts:
I am trying to wire a fss1-102z 5v ssr relay to my arduino nano but i cant get it to work here is my circuit. It stays stuck on and i cant get it to turn off.

Bluetooth control code

char val;         // variable to receive data from the serial port
int ledpin = 2;  // LED connected to pin 2 (on-board LED)

void setup()
{
  pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT

    Serial.begin(9600);       // start serial communication at 115200bps

}

void loop()

{
  if( Serial.available() )       // if data is available to read
  {
    ;
  }
  val = Serial.read();         // read it and store it in 'val'

  if( val == 'a' )               // if 'a' was received led 2 is switched off
  {
    digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2
  }

  if( val == 'A' )               // if 'A' was received led 2 on
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
  }

  if( val == 'b' )               // if 'b' was received led 3 is switched off
  {
    digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3
  }

  if( val == 'B' )               // if 'B' was received led 3 on
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
  } //else (ledpin = 3, LOW)        //set led pin 3 to low state

  if( val == 'C' )               // if 'C' was received led 2 on for 1 second
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'D' )               // if 'D' was received led 3 on for 1 second
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 3
  }

  if( val == 'E' )               // if 'E' was received led 2 on for 5 seconds
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'F' )               // if 'F' was received led 3 on for 5 seconds
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);       // turn Off pin 3
  }

  if( val == 'G' )               // if 'G' was received turn led pin 2 on for 500ms then switch off and turn on pin 3 for 500 mili seconds then off
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(500);                     // wait 500mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 2
    delay(500);                     // wait 500 mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'h' )               // if 'h' was received switch off all pins
  {
    digitalWrite(ledpin = 13, LOW);    // turn Off pin 13
    digitalWrite(ledpin = 2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, HIGH);      // turn Off pin 3
}

  if( val == 'H' )               // if 'H' was received switch pin 2 on and off 1000 times

  for(int i = 0; i < 1000; i++)
  {
    digitalWrite(ledpin = 2, HIGH);  // turn ON pin 2
   delay (1000); //wait 1000 mili seconds
    digitalWrite(ledpin = 2, LOW);  // turn Off pin 2
   delay (1000); //wait 1000 mili seconds

  }

}


texts:
I am getting the error in my title when I try to compile the following code:

#define char incomingByte; //Defines incomingByte
#define char sendBack = K;
#define char ?;
#define pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.
pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.
incomingByte  = Serial.read();
if(incomingByte = ?) {
Serial.print(sendBack);
  }
 }
}


texts: Solution needed for sending HTTPs requests from multiple Arduino units in the field

texts:
I'm using the Arduino Wifi Nina Library to connect an Arduino Uno Wifi Rev2 to wifi and then using the Arduino HTTP Client library to make HTTP post calls to the internet. It is working. However when I switch from HTTP to HTTPs (ie: switching the port to 443 from 80) the code below fails. I understand This is because I don't have a cert on the Arduino. I need to purchase/obtain a cert and download it to the Arduino.

I need to find a solution to this problem that meets the following constraints I have:

I will only be sending https requests to one URL:
https://api.mailgun.net
The amount of memory storage available on Arduinos is severely constrained
I plan to deploy this Arduino into the field. After I deploy it, I will no longer be able to physically access it to manually update any expired certificates. But the Arduino unit must be able to send HTTPs requests to https://api.mailgun.net in perpetuity.
I plan to deploy not just this Arduino unit, but a fleet of similarly functioning Arduino units with the same functionality. And I need to keep the costs of any certificate(s) to an absolute minimum.

    #include <WiFiNINA.h>
    #include <ArduinoHttpClient.h>

    #define REMOTE_SERVER_DOMAIN "api.mailgun.net"
    #define REMOTE_SERVER_PORT 443
    #define MAILGUN_USER "my-user"
    #define MAILGUN_PASSWORD "my-secret"

    bool sendEmailViaHTTPS()
    {
        WiFiClient wifiClient;
        HttpClient httpClient = HttpClient(wifiClient, REMOTE_SERVER_DOMAIN, REMOTE_SERVER_PORT);
        httpClient.beginRequest();
        httpClient.post("/v3/sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org/messages");
        httpClient.sendHeader("Content-Type", "application/x-www-form-urlencoded");
        httpClient.sendBasicAuth(MAILGUN_USER, MAILGUN_PASSWORD);
        String postData = String("from=Mailgun%20Sandbox%20%3Cpostmaster%40sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org%3E&to=Me%20%3Cmyemail%40gmail.com%3E&subject=Hello%20World1&text=Hello%20World2");
        httpClient.sendHeader("Content-Length", postData.length());
        httpClient.beginBody();
        httpClient.print(postData);
        httpClient.endRequest();
        int statusCode = httpClient.responseStatusCode();
        String response = httpClient.responseBody();
        Serial.print("Status code: ");
        Serial.println(statusCode);
        Serial.print("Response: ");
        Serial.println(response);
        return statusCode == 200;
    }

What is the best solution to enabling my Arduino to send HTTPs requests as stated above with the least cost and friction?


texts:
I would like to use Arduino to control locks around a building which is 5 storeys high and on every floor there is 2 door.

I'm concerned whether the wires is able to travel all the way from the ground floor to the 5th floor to provide enough power to the relay located at the door.

The lock will be a 12V magnetic lock and it will be unlocked thru a SSR relay which will be controlled by the arduino


texts:
I've recently been looking at Timers and I'm trying to generate a PWM frequency at 250000Hz using Timer0 on PIN 4. When I set OCR0A = 63 I get nothing from the light however when I set OCR0A = 125 it turns on ( 128000Hz - according to the formula in the datasheet unless I've been working it out wrong). What's the reason for it not working when OCR0A = 63

#include <DmxSimple.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(250000);
  pinMode(2,OUTPUT);  // SHIELD DRIVER OUTPUT ENABLE
  digitalWrite( 2 , HIGH); // SHEILD DE HIGH
  DDRG |= bit(DDG5);

  TCCR0A = 0;
  TCCR0B = 0;
  TCNT0 =  0;

  TCCR0A = bit(COM0A1)| bit(COM0B1)| bit(WGM01)| bit(WGM00);
  TCCR0B = bit(WGM02) | bit(CS00);
  OCR0A = 63 ;
  OCR0B = 31;

}

void loop() {
  // put your main code here, to run repeatedly:

(1,PORTG |= (1<<5));
(1,PORTG &= ~(1<<5));

}


texts: I've ever been so confused in my life. I'm new to Arduino and electronics but I just can't figure it out which diode is IR transmitter/receiver or even if it is IR. I know that IR is not visible to human eye but I'm really clueless and I need help distinguishing them. I think the black one is a receiver but when I connect the white/transparent one it lights up so I guess It's not IR diode, right? How do I test them to see it anyways?


texts:
I have an Arduino with Ethernet Shield. I'm trying to get data from Arduino, using AJAX call.
At the moment I have the following code on Arduino:

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

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

EthernetServer server(80);

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

  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  float temperatureIndoor;
  float temperatureOutdoor;
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: Arduino");
          client.println("Connnection: close");
          client.println();

          temperatureIndoor = 22.77;
          temperatureOutdoor = 15.55;
          client.print("{\"0\":{\"TemperaturaInterior\":\"");
          client.print(temperatureIndoor);
          client.print("\",\"TemperaturaExterior\":\"");
          client.print(temperatureOutdoor);

          client.print("\"}}");
          client.println();
          break;
        }

      }
    }
    delay(1);
    client.stop();
    Serial.println("client disconnected");
  }
}

I'm trying to get values with the following ajax call:

    $.ajax({
        url: 'http://192.168.1.177/',
        type: 'post',
            data: { tag: 'getData'},
            dataType: 'json',
                  async: false,
                  success: function (data) {

$('#TemperaturaInterior').val(data.TemperaturaInterior).show();
$('#TemperaturaExterior').val(data.TemperaturaExterior).show();

                            }
                        });

If I access directly from the browser to Arduino (192.168.1.177) I get the correct JSON reply from arduino:
{"0":{"TemperaturaInterior":"22.77","TemperaturaExterior":"15.55"}}

I'm not getting the values.
Any idea?
Thanks

NOTE:

This what I get when ask to arduino to give me the values:


texts: Program is executing but AT commands not showing in serial monitor

texts:
My purpose was to send SMS using GSM SIM800L coreboard  and Arduino UNO. Here is the code

    #include <SoftwareSerial.h>

//Create a software serial object to communicate with SIM800L
SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(115200);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("TEST"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

And here is the serial monitor output

 22:31:19.430 -> Initializing...

However, when I run the code, I get the text message to my mobile phone, but I can't see any AT commands in the serial monitor. It only outputs "Initializing..." .
All the connections and baud rates are okay, checked a thousand times. Has connected 2A, 4.4v power supply to the GSM coreboard and shorten the wires, and sho No bad soldering joints. GSM module red led flash per 3 seconds. And again, I'm getting the text message to my phone. So that means the problem is with the Arduino serial monitor or code, not in the hardware. I need to see AT commands because I need to put more commands through the serial monitor, I tried typing and click send, But it's not showing anything. Any assistance you can provide would be greatly appreciated.


texts:
I'm new to Arduino programming. I want to make my esp8266 get static IP based on gateway.
I mean if gateway is 192.168.0.1 then it should get 192.168.0.15 as static IP. And if gateway is 192.168.1.1 then it should get 192.168.1.15 as IP.


texts:
I have made a project using Arduino, 3 LDRs and a L293D motor driver shield. My project was that when I block light from the first LDR, the motor will spin. When I block light from the second LDR, the motor will spin in opposite direction, and when I will block light from the third one, it will stop. The code had no errors and I expected it to work... But no luck. When I blocked light from the first or second LDR, the motor only made a faint "zing-zing" type of sound. Why is this happening? Is this a power problem? But I have connected 2 9v batteries to the shield and the Arduino. Please help! Here is the code I used-

#include (AFMotor.h)

const int LDR1 = A0;
const int LDR2 = A1;
const int LDR3 = A2;
const int LightIntensity = 150;
int SensorReading1 = 0;
int SensorReading2 = 0;
int SensorReading3 = 0;
AF_DCMotor motor(1);

void setup(void)
{
  pinMode(LDR1, INPUT);
  pinMode(LDR2, INPUT);
  pinMode(LDR3, INPUT);
  motor.setSpeed(255);
}

void loop()
{
  SensorReading1 = analogRead(LDR1);
  SensorReading2 = analogRead(LDR2);
  SensorReading3 = analogRead(LDR3);

  if (SensorReading1 < LightIntensity)
  {
    motor.run(FORWARD);
  }

  if (SensorReading2 < LightIntensity)
  {
    motor.run(BACKWARD);
  }

   if (SensorReading3 < LightIntensity)
  {
    motor.run(RELEASE);
  }
}


texts: Arduino drawing a bitmap on nokia 5110 lcd

texts:
Hello I finally got my nokia 5110 lcd working, I have tested it by displaying bitmap images other people have made. I made my own image and then used lcd assistant to turn it into an array. First look at my code.

#include "U8glib.h"

U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6);  // CLK=8, DIN=4, CE=7, DC=5, RST=6

int x = 5;
int y = 5;

int level = 5;

const uint8_t rook_bitmap[] U8G_PROGMEM = {
0x7E, 0x82, 0x04, 0x8E, 0x7A, 0x42, 0xB4, 0x24, 0x08, 0xD8, 0x48, 0x08, 0x08, 0x0C, 0x02, 0x22,
0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1E, 0x11, 0x21, 0x22, 0x14, 0x3B,
0xD4, 0x25, 0x29, 0x68, 0xA8, 0xA8, 0x74, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};

void draw(void) {
  // graphic commands to redraw the complete screen should be placed here
  u8g.drawBitmapP( 5, 5, 3,18, rook_bitmap);

}

void setup(void) {

}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

// y++;
  // rebuild the picture after some delay
  delay(1000);
}

The part that goes wrong is at u8g.drawBitmapP(5,5,21,18, rook_bitmap);
I know it is to do with the 21 and 18 being wrong because I don't know where to get those numbers. Is it the width and height of the image when it is in paint.net or what is it?


texts: GPS: Not receiving any valid output from ATGM336H

texts:
I have an Arduino Pro Mini along with a GPS Unit - ATGM336H. Below is the sketch I'm currently using:

#include <SoftwareSerial.h>
#include "Ublox.h"
SoftwareSerial GPS(4,5);
Ublox serial_gps;

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

void loop(){
  while(GPS.available()){
  char c = GPS.read();
  if(serial_gps.encode(c)){
  Serial.println(serial_gps.longitude);
    }
  }
}

I'm able to receive NMEA stream from the GPS Unit and parse (tried TinyGPS++, TinyGPS and Ublox) the stream but the data is not valid nor does it ever change. I've read that this GPS unit can take up to 32 seconds to get a fixed position and deliver valid co-ords but I cannot receive any.

Is there anything obviously wrong with my sketch or hardware setup?

Any and all help would be greatly appreciated!