texts: Wifi strength Automation . Help. Noobie here

texts:
#include <ESP8266WiFi.h>
const char *SSID = "mr_lazy_boei";
const char *pass  = "usalusal";

WiFiClient client;

// Relay pin number
int ignition=2;
int self=0;

//   Return RSSI(Received Signal Strength Indicator) or 0 if target SSID not found
int32_t getRSSI(const char* target_ssid) {
 byte available_networks = WiFi.scanNetworks();

 for (int network = 0; network < available_networks; network++) {
   if (WiFi.SSID(network).compareTo(target_ssid) == 0) {     //stringOne.compareTo(stringTwo) < 0
     return WiFi.RSSI(network);
   }

 }
 return 0;
}

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

 Serial.println("Connecting to ");
 Serial.println(SSID);

 WiFi.begin(SSID,pass);
 while(WiFi.status() !=WL_CONNECTED)
 {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

pinMode(ignition,OUTPUT);
pinMode(self,OUTPUT);
}

void loop(){

int32_t rssi = getRSSI(SSID);

 // For debugging purpose only
 Serial.print("Signal strength: ");
 Serial.print(rssi);
 Serial.println("dBm");

 if (rssi > (-55) && rssi != 0) // if rssi is greater then -55 dbm or it's 0 dbm, then the light will turn
 {
   digitalWrite(ignition, LOW);
   Serial.println("ON");
}
else

{
 digitalWrite(ignition,HIGH);
 Serial.println("OFF");
}
if (rssi > (-55) &&rssi !=0)
{
 digitalWrite(self,LOW);
 delay(750);
 digitalWrite(self,HIGH);
 Serial.println("SELF OFF");

}

}

Above is my code written. As you can see, I have two variables: ignition and self. ignition works the way I want, but the self variable turns on and and then off. That is correct. But it again turns on because of void loop().
Let me explain further:
If wifi signal is strong the ignition should turn on and the self should turn on for less than a second and then turn off. It should not turn on again. When the signal goes weak the ignition turns off. Again, when signal gets strong the ignition turns on and I need self to turn on for not even a second and turn off.
I tried my best getting that. I tried moving it to void setup(), but that just works when I power up the device. After that it doesn't turn on or off. Please kindly help me. I know here I am having very talented brothers who would help me out on this issue.


texts: How to increase the detection distance on Arduino KY-032 obstacle Avoidance sensor?

texts:
We've got an Arduino KY-032 obstacle avoidance sensor, and have spent a decent time searching and researching to find a detailed data sheet/manual to figure out how it works; but there aren't any detailed information on the module.

One of the few instructions here says that the potentiometers on the chip are used to adjust the distance, but I've tried all different settings and the maximum I can get is 10 centimeters. I've tried different surfaces with different reflectivity levels, but it doesn't really differ much.

Any idea how to increase the distance on this? Anything to do with the enable jumper?

Update: Here's the related code to the obstacle detection:

void loop() {
  // check the network connection once every 10 seconds:
  val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
  if(full==1 && val==LOW) {
    Serial.print("Bin Full");
    delay(5000);
  } else {
    if (val == LOW) {
      // When the obstacle avoidance sensor detects a signal, LED flashes
      digitalWrite (Led, HIGH);
      delay(2000);
      if(digitalRead(buttonpin)==LOW) {
        delay(2000);
        if(digitalRead(buttonpin)==LOW) {
          full = 1;
        }
      }
      count++;
      //printCurrentNet();
      sendData();
    } else {
      digitalWrite (Led, LOW);
      if(full==1) {
          count = 0;
      }
      full = 0;
    }
  }
}


texts:
I am new to arduino.I try to read temperature using DS18B20 temperature sensor.I connected the pins as bellow.But,When I connected 1-pin to ground and 3-pin to +5V the sensor heated and all the little lights on the UNO board turned off and it stopped working.

When I connected 3-pin to ground and 1-pin to +5V the board worked normally.But,I gives -127 as the temperature when I uploaded the bellow code.

#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to the Arduino digital pin 2
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

void setup(void)
{
// Start serial communication for debugging purposes
Serial.begin(9600);
// Start up the library
sensors.begin();
}
void loop(void){
// Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
sensors.requestTemperatures();
Serial.print("Celsius temperature: ");
// Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
Serial.print(sensors.getTempCByIndex(0));
Serial.print(" - Fahrenheit temperature: ");
Serial.println(sensors.getTempFByIndex(0));
delay(1000);
}

I connected with both Normal mode and Parasite mode.But, same results..

I use this:

Help me to solve the problem.
Thank you!


texts: I am getting constant values and I need to know the amplification of the circuit. I believe that amplification = R8/R6 though I am not sure.


texts:
I hope I can get some help on how to get this to work.

I have multiple Sensors (32 of these) which values I want to read. I am using a master multiplexer HC4051 connected to 4 slave multiplexers, this is my wiring:
[here][1]

I tested it using one single multiplexer and it works as intended, but when adding the slave I cannot getting it to work, I am not sure how to code for it.

When using this code:

// 74XX4051 ADDRESS PINS :
#define  M_S0 2
#define  M_S1 3
#define  M_S2 4

#define  S_S0 7
#define  S_S1 6
#define  S_S2 5

// 74XX4051 ANALOG PIN :
#define  Z 0

void setup() {
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);

    // CONFIGURE SERIAL
    Serial.begin(57600);
}

void loop() {
    int value;

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for ( byte count = 0; count < 4 ; count++ ) {
         // SET THE ADDRESS
         digitalWrite(M_S0, bitRead(count, 0) );
         digitalWrite(M_S1, bitRead(count, 1) );
         digitalWrite(M_S2, bitRead(count, 2) );

         // LOOP THROUGH ALL THE ADDRESSES OF THE SLAVES
         for ( byte count_1 = 0; count_1 < 32 ; count_1++ ) {
             digitalWrite(S_S0, bitRead(count_1, 0) );
             digitalWrite(S_S1, bitRead(count_1, 1) );
             digitalWrite(S_S2, bitRead(count_1, 2) );

             // READ THE ANALOG VALUE
             value = (bitRead(count_1, 2), bitRead(count_1, 1), bitRead(count_1, 0));
         }

         // READ THE ANALOG FOR THE MASTER ADRESSE
         value = analogRead(Z);

         // SERIAL OUTPUT
         // print : ### value
         Serial.print(bitRead(count, 2));
         Serial.print(bitRead(count, 1));
         Serial.print(bitRead(count, 0));
         Serial.print(' ');
         Serial.println(value);

         delay(100);
     }
}

I am only getting random readings really (the reading LED for the moisture sensor does not switch on when the reading is done).

What I am doing wrong? Any help is appreciated.

UPDATE:

i updated my code as follows :

// Master moisture sensor pins
#define  M_S0 7
#define  M_S1 8
#define  M_S2 9
// Slave moisture sensor pins
#define  S_S0 4
#define  S_S1 5
#define  S_S2 6

// PIN from the transistor to power the sensors only when doing a reading
int sensorVCC = 13;

//  ANALOG PIN :
#define  Z 0

void setup() {
    Serial.begin(9600);
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(sensorVCC, OUTPUT);

    digitalWrite(sensorVCC, LOW);
}

void loop() {

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for (int i = 0; i < 32; i++) {
    digitalWrite(sensorVCC, HIGH);
    delay(100); //make sure the sensor is powere

    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int humidityRaw = analogRead(Z); // 1023 to 0 ===> 0 to 100%
    int humidityReal = map(humidityRaw, 975, 523, 0, 100);
    digitalWrite(sensorVCC, LOW);

    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.print(humidityReal);
    Serial.println(" % ");
    delay(1000);
}
}

and this is my output :

    Input 0: 100 %
    Input 1: 0 %
    Input 2: 100 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 0 %
    Input 1: 100 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 100 %
    Input 1: 0 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .

ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong ?


texts:
I'm trying to figure out a way to controll a DFplayer mini mp3 player with ADkeys.
Because I only have two or three files to play at a fixed volume I find it easier to just use the ADkeys. https://wiki.dfrobot.com/DFPlayer_Mini_SKU_DFR0299#target_4

Lets say I want to use Segment 1 - Segment 3 (MP3 file 1 - MP3 file 3). I would then connect a resistor (or none in Segment 1) in between and to three pins on the Arduino.
But how can I make the pin neutral, so that it does not trigger everything at once?
As far as I can read the pins are grounded in Arduino if not "high".


texts: Serial communication using Arduino and TeraTerm

texts:
I wrote a simple serial program using Arduino Mega 2560, it is connected to COMPORT 10. Here is the program I Wrote,

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

void loop()
{
  Serial.println("HELLO");
  delay(1000); //Send every one second
}

Now, I tried to send this message "Hello" to TeraTerm (COMPORT 1, for this I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0. Doing this I do receive message in my TeraTerm screen but the received message doesn't make sense, its receiving garbage. Its not the case of mismatch of baud rate I am using 9600 on both the side.

However I do receive message "HELLO" in the serial monitor. Is there something I am doing wrong that I am not receiving message on TeraTerm.


texts: Webserver on Arduino: How to 307 temporary redirect

texts:
I originally asked this question. Regarding a webserver Refresh issue on arduino.

I am totally new to web development and ethernet. The answer from @Majenko is correct, but I do not understand how to implement it. Should I change the homepage() function's first line to HTTP/1.1 307 temporary redirect and use META REFRESH?

Or do the homepage() first using HTTP/1.1 200 OK and then for all the following requests, use HTTP/1.1 307 temporary redirect?


texts: How to make C++ code compatible with Arduino IDE?

texts:
I wrote some code in C++ (Used libraries like fstream, vectors etc.) Now when I transferred the code to Arduino it wouldn't compile so I added the following library: https://github.com/maniacbug/StandardCplusplus I downloaded the IDE from here: https://www.arduino.cc/en/main/software

Now almost all my code works: All the libraries I've used work except for fstream which I've used to read a specific file.

Now is there a certain problem with the 'StandardCplusplus' library and how can I counter this problem.

Plus can someone give me an alternative for fstream that works with Arduino. Was reading a bmp image using C++. Now fstream works in a certain way (reads the file in a certain way). Is there some alternative to fstream.


texts: H-Bridge vs Motor shield for the arduino

texts:
Assuming we wish to control a small toy car with an arduino - meaning spinning the right and left wheels forward and backward and being able to break and control the speed, where each wheel has it's own engine (but of course two engines on the same side will run on the same speed and direction).

We saw we have two main options - Buying and wiring up a H-Bridge or buying a motor shield (which is based on one).

Are there any advantages for using a motor shield?

Thanks in advance.


texts:
I connected the output from an encoder motor to int0. this is used to increment a counter at every pulse. in the loop(), I check this counter and stops the motor if it is above certain value. But this "if statement" works erratically. The while loop should break at 380, but sometimes it breaks at 256.

Serial.print(cnt);
cnt=0;
Serial.print("  ");
Serial.print(cnt);
motor1_up(255);
motor2_up(255);
while(1)
{
    if(cnt>380)
    {
        Serial.print(" break ");
        Serial.print(cnt);
        break;
    }
}
motor1_down(255);
motor2_down(255);
Serial.print("  ");
delay(40);
Serial.println(cnt);
motor1_down(0);
motor2_down(0);
delay(2000);

Here is the serial output

 1  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389
 396  0 break 381  389
 396  0 break 256  264
 270  0 break 381  389
 397  0 break 381  390
 396  0 break 381  389
 397  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389


texts: Velleman KA02 not working on Mega 2560 r3

texts:
I have a Velleman KA02 audio shield. When I use this shield on an Arduino UNO R3 with this sample code, it works. And by "work" I mean when I interact with the Serial Monitor (by pressing Y, for example), I hear the playback.

However, if I place this audio shield on a Mega 2560 R3, the shield no longer works (pressing Y does nothing). I read about the SPI library, and the document seems to suggest that MISO, MOSI, SCK and SS are different for the Uno vs the Mega. For the Uno,

MOSI: 11
MISO: 12
SCK: 13
SS: 10

and the article is consistent with the constants defined in the ISD1700.h file. For the Mega,

MOSI: 51
MISO: 50
SCK: 52
SS: 53

I can modify ISD1700.h for use with the Mega easy enough. However, I do not think I can just sit the audio shield right on top of the Mega with the modified code and have it work. I used some (male to female) jumper wires to connect from the Mega pins 50, 51, 52, 53 to the audio shield pins 12, 11, 13, 53 (correspondingly). Additionally, I have jumper wires connecting the power and ground from the Mega to the audio shield. What works is that the audio shield has power and I am able to press the physical buttons on the audio shield to record and playback. What does not work is that when I enter Y in the serial monitor to force a playback, although the character is read and the switch case is reached, the playback never happens.

Any ideas on what I am doing wrong? On the Velleman site, they seem to suggest that this audio shield only works with the Uno, but the Illustrated Assembly Manual says that the audio shield should work with the Mega.


texts: Min/Max current for supply input of mega2560

texts: What is the min and max current the mega2560 can take for the 5v supply input voltage of the chip itself, not just the arduino mega?


texts:
What is the "proper" way to handle an error during setup on an Arduino -- for example some attached component is missing or returning an error code or invalid response?  The setup() function returns void so that's no help. This just doesn't seem to be an issue that is addressed in the official docs -- at least not that I have found so far.

Here are some options I have considered:

Throw an exception (but where does that go?)
Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.
Set a setup_successful flag and then do if (!setup_successful) return;  in the main loop()


texts:
I ran the following really simple code on my micro and the monitor is just blank, not displaying any zeroes or anything and the Tx light isn't lighting up. I haven't used analog inputs much so I don't know what could be causing this. Can anyone help? Thanks, here's the code

int sensePin = 0;
void setup() {
    analogReference(DEFAULT);
    Serial.begin(9600);
}

void loop() {
  Serial.println(analogRead(sensePin));
  delay(500);

}


texts: How to use ESP8266 for wireless communication?

texts: I saw many tutorial explaining how to program ESP8266 but Specifically I didn't get any tutorials explaining how to use with Arduino or any other Microcontroller for Wireless Communication. I had a doubt how could I use it with Arduino for Serial Communication such that I could use with my handset ( using Blynk ) and with my PC.


texts:
So I have a project where I need to run pthreads (coded in C) on an Arduino Uno. I've written and compiled the code and the output is what we need when I use a C compiler. But I'm having trouble running it on the board. I've installed the Pthreads library in the libraries folder of the Arduino, but it still gives me erroneous errors.

I'm jumbling back and forth without finding a solution, can anyone give me any tips?  It's become so annoying that I'm thinking of buying a Pi.

Any help is much appreciated.

Edit: let me rephrase: the professor wants us to implement pthreads on an Arduino or Pi. I didn't decide pthreads is the solution, it is the requirement.


texts:
Im now working on a Node MCU based project but the problem is that i cannot upload the code to the board. Further more whenever i connect the usb to the NodeMCU my keyboard stops working and only works again after i turn off and on my pc this happens whenever i disconnect and connect the Node MCU. The error is COM port is not found or board is not connected and sometimes after i disconnect the Node MCU my system gives a message The Last USB device malfunctioned
Can anyone help I'm using a basic NodeMCU 12E CP2021??


texts: Interfacing with desktop computer console software

texts:
Recently I bought the following USB to Serial cable: https://www.adafruit.com/products/954

This cable has grd, vcc, rx and tx lines.

I am looking to use this cable to interface with my desktop computer with a program like Tera Term or Hyperterminal so i can output messages for debugging purposes.

Also, I am trying to stay from using the Arduino IDE. I would prefer using C and flashing in the hex manually.

So, can anyone point me to a tutorial or explain how to make this happen?

thanks people.


texts: RFID RC522 Serial Communication converting problem

texts:
I am new to the RFID Scene and Serial communication as well.

So I am trying to use the RC522 RFID module and I wrote in block 22 - 0x36 which is 6. I want to write a code where I take whatever is in block 22 - 0x36, convert it into a float - 6.00 and then do some addition or deduction for example 6.00-2.5 = 3.5 and then I want to rewrite the value of 3.5 into that same sector but of course, convert it back to HEX ASCII - 33 2e 35. I've tried quite hard to find the solution online but couldn't.
  So is this possible to do?

Thanks.


texts: How to flash pre-compiled bin files into NodeMCU using Ardunio IDE

texts:
How to flash pre-compiled binary into NodeMCU using Ardunio IDE. Since every time it require to compile and flash it. Is there way to flash binary alone to nodeMCU via Arduino IDE ?

One can export binary file from IDE -> Sketch -> Export Compiled Binary. Binary will be copied into working directory. U can check the path Sketchbook location in File -> Preferences. But how to flash binary alone to nodeMCU.

I have fashed using esptool.py from linux. But is there a way to flash from IDE for handy ?


texts: ArduCAM OV2640 and microSD card module -- SPI problems

texts:
So what I'm trying to do is use the ArduCAM OV2640 (2MP Mini) to take a timelapse. Of course the first thing I have to do it to get it to take a picture and write it to an SD card. The thing is, the camera works fine by itself, however when I hook up the SD card something happens where the SPI no longer works (I have a general understanding of how SPI works -- not a highly technical understanding though).

So my main question is if it's possible for a device using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller?

And if so, is there any software or way to visualize this? Like something that monitors the SPI bus?

And as for how to actually fix the problem, would it be practical to use a shield with a built in SD card module? Or use a logic gate to determine which device to allow access?

I really don't have the greatest understanding of this, so any help would be appreciated.

EDIT:

I'm using this camera module with this sd card module. As for my wireup, the camera follows as below:

The common pins between the SD card module and camera are VCC,GND,MISO (pin 12) , MOSI (pin 11), and SCK (pin 13). I have an individual CS pin for each.


texts: Arduino with NFC: Garbled Serial Monitor

texts:
I started working on a small programming project just for fun and I have got stuck. I have been using the following tutorial to make an Amiibo Music Box

Now using the libraries the tutorial suggested, I successfully uploaded the sketch to the device. However when I put an Amiibo or NFC card on top and look at the Serial Monitor, I get lots of garble and no sound.

¸ý×ÿòœy_ÿ#À–Yÿ›l°   _Yÿ8dÐa4’ÿ’Í�©ÿ›—Lµ›ú’áo°)h@’öþ8‚¤hþ:dÐ S4ê’ÉãÈô›l°É�°ò“ƒc¶ÿ™l±a“ùü8‚´hþ›l°É�´÷“ÅiØð
¶–t=Üý’ÉãÈôâd@àÉ‘ø8‚¤hþ
–e¼Õý’ÍÐPÿK¬ÀàÉ�ú8�·i™–e¼Õý8©Pòý’t=Üý“ƒf–ÿü’t=Ø9UY6þ›hX Cú’Í�©ÿ(l„±Ô_ü8‚´hþKìAÀò ý:‚´hþ8lÐaÓ4â’ÌcÈõ›hX Cú“ƒf–ÿKìEÀò ý’ÌiØõ8lÐaâtý“ƒ&–ÿè4@’âþ“ƒ&–ÿš’L²µšý8�·yÿ)l„úÈï’ÉãÈõ(l„±Ô_ü’ÍÙ:dÐ`S4ê2"´žþ)l„úÈï2"ßŸÿ›h±ÑªÛÖ’áoÞÿüÒt=Ø‘�&’ÿ�šA’âþ“ƒc¶þ›l±ÑªËÓ’Í�©ÿ8lÐaâtý’ÍÙ
––\5,ÿ’Í�©ÿè4@àâþ8©Pòý–t=Üý:‚´hþ
––t=Üý8‚´hþ8l€a¢tý’ÉãÈõš’L²µšýÜ,þÍ›þëÖÿÜ,þÜ,ÿÜ,ÿYÿ\ÿëòÿÜ,þêëòÿëòÿê4KÖÿ\ÿ]ÓÜ,ÿ\

I tried the card that comes with the kit and it does not work either. Has anyone got any idea why this has failed? I have put a link to the libraries and code I am using below.

https://github.com/ModusPwnin/Interactive-Amiibo-Stand
https://github.com/ModusPwnin/Interactive-Amiibo-Stand/blob/master/Amiibo%20Stand%20v3
https://github.com/adafruit/Adafruit_NFCShield_I2C
https://code.google.com/p/wavehc/

I am new to this but I want to understand why this is not working as well. Can anyone help me?


texts: Arduino won't send serial data if connected with external power supply

texts:
I am trying to make a connection between 2 Arduino's with the APC220 rf modules.

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

void loop() {
   int value = 5;
   Serial.println(value);
   delay(1000);
}

I uploaded this code to my Arduino Nano and Uno. I disconnected the rf modules for uploading the code.

I tried to run this program with an external power source (lipo 11.1V 2200mAh).
The Arduino is powered on(power led is on) BUT the tx led doesn't blink.

The only way to make it work is by using the usb and opening the serial monitor on my pc.

I tried to use a 10k resistor between tx and rx (or rx to ground) but the code won't run...

Can someone help me?

Solution : the arduino worked perfect. When you connect the arduino with an exernal power supply the tx and rx lights won't light up, Even when they are transmitting or receiving.


texts: ESP8266 crashes when trying to copy a string into a big char

texts:
I'm trying to parse with tinyxml2 a modest XML (3.4kb) to retrieve some data.

My ESP8266 crashes every time I try to use the toCharArray method.

here's my code

// here I'm getting an http request
String payload = https.getString();

// checking the payload, it seems fine in console but I get some garbage characters when àèéùìò are printed
Serial.println(payload);

// Length (with one extra character for the null terminator)
int str_len = payload.length() + 1;

// Prepare the character array
char xml[str_len];

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here

the length of the string is something around 3900, which I'm not sure can fit this kind of array on this device. If it's the case, what will be a better strategy ?

As you can imagine I'm just starting with the c language :)

EDIT: https.getString().c_str() + less variables was the right way to save memory


texts: I have read many tutorials on LDR(Light dependent resistor) with Arduino which includes a 10 kilo ohm resistor but can i use it with 220 ohm resistor or even without resistor.


texts: Turning a motor on and a led at the same time for a given time period

texts:
I need help with this code, I want to have a motor turn on for a given time and at the same time have an led light up to indicate it is on which will also turn of once the motor has stopped. It is controlled by A TECT5000 SENSOR, which acts like a switch to transfer a signal to the motor and LED.

At the moment, I can get the motor to turn on and off for a given time but not the LED. Every time I activate the circuit with the sensor it turns on and stays on or turns of and stays of. Here is the current code I am using.

// Program: Led drive using reflective optical sensor
// Author: Arduino e Cia

int outgoingsignal = 8 ; // Pin of led
int pinsensor = 7 ;   // Connected to the "collector" pin of the optical sensor
int reading;      // Stores information about sensor reading
int statusled = 0 ;
int motorPin = 9;  // define the pin the motor is connected to
                   // (if you use pin 9,10,11 or 3you can also control speed)
                   // Stores led status (on / off)

void setup ()
{
  pinMode (outgoingsignal, OUTPUT); // Defines the led pin as
  pinMode (pinsensor, INPUT);   // Defines the sensor pin as input
   pinMode(motorPin, OUTPUT);
}

void loop ()
{
  // Le the sensor pin information
  reading = digitalRead (pinsensor);
  if (reading != 1 ) // Checks if the object was detected
  {
    while (digitalRead (pinsensor)!= 1)
    {
     delay (100);
    }

    statusled =! statusled;
    // Reverses the status of the led (on / off)

    // Turns on or off the led as "statusled"
    digitalWrite (outgoingsignal, statusled);
  motorOnThenOffWithSpeed(); }

}
void motorOnThenOffWithSpeed(){

  int onSpeed = 255;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 0;  // a number between 0 (stopped) and 255 (full speed)
  //int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
 // delay(offTime);                   // waits for offTime milliseconds
}


texts:
I am working on home automation project. A network consists of one master device and many (maybe 10-20) slave devices, all communicating via these RF modules. I am using arduino in slave devices. Master will be based on raspberry Pi (most probably). Slave nodes can be sensors or switches(to control household electronics). To and fro communication will include data such as : a) Turn off bulb 1, b) Turn on TV, c) Set the bulb brightness to 34%, d) Temperature reading is 23 degree Celsius etc.

From security point of view, imagine there are similar other networks in the range and one network must not interfere with another. As such, I need to implement some sort of authentication whenever each data transfer takes place between master <---> slave. What logic do you suggest for this process?

There can be cases when data has not been received successfully by the receiving end. In such cases, I am planning to use some sort of checksum and acknowledgement system. If acknowledgement is not received, data will be resend in time intervals of 1s, 5s, 10s, 30s, 30s. If these 5 resends fail, the slave/master will be considered as unavailable/powered down. Your opinions/suggestions on this?

Slave arduino will be busy controlling appliances/sensors connected to it (real busy when controlling appliances). As such, it won't have much time for communication. Less time required for communication == Awesome. How much time do you think the arduino will take to complete one such data transfer?

Another solution I could think of was using two arduinos connected via i2c in each slave module. One arduino will be busy controlling the lights/sensors. Other one will take care of RF communication. If it receives some valuable info which was meant for this particular module, it will transfer the same to the other one using i2c bus. Is this a feasible backup plan?

Am I doing wrong by selecting RF modules for this purpose? Should I switch to Zigbees?

Thanks guys for reading. Any constructive suggestions from your side will be very helpful.


texts:
I am sending a list of servo positions via the serial connection to the arduino in the following format

1:90&2:80&3:180

Which would be parsed as:

servoId : Position & servoId : Position & servoId : Position

How would I split these values up, and convert them to an integer?


texts: Arduino UNO reprogram the MEGA8u2 using external programmer

texts:
As they say in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 you need to solder a 10k resistor in order to reprogram/reset the MEGA8u2 chip on Arduino UNO but sometimes you may lack the needed tools.

Is there a way to reprogram the MEGA8u2 using an external programmer or an another arduino as a programmer?

My idea behind this is to use the ISP LAYOUT for ATMEGA8U2 in order to load the correct bootloader:


texts: Can I call functions from a different sketch?

texts:
I am a beginner at programming with Arduino and I am unsure on how can I call functions (such as, getData()) for the touchscreen LCD to display that data. The purpose of my device would be to listen to data communications between sensors and a controller and thus I have one RedBoard with CAN-BUS shield with a dataComms.ino sketch, which initialises getting data functions from received data packets and parses them.

Do I need to create another sketch for the display? If so, how can I call functions from another sketch, so that display.ino would have access to received values? Or are there some better ways of displaying data?


texts:
I have bought an arduino uno but when i plugged in the arduino to my laptop its not turned on (the built-in LED was off) and at the arduino IDE I wasnt able to change the port (the port button was unavalible)
what should I do for the arduino uno board to work?


texts: Multiple variant.cpp entries for same physical pin

texts:
Some variant.cpp files have more than one entry that points to the same physical pin. For example (from Arduino Zero's file):

// 14..19 - Analog pins
// --------------------
{ PORTA,  2, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // ADC/AIN[0]

...

// 43..45 - Alternate use of A0 (DAC output), 44 SWCLK, 45, SWDIO
{ PORTA,  2, PIO_ANALOG, PIN_ATTR_ANALOG, DAC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // DAC/VOUT

The first entry sets up the pin as a regular analog input pin on A0. The second entry sets it up as a DAC on pin IDE pin 43.

The corresponding variant.h file defines the DAC pin and A0 as entry 14, rather than 43. I also have seen plenty of examples online that use the DAC via A0 when working with an Arduino Zero.

/*
 * Analog pins
 */
#define PIN_A0               (14ul)
#define PIN_A1               (15ul)
#define PIN_A2               (16ul)
#define PIN_A3               (17ul)
#define PIN_A4               (18ul)
#define PIN_A5               (19ul)
#define PIN_DAC0             (14ul)

Finally, I see other variants, like this one that don't even bother to create a DAC-specific entry. So presumably it doesn't actually matter? If not, then why is it in the Arduino Zero variant.cpp file at all?

A related question: How does using a pin for multiple purposes work? For instance, if I had a pin I've configured for SPI MOSI (in variant.cpp), and I wanted to also use it for PWM (given the datasheet says the pin is on a SERCOM and a timer), do I actually need two entries in variant.cpp and thus two different IDE pins to use in my sketches (one that has a pin type of PIO_SERCOM and another with PIO_PWM)? I can think of plenty of times working with an Arduino UNO, for instance, where I've just used the same IDE pin number for general IO as well as SPI (MOSI).


texts: How to connect Flora 2 and nRF8001 BLE Breakout

texts:
I'm trying to get the nRF8001 BLE Breakout polling properly on Flora but Adafruit's tutorial and everything I've read and hunted around but I'm new to Arduino and not really sure how the Adafruit_BLE_UART library is handling I/O on the various pins. I'd appreciate it if anyone knows the proper pin configuration to get this working. I'm not in a position where I can easily change out to a better BLE device for my Flora.

So it's clear I have

SCK connected to SCK.
MISO to MISO, I've also tried it in D12 with the same outcome.
MOSI in MOSI, there's no D11 on this board so I couldn't try that.
REQ in D10.
RDY in SDA, which is supposed to correspond to D2 (besides SCL I don't think there are any other interrupt pins).
RST in D9, also tried it in the Reset SPI, doesn't seem to make any difference.

In short I'm using all the appropriate SPI pins and two of the data pins mentioned in the BLE tutorial, and I've tried a couple other configurations without much success.

And it appears to be powered properly.

using echoDemo, getState always returns the disconnected opcode. Polling apparently does nothing, setDeviceName does not set a name. I think either MISO or MOSI or both are the problem here. I can blink the LED, and other peripherals are working okay. (Crossposted to Adafruit forums.)

Some code:

#include <SPI.h>
#include "Adafruit_BLE_UART.h"

// Connect CLK/MISO/MOSI to hardware SPI
// e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

void setup(void) {
  Serial.begin(9600);
  while(!Serial); // Leonardo/Micro should wait for serial init
  Serial.println(F("Adafruit Bluefruit Low Energy nRF8001 Print echo demo"));
  BTLEserial.setDeviceName("NEWNAME"); /* 7 characters max! */
  BTLEserial.begin();
}
aci_evt_opcode_t laststatus = {5};

void loop() {
  // Tell the nRF8001 to do whatever it should be working on.
  BTLEserial.pollACI();
  // Ask what is our current status
  aci_evt_opcode_t status = BTLEserial.getState();
  Serial.println(laststatus);
  Serial.println(status);
  Serial.println(ACI_EVT_DEVICE_STARTED);
  Serial.println(ACI_EVT_CONNECTED);
  Serial.println(ACI_EVT_DISCONNECTED);
  delay(1000);
  // If the status changed....
  if (status != laststatus) {
    // print it out!
    if (status == ACI_EVT_DEVICE_STARTED) {
        Serial.println(F("* Advertising started"));
    }
    if (status == ACI_EVT_CONNECTED) {
        Serial.println(F("* Connected!"));
    }
    if (status == ACI_EVT_DISCONNECTED) {
        Serial.println(F("* Disconnected or advertising timed out"));
    }
    // OK set the last status change to this one
    laststatus = status;
  }
}


texts: All four of my ESC motors stutters when I run it on my Arduino, how can this be fixed?

texts:
I am creating a drone and when I run it with my arduino all 4 motors stutters.

This is the ESC and the motor i bought:

hobbyking.com/en_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I put the 3 motor wires in the esc directly. (This is already presoldered by the company i bought it from). Then I have soldered bullets myself on the end of 2 connections of the ESC and then I enter them to my power distribution board:
hobbyking.com/en_us/hobby-king-quadcopter-power-distribution-board.html)!

After this I put jumper cables on the ESC cables (ground + signal, not the powercable). The signal I just use a regular jumper cable on each ESC and put it to the arduino board and when I use ground I use a jumper cable on the all the ground ESC wires and then I solder them together with another jumper cable and put that on the GND on the arduino uno.

Have I done a bad soldering job and is that the reason why the motors are stuttering? And if so is it the GND pins soldering or is the bullets I solder to the ESC and connect to the power distribution board? Or is it maybe something else? The three motor wires are all black meaning i have just randomly put them on the ESC. If I swap them around a bit might that solve it?

This is how the soldering looks:

This is how I solder different jumper cables together to one jumper cable and put it on the GND on the arduino uno. (I added a shrinking tube after that).

This is another one I did with the GND to see if the first one above was a bad soldering job:

Appreciate every help and tips :)


texts: Can I daisychain multiple Arduino Nanos to a single USB port (specialized purpose)

texts: I need to have several Nanos on one USB port. They will have separate power, so power constraints won't be a concern. I need them all to go through the same serial port. They will never get anything sent to them, and should never send data simultaneously. Each one is connected to a switch, and upon pressing the switch, will send an 8-digit serial number over serial. I want to have a VB.NET application which listens over this shared serial COM for numbers, and collects them all, displaying them in a history list. Can this work?


texts: How can I convert Arduino String to C string type?

texts:
I got a String which as I understand is an Arduino object, and got some C++ code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <string.h>

LiquidCrystal_I2C lcd(0x20,16,2);

boolean borrar = false;
String IP;

void setup()
{
  lcd.init();
  lcd.backlight();
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop() {

  while (Serial1.available()) {

    char caracter = Serial1.read(); //Comprobamos el caracter

    switch(caracter) {

    default:
                if (borrar) {
                              IP = "";
                              lcd.clear();
                }

                lcd.print(caracter);
                delay(125);
                borrar = false;

                IP.concat(caracter);
                break;

    case '\r':
    case 0x0F:
    case 0x0A:

                String res = "";
                borrar = true;
                int num= atoi(IP.c_str());
                if (num < 127)
                  res="Clase A";
                if (num == 127)
                  res="Direccion reservada";
                if (num > 127 && num < 192)
                  res="Clase B ";
                if (num >= 192 && num < 224)
                  res="Clase C ";
                if (num >= 224 && num < 240)
                  res="Clase D ";
                if (num >= 240 && num < 255)
                  res="Clase E ";
                break;

  } //fin switch

}//serial disponible

}//fin programa

However, this won't compile because of this line:

int num= atoi(IP.c_str())

As IP is a String and such method works for string. How can I make it compatible (convert it)?


texts: How can I use arduino board for AC mains?

texts:
I want to use LDR to control a light bulb (12W) which runs on AC supply using Arduino.

Is it possible to do this?

If yes, how?


texts:
I read a comment form here:

"Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using Serial.readBytesUntil(), Serial.readBytes(), Serial.parseInt() or Serial.parseFloat(). It defaults to 1000 milliseconds."

According to the latest webpage,

"Serial functions that use the timeout value set via Serial.setTimeout():

Serial.find()

Serial.findUntil()

Serial.parseInt()

Serial.parseFloat()

Serial.readBytes()

Serial.readBytesUntil()

Serial.readString()

Serial.readStringUntil()

"

So apparently, there's no direct indication to set a timeout option for Serial.read().

How to set a time out like Serial.setTimeout() for Serial.read()?


texts: Weird formatting behavior with sprintf function

texts:
I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.

But that line:

sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));

returns something like this:

3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)

It's suppose to return something like this:

3000;110;291;263;230;0;0;245

Here is my sketch:

int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;

volatile boolean interruptFlag = 0;
char read[45];
char signal[2048];
volatile int count = 0;
volatile long x = 0;

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

  noInterrupts(); // Stop interrupts.

  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.

  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)

  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);

  interrupts(); // Allow interrupts.
}

ISR(TIMER1_COMPA_vect){
  if (!interruptFlag){
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag){
    writeAnalogSignals();
    count++;
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  if (strlen(read) == 0) {
    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  } else {
    sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  }
  strcat(signal, read);

  x += 2;

  if (count >= 50) {
    Serial.print(signal);
    signal[0] = 0;
    count = 0;
  }
}


texts:
I've made a clock using an Arduino, but the time seems to drift.  I am aware of the rollover issue; the clock seems to drift by about 15 minutes over the course of a week.

I'm using a custom PCB with this resonator from Digi-key.  The code reads the millis() function at the beginning of each loop, and works from that value.

My question is:  How can I measure time with an Arduino, accurately enough to make a passable desk clock?


texts:
This is my first manually typed code. I'm sure there may be some glaring "schoolboy errors" in it, so wondered if people could give it the 'once over' In particular, I have never used C++ arrays, storing binary data within, and then trying to read them bit by bit. In perl, much easier; you would simply use a multi-dimensional something like this:

@code1=('10101010', '01010101');
$bit=$code1[0][0] (..through to..) code1[0][7]
$bit=$code1[1][0] ... code1[1][7]

So this is my Arduino code. Welcome to suggestions.

int pinArray[]={2,3,4,5,6,7,8,9};
int code1[]={B10101010, B01010101,B10101010, B01010101,B10101010, B01010101};
int count=0;
int split=0;    // Counter for the bit loop
int led;    // Store bit data
byte x;     // Used to store the binary data in code1

void setup(){
    for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT); // Sets pinMode as output on pinArray pins
    ]
}

void loop(){
    for (count=0; count<6; count++){
    x=code1[count];
    ledDisplay(x);
    }
}

void ledDisplay(){
    for (split=7; split>=0; split--){
    led=bitRead(x,split);
        if (led == 1){
        digitalWrite(split+2,HIGH);
        }
        else{
        digitalWrite(split+2,LOW);
        }
    }
}

Have just modified split as realised bit7 is the leftmost digit. In split, I am adding 2 to the value.  Does this need to be enclosed in brackets,ie (split+2) ?


texts: Why is Serial.print working when nobody receives the data?

texts:
I have a kind of theoretical question. Let's have an Arduino Uno connected through USB that does a lot of Serial.print-ing. Then I disconnect it and I don't see anything on the Serial monitor, but the Arduino is still working. I can judge by the blinking lamps and so on.

Now I see that all printing goes through HardwareSerial::write from the Arduino core. There is this statement:

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  // ???: return 0 here instead?
  while (i == _tx_buffer->tail)
    ;

It means that if the output buffer is full, the Serial.print will hang there eternally. However this doesn't happen. I guess somebody is consuming the data and to be more precise in ISR(USART_UDRE_vect). It seems as the only place where within interrupt _tx_buffer->tail can be changed. Otherwise the code would loop endlessly in HardwareSerial::write. This interrupt USART_UDRE_vect should be raised only when the Data Register is empty.

My question is - who is consuming the sent data? Is that done by some USART_to_USB drivers? Or am I missing some part of the picture?

Regards,
Boyan


texts: Is volatile needed when variable is accessed from > 1 ISRs, but not shared outside ISRs?

texts:
It's clearly documented that when global data is shared with an ISR and the main program, the data needs to be declared volatile in order to guarantee memory visibility (and that only suffices for 1-byte data; anything bigger needs special arrangements to guarantee also atomicity). Here we have good rules:

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

But is volatile needed when the variable is accessed from > 1 ISRs, but not shared outside ISRs? For example, I have a function that maintains internal state using a static variable:

void func() {
    static volatile long counter; // volatile or not?
    // Do stuff with counter etc.
}

That function is called in two ways: from pin interrupt, and from TimerOne library:

attachInterrupt(0, func, CHANGE);
Timer1.attachInterrupt(func);

There are no atomicity problems, since when an ISR is entered, interrupts are automatically disabled, but this volatile is more of a compiler question: what is cached and what is not.

Better safe than sorry, of course...


texts:
My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.

I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)

Can someone shed some light as to how I do this?

The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.

Here is what I have.

Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.

// Setting The Pin Numbers
const int touchsensor = 2;                      // the number of the touchsensor pin
const int buzzer =  4;                          // the number of the LED pin

// variables:
int touchsensorState = 0;                       // variable for reading the
touchsensor status
unsigned long timestamp = 0;
unsigned long timeout = 1000;

void setup() {

  pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
  pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
 }
void loop() {

   touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

   if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
     digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
     timestamp = millis();                       // Timing button press
   }

   if(millis() - timestamp > timeout) {
   digitalWrite(buzzer, LOW);                  // buzzer will not sound:
   }
}


texts:
I have the following code:

      uint8_t buf[1];
      uint8_t buflen = 1;
      if (driver.recv(buf, &buflen)) // Non-blocking
         {
            int i;
            // Message with a good checksum received, dump it.
            Serial.print("Message: ");
            Serial.println((char*)buf);//this prints out okay
            highPins[(char*)buf] = 1;
         }

The problem is in highPins[(char*)buf]. highPins is array, and in (char*)buf I get index number. When I display it with Serial.println, it shows the number, but here it does not. I am guessing its because (char*)buf is not a number. I have tried to convert it to int with few functions I have found online, but it was unsuccessful. Any help is appreciated :)


texts: How to get data from a sensor's FIRST IN FIRST OUT FIFO register (from two's complement)

texts:
I want to get acceleration data from a ADXL355 sensor.

My code:

void readFIFO (){
long data[3];
byte data2 [9];

digitalWrite(chipSelectPin, LOW);
SPI.transfer( (FIFO<<1) | 1);
for (int i = 0 ; i < 9; i++){
    data2[i] = SPI.transfer(0x00);
}
digitalWrite(chipSelectPin, HIGH);

Serial.println("Byte data in hex and binary");
 for (int j = 0 ; j < 9 ; j++){
    Serial.print("element "+String(j) +": ");
     Serial.print(data2[j],HEX);
     Serial.print(" ");
     Serial.println(data2[j],BIN);
 }
 for (int z = 0 ; z < 3; z++){
    data[z] = ((data2[z*3]<<12) | (data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
 }
 Serial.println("concatenated values: ");
 for (int i = 0 ; i < 3 ; i++){
    Serial.println(data[i]);
 }
}

Sample output:

Byte data in hex and binary
element 0: F9 11111001
element 1: 1B 11011
element 2: 51 1010001
element 3: 0 0
element 4: FD 11111101
element 5: 90 10010000
element 6: C3 11000011
element 7: 2A 101010
element 8: 20 100000
concatenated values:
-28235
4057
12962

The values are two's complement. Are these the correct values? If not what am I doing wrong?


texts: What could make an LCD stop working permanently after being connected for 5 seconds to Arduino?

texts:
I was using a 20x4 LCD connected to Arduino Uno via a common I2C adapter board. Everything was working perfectly, including the LCD. I had it running like this for a couple of days without any problems.

My next step was to connect the LCD to a Nano instead in order to make the package smaller. The exact same code from the Uno was uploaded to the Nano, and I connected the wires in the exact same way. The major difference here was that I soldered the wires onto the Nano, because I didn't want to use headers. I did a continuity test for shorts and the connections seemed to be fine. There are only 4 wires between the Arduino and LCD adapter board: 5v, ground, SDA and SCL.

The Nano powers up fine, and the LCD powers up fine, but immediately the LCD shows the following:

That had never happened when I had the LCD connected to the UNO.

After that, the LCD stops working completely, even when I move it back to the UNO. It just constantly displays those 2 lines. (Adjusting the contrast makes the boxes appear or disappear).

After the first LCD seemed permanently broken like that, I tested it on a 2nd brand-new LCD. First I connected it to the same Uno with the same code, and everything was working perfectly. I re-uploaded that same code again to the Nano, just to make sure everything was in sync. Then upon connecting the 2nd LCD to the Nano, immediately it displayed those 2 lines. I disconnected it right away (within 5 seconds), and tried to put it back on the Uno, but still the display is corrupted. I've tried other sketches, but both of these displays seem to be broken and never display anything except for those 2 lines.

Even if I just connect 5v and ground to the LCD, no matter from what source, it just constantly displays those 2 lines.

Any ideas as to what could "break" an LCD so quickly like that, and if it's possible fix it?

Edit:
As per Gerben's suggestion, I removed the I2C backpack and hooked the LCD up directly. This was the 2nd one I had broken, the one where I'm more certain of its entire (short) history. I ended up with the exact same result. Adjusting the pot only makes the boxes appear or disappear. I tried skipping the Arduino completely and giving it 5v power from an adapter, and it still has the same result.


texts: Spilt string and convert to float to compare

texts:
I'm transmitting: Temperature: 28.22C

and on the receiving end I'm receiving the whole tranmission as a string. I'm trying to spilt Temperature to leave it as a string and 28.22 as a float to compare, how do I do that ?

TX end hardware: (Arduino Uno board with Xbee S1)  to computer
RX end hardware: (Arduino Uno board with Xbee S2)  to computer


texts:
There is a ANSWER to this question on this site: "Convert to and from Unix Timestamp"  The ANSWER includes a code example.  In the code example
there is an array named "days[][]".  What is this or where is this declared and populated?


texts: Adding to the counter only ONCE while R2 =<200

texts:
I am very new to Arduino and I have this little bit of code:

if (R2 <= 200){
  counter=counter+1;
  Serial.print("counter: ");
  Serial.println(counter);
}

I want it to count every time R2 is less than or equal to 200, but I only want it to count once. Right now it adds to the counter 3-2 times while R2 is less than 200. I'd like it to only count once while in that range before R2 becomes greater than 200.

Any suggestions or links to helpful information would be very appreciated. Thank you!


texts: Splitting the power source between an arduino and a servo

texts:
I have an Arduino board which is controlling a servo. I think I read that I could only supply about 100 mA through the Arduino's 5v pin. Because of that the power supply I use is able to deliver about 2A I would like to split the power before the Arduino. How do I do that?

Do I have to take some safety for the Aduino in concern or could I just split the wire?


texts:
I was trying to understand the working of micros() function internally and I had a look at the function in Arduino.h

This is the code:

unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
 #if defined(TCNT0)
    t = TCNT0;
 #elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t & 255))
        m++;
#else
        if ((TIFR & _BV(TOV0)) && (t & 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

Can someone please explain me what this line is doing :

  if ((TIFR0 & _BV(TOV0)) && (t & 255))
   m++;


texts: Arduino Uno Motor control using 2 Relays, 2 Limit switches and Bluetooth. Forward Reverse Stop

texts:
Modified existing project from this link:  Problem : Trigger limit switch to stop DC motor

I modified this code to control two relays which are wired to motor poles for Forward or Reverse movements until they physically reach a limit switch on either side.

Serial input of 'A' turns on one relay. If Limitswitch1 is pressed, this relay switches off.
It detects the current state of the system and awaits the Serial input of 'B' which then turns on the second relay. If Limitswitch2 is pressed, this relay switches off.

The issues are:

Please help with code - I require option where the two relays switch off on the serial input of letter 'S' and to add the corresponding state machine. Essentially to add a Stop function.
The limit switches work intermittently, sometimes they respond flawlessly, sometimes not at all. I have bought three different brands of switches to test but all have the same behaviour. I have pulled switches up and down with resistors in vain. I have performed button count test using code from this forum and confirm that the switch also behaves erratically. Can changes to code improve switch feedback?

Suggestions will be greatly appreciated.

const byte RELAY1 = 2;
const byte RELAY2 = 3;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;

const byte State_Idle = 0;
const byte State_Forward = 1;
const byte State_Reverse = 2;
byte currentState;

void setup(){
pinMode(RELAY1,OUTPUT);
pinMode(RELAY2,OUTPUT);

pinMode(LimitSwitch1, INPUT);
pinMode(LimitSwitch2, INPUT);

Serial.begin(9600);
currentState = 0xFF; // Force a change to enter the idle state
 }

void loop(){
// Check if we need to change state
byte nextState = currentState;
switch (currentState)
{
case State_Idle:
    { // If we received a valid command, start the operation
        if(Serial.available() > 0)
        {
            switch (Serial.read())
            {
            case 'A':
                nextState = State_Forward;
                break;
            case 'B':
                nextState = State_Reverse;
                break;
            default:
                break;
            }
        }
    }
    break;
case State_Forward:
    if(digitalRead(LimitSwitch2))
        nextState = State_Idle;
    break;
case State_Reverse:
    if(digitalRead(LimitSwitch1))
        nextState = State_Idle;
    break;
default:
    nextState = State_Idle;
    break;
}

// If there was a change, switch state and trigger enter condition
if (nextState != currentState)
{
    currentState = nextState; // Move in the new state
    switch (currentState)
    { // Entering the new state
    case State_Idle:
        // Switch both Relays OFF
        digitalWrite(RELAY1, HIGH);
        digitalWrite(RELAY2, HIGH);
        break;
    case State_Forward:
        // Move Forward
        digitalWrite(RELAY1, LOW);
        digitalWrite(RELAY2, HIGH);
        break;
    case State_Reverse:
        // Move Reverse
        digitalWrite(RELAY1, HIGH);
        digitalWrite(RELAY2, LOW);
        break;
    }
}
}


texts: Rechargeable USB "AA" Batteries. Has anyone used them?

texts:
I have a cosplay project where I'm creating a "Megaman" aka Rockman type of arm cannon (it's actually based on DC's Cyborg). Anyhoo, I've been weighing options like using 3xAA alks or 4xAA nicd (or otherwise 1.2V)--inclcuding various combinations of less or more cells with a voltage regulator; boost up or step down as appropriate.

there are 4 lighted segments (15 leds of WS2812B x 4). I also of course have to power the Arduino Nano as well. I'm flexible on led brightness so I'm just going to tune it [code it] to whatever looks adequate for my purpose. I am aware of the 50ma draw of these units at full brightness

My original plan was to just keep it easy (read lazy) and use 3 AA alks per 2 segments, and another 3 so the nano can have it's own supply. So 9 cells in total (without any additional regulation). Before you judge me--weight, volume, and especially area are definitely big factors in my decision.

So that's a long way to get to my actual question. Has anyone used these new types of USB rechargeable batteries? They seem to have the best of both worlds with the power of an alkaline but the consistency and sustainability of a NiMH /NiCD as they have internal regulators that produce a steady 1.5v (until they don't--which I'm more than cool with)

Short of having a properly regulated 5v power supply, are these a good option if I want to be slightly more responsible than throwing in whatever other AAs I have lying around? They definitely check the box on my space/mass requirements. I'm sure they do fine with most consumer electronics, but as far as arduino and any other custom/hobby 4.5-5v applications how reliable are these? Even if you haven't used them before I'd be curious of your thoughts. I'm a novice at best when it comes to elec engineering.

Yes, they are expensive. Thanks all!

examples:
https://www.amazon.com/Rechargeable-Batteries-Quick-Charge-Integrated-Protection/dp/B07F27PK2M/ref=sr_1_5?crid=1RTQUCZYG4KBM&dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588280164&sprefix=usb+aa%2Caps%2C242&sr=8-5

https://www.amazon.com/Blackube-Rechargeable-Batteries-Lithium-1500mAh/dp/B07D9K2H9H/ref=sr_1_11?dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588282813&sr=8-11


texts: Dim 4k LCD panel in response to ambient light

texts:
Warning: I'm completely new to Arduino, and not even sure if it's the right solution here.

I'm trying to make a better digital picture frame. Got almost all the way there by just buying a nice flat-bezel 4k display, connecting a chromecast, and putting a picture frame on it. Voila!

But I want it to adjust its brightness in response to ambient light -- and turn itself off when the room is dark. So now I need something to check a light sensor and control screen brightness.

Is it possible (and does it make sense) to disassemble the monitor, wire up the LCD panel to a controller with arduino, add in a light sensor, and try to tackle it that way? Is there a better way?

Would greatly appreciate any recommendations / suggestions / ideas.

Thanks!


texts: Prints to the serial monitor are being overwritten

texts:
Using esp32, Arduino IDE 1.8.9 on OSX.

My code is interspersed with Serial.println() writes to the serial monitor of various status messages.

As far as I can tell, if a println is not fully written out to the serial monitor before another println is sent, then the first println does not finish displaying properly, and appears to garbled.

I'm using baud rate 115200.

I'm guessing that there's no flow control between the serial monitor and the computer.

It's strange though because I've been doing quite a bit of Arduino IDE programming for a while now but I don't ever recall this being an issue.

Does anyone have any idea of what might be going on, and how I can ensure that messages are fully displayed on the serial monitor?


texts: Converting code for ATTINY85 to ATMEGA2560. Pin change interupts

texts:
I have code that compiles correctly for an ATTINY85 board using the ARDUINO IDE but I don't have an ATTINY85 board. I have an Arduino Mega ATMEGA2560 and when I select this board in the Arduino IDE the code does not compile and throws this error message

sketch_feb21a:216:3: error: 'GIMSK' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

   ^

sketch_feb21a:216:16: error: 'PCIE' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

                ^

sketch_feb21a:217:3: error: 'PCMSK' was not declared in this scope

   PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin

   ^

exit status 1
'GIMSK' was not declared in this scope

Here is the code snippet that throws the error

void sleep()
{
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin
  ADCSRA &= ~_BV(ADEN);                   // ADC off
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

  MCUCR &= ~_BV(ISC01);
  MCUCR &= ~_BV(ISC00);       // Interrupt on rising edge
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT2);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear SE bit
  ADCSRA |= _BV(ADEN);                    // ADC on

  sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
   /*noInterrupts();
   while (digitalRead(BUTTON_PIN) == LOW);

   delay(50);
   while (digitalRead(BUTTON_PIN) == LOW);
   playTrack(1 + (curTrack++ % 2));
   delay(400);

   interrupts();*/

}


texts: Understanding the meaning of '[](){ /* Code */ }' in an argument

texts:
I have this piece of code from a library and im trying to understand the 3rd argument, I've searched google to the best of my abilities and could not find any tutorials or references in in the C/C++ language about it.
timeOutTask.set(NODE_TIMEOUT, TASK_ONCE, [self = this->shared_from_this()]() {
    Log(CONNECTION, "Time out reached\n");
    self->close();
  });

Specificly im trying to undestand this piece of code that utilizes the above mentioned method.
blinkNoNodes.set(BLINK_PERIOD, (mesh.getNodeList().size() + 1) * 2, []() {
  // If on, switch off, else switch on
  if (onFlag)
    onFlag = false;
  else
    onFlag = true;
  blinkNoNodes.delay(BLINK_DURATION);

  if (blinkNoNodes.isLastIteration()) {
    // Finished blinking. Reset task for next run
    // blink number of nodes (including this node) times
    blinkNoNodes.setIterations((mesh.getNodeList().size() + 1) * 2);
    // Calculate delay based on current mesh time and BLINK_PERIOD
    // This results in blinks between nodes being synced
    blinkNoNodes.enableDelayed(BLINK_PERIOD -
        (mesh.getNodeTime() % (BLINK_PERIOD*1000))/1000);
  }
});

My question comes down to what the [](){ /*Code*/ } actually do in an argument of a function?


texts: ESP8266 seems to be bricked , how to recover?

texts:
In a part of my sketch I put by mistake
pinMode(7,INPUT_PULLUP);
Which is dedicated pin for external flash chip (gpio7/SDIO_DATA_0/SPI_MISO) that not supposed to use for sketch. after uploading sketch now ESP is not responding to any further programming.

Could be Flash chip got corrupted due to the above mistakes?. Is it possible to recover?
I already bricked two of my modules with same sketch before identifying above mistake.
Sketch where working normal on Modules without above code.

When I connect to module with boad-rate 74880 chip returns
 ets Jan  8 2013,rst cause:2, boot mode:(3,7)
please check what happens when I try to upload the code upload error


texts: How can I pulse a stepper motor whilst also wanting to handle other tasks?

texts:
A Polulo A4988 driver board listens for a LOW -> HIGH pulse on a digital pin to step a stepper motor.

A simple way to pulse this with a delay of say 100μs, is to use the delayMicroseconds function:

#define STEP_PIN  3
#define DELAY     100

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

void loop(){
    //heavy computation taking time
    digitalWrite(STEP_PIN, LOW);
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(DELAY);
}

Although this works, the issue is that all the time that the processor spends in the delayMicroseconds function is wasted. This means that if I wanted to, for example, handle inputs from a serial line, I would have no time to do this. In addition, the time for these computations to complete would result in the pulse time increasing which is not ideal as the speed of the stepper would no longer be uniform.

How can I efficiently pulse the stepper at the correct time, whilst leaving my self room to run other tasks between pulses?

P.s. This is for this project: https://github.com/joeiddon/chess_robot.


texts: I have an Arduino nano. I am a beginner to Arduino, so I tired the example sketches. The "Blink" sketch worked well. So now I am trying to get this Micro Servo (9g SG90) to work. No codes built in or the ones if look up on internet are making it rotate. Would love to hear how Icould make the example program "Sweep" is work.


texts: How can I use attached interrupt on my project?

texts:
Hi I have a coinslot project and connected with a fingerprint sensor it was stated in the ardiuno forum that it will work on pin 2 and 3 , but it is already used pins of the finger print sensor .
Coinslot signal is in pin 9 and the in2,3 is for the rx and tx of the fingerprint sensor.


texts: error at compiling : 'class TwoWire' has no member named 'setClock'

texts:
I am a newbie C programmer and I just started with Arduino web editor (Win10-Firefox)to code for a Raspberry Pi (3B) board. RPi is on line via ethernet connection.
I tried to compile an example from Garmin Lidar_lite v3HP for I2C, as available in the library collections for Arduino.
When compiling the example I get after a while this error message:
Using library Wire in folder: /home/builder/.arduino15/packages/arduino/hardware/mraa/1.0.8/libraries/Wire (legacy)
Using library lidar_lite_3_0_3 at version 3.0.3 in folder: /home/builder/opt/libraries/latest/lidar_lite_3_0_3
/tmp/967842743/v3HP_I2C/v3HP_I2C.ino: In function 'void setup()':
/tmp/967842743/v3HP_I2C/v3HP_I2C.ino:51:18: error: 'class TwoWire' has no member named 'setClock'
Wire.setClock(400000UL); // Set I2C frequency to 400kHz (for Arduino Due)
^
exit status 1
Checking the arduino forum I find some similar question, but of many years ago and likely not applicable any longer.
I appreciate your expert inputs on how to resolve in simple terms.
Thanks a lot! Greetz, Ivan


texts: Reliably reloading the calibration data of IMU BNO055

texts:
I am using the BNO055 IMU and the Adafruit Library.
I want to store the calibration data and load them after the microcontroller is powered off and repowered on.
The Adafruit Library provides an example for storing and restoring but, in actual facts, it does not work. It is always required to recalibrate the magnetometers, but even doing so, the library reperform the whole calibration including the accelerometers.

I would like to simply restore all the calibration data (including the magnetometers) so that no calibration needs to be performed when the IMU starts.

I have read a massive amount of posts on the argument, but I really could not figure out how to reliably load all the calibration data at boot and avoid recalibrating them.

Is there anyone who succeeded and can please share the code?


texts: How to read data directly from lcd display

texts:
Referring to post: LCD data read and show on computer
It was not clear what the final code is. Could you post the code and schema again, and if possible, an explanation of how it works?

My problem:

I need to read the information of a lcd 20x4 display, which is controlled by a PLC (which has the protected hex code), and send the data through the serial port.

For this I am using an arduino one to do the reading. I connected the arduino in parallel with the display data bus, to try to read the bits and convert later.

This is the schematic I'm using:

Note: I have placed 1k resistors to make the pulldown on each pin, to avoid reading errors.

With this code:

The problem is that I'm having these results in reading:

No matter what appears on the screen, they are always invalid characters.
If someone identifies where my problem is, I'll be very grateful.


texts: Reading and comparing data from Arduino Uno EEPROM

texts:
I'm trying to read compare data from EEPROM (Arduino UNO). Reading is working fine but comparing it using the '==' operator is not working as expected.

//string 'True' is already stored in EEPROM

int addr = 0;
char value = EEPROM.read(addr);

Serial.println(value);// this line successfully prints the letter 'T'

// but this function is not working
if (value == "T") {
  Serial.println("foo");
}


texts:
I want to connect a Hokuyo scanning range finder to an Arduino Mega, the outputs are labeled like this:

COM+
COM-
Input
Output
DC12/24
GND

I want to read its serial output with Arduino, please help me in details.
Thanks


texts:
Want to use Arduino Time library and occasionally sync it with an external RTC (Maxim DS3231 chip).   I am turning LEDs on and off based on time and using a shift register (Nexperia 74HC154PW) and encoder (ST Micro STP16CPS05TTR).
It has all been working fine, until I decided to use libraries as shown in:
https://github.com/PaulStoffregen/DS1307RTC/commit/160fa0dbca29f6fb3c1465954f89ad7f1f0fbf67
//using libraries shown in examples/SetTime
What I cannot figure out is why using #include <DS1307RTC.h>  prevents the LEDs from lighting.
I have only included code below that lights the LED via a shift register to demonstrate that it runs without an error, but (have to take my word) does not light the LEDs.
If I comment out #include <DS1307RTC.h>  the LEDs light.
Note that in the code below time is not used for anything.
What is including  <DS1307RTC.h>  doing to break it?
Puzzled.
#include <Wire.h>
#include <Time.h>
#include <TimeLib.h>
#include <DS1307RTC.h>    //the problem:  Will not light LEDs if this is used

                          //RTC used is Maxim DS323`chip
                          //RTC connected to ATMEGA328 pin 27 PC4(ADC4/SDA) and pin 28 (PC5 (ADC5/SCL)
                          //RTC works great.

//Ouputs from Atemga and Inputs into 74HC154 pins
const int A0_Pin = 4; // Atmega328 pin  2 = Arduino pin 4
const int A1_Pin = 5; // Atmega328 pin  9 = Arduino pin 5
const int A2_Pin = 2; // Atmega328 pin 32 = Arduino pin 2
const int A3_Pin = 3; // Atmega328 pin  1 = Arduino pin 3

// Shift Register STP16CPS05 has 16 outputs.  Send two sets of 8 bits to turn on columns.  1 = on.
const int latchPin = 9;   // Aruino Pin 9 = ATMEGA328 DIP Pin15 = TQFP Pin 13. Connected to LE-DM1 of STP16CPS05 pin 4  Latch Pin
const int clockPin = 13;  // Arduino Pin 13 =  ATMEGA328 DIP Pin19 = TQFP 17. Connected to CLK of STP16CPS05 pin 3  Clock Pin
const int dataPin = 17;   // Arduino Pin17 = ATMEGA328 DIP Pin 26 = TQFD 26. Connected to SDI of   STP16CPS05 pin 2  Data Pin (SDI)

void setup() {

pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);

pinMode(A0_Pin, OUTPUT);
pinMode(A1_Pin, OUTPUT);
pinMode(A2_Pin, OUTPUT);
pinMode(A3_Pin, OUTPUT);
 }

void loop() {

  digitalWrite(latchPin, LOW);  //LOW through inverter = HIGH = OEDisabled for both Decoder and Shift Reg
                               //LOW Shift Reg New Data to Buffer
  digitalWrite(A0_Pin, 0);
  digitalWrite(A1_Pin, 1);
  digitalWrite(A2_Pin, 1);
  digitalWrite(A3_Pin, 0);

  shiftOut(dataPin, clockPin, LSBFIRST, B11000000);
  shiftOut(dataPin, clockPin, LSBFIRST, B11111111);

  digitalWrite(latchPin, HIGH);  //HIGH through inverter = LOW = OE Enabled for both Decoder and Shift Reg
                               //HIGH Shift Reg Move data to Output pins

}


texts: HC06 correct baud rate but missing characters/ no AT commands

texts:
I have an issue with the communication between my Serial Monitor and my BT HC06 Module. Iam able to send ascii characters from my phone with BT connection to my local serial monitor. When i send characters from my local serial monitor to my BT module i receive something like this: AT -> U or 3 -> 3

I have this issue since i changed the baud from 9600,0,0 to 9600,0,1

Code:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(9600);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}


texts:
I am trying to toggle on/off between two separate HTTP request.
One submit button to turn it on, and another separate submit button to turn it off.
I expect the device to launch in the off/low 0V position
digitalWrite(switchPin2, LOW);
The first submit button would turn the device on/HIGH/sw1, the second submit button would turn it off/LOW/sw2.
But what it is doing is at first nothing when the first/sw1 submit button is pressed but when I press the sw2 submit, I get serial output telling me that sw1 was just pressed. Then if I press sw2 again, it will tell me sw2 was just pressed but will not repeat the cycle until i press sw1 again. Then sw2 becomes functional, just performing the wrong function.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

const char* ssid = "ssid";
const char* password =  "pass";
int switchPin2 = 4;

//counter variable
int switch2;

String inString;

void webpage() {
  server.send(200,
          "text/html",
          " \
           \

Air conditioner manager
 \n\

Turn air conditioner on for "+String(switch2)+" ms
 \
           <form name='frm1 method='post'> \
            <input type='text' name='sw1' value=8000> \
            <input type='submit' value='Submit'> \
           </form> \

Turn air conditioner off for "+String(switch2)+" ms
 \
           <form name='frm2' method='post'> \
            <input type='text' name='sw2' value=8000> \
            <input type='submit' value='Submit'> \
           </form> \
           \
          ");
}

void response() {
  //add additional switch/relay here if adding new plug
  if (server.hasArg("sw1") && (server.arg("sw1").length() > 0)) {
    Serial.print("Switch 1 entered:\t");
    Serial.println(server.arg("sw1"));
    digitalWrite(switchPin2, HIGH);
    Serial.print("\nUnit is on:\n");
    int num = server.arg("sw1").toInt();
    ++switch2;
    server.sendHeader("Location", String("/"), true);
    server.send (302, "text/plain", "");
  } else if (server.hasArg("sw2") && (server.arg("sw2").length() > 0)) {
    Serial.print("Switch 2 entered:\t");
    Serial.println(server.arg("sw2"));
    digitalWrite(switchPin2, LOW);
    Serial.print("\nUnit is off:\n");
    int num = server.arg("sw2").toInt();
    ++switch2;
    server.sendHeader("Location", String("/"), true);
    server.send (302, "text/plain", "");
  } else {
    server.send(400, "text/html", "
HTTP Error 400

Bad request. Please enter a value.
");
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(switchPin2, OUTPUT);
  digitalWrite(switchPin2, LOW);
  WiFi.begin(ssid, password);  //Connect to the WiFi network
  while (WiFi.status() != WL_CONNECTED) { // Wait for connection
    delay(500);
    Serial.println("Waiting to connect...");
  }
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP()); // Print the local IP
  // server.on("/body", handleBody); // Associate the handler function to the path
  server.on("/",HTTP_GET, webpage);
  server.on("/",HTTP_POST,response);
  server.begin(); // Start the server
  Serial.println("Server listening");
}

void loop() {
  server.handleClient(); //Handling of incoming requests
}

I get no error, only erratic output.
How do I toggle on/off between 2 submit buttons?
UPDATE: Serial output.
Waiting to connect...
IP address: 192.168.1.9
Server listening
Switch 1 entered:   8000

Unit is on:
Switch 2 entered:   8000

Unit is off:


texts: Creating an array with the length coming from a library

texts:
When creating an array like in the sketch

#include <Lib.h>

int myArray[Lib::len];

void setup() {}

void loop() {}

the variable len must be an integer constant that is known at compile time. Like shown in the sektch, I want to put the length of the array into a library and get it from there. The problem is that for this to work, you have to initialize the constant already in the .h file, which is against proper library standards. This is how you would do this (.h file of the library):

class Lib {
  public:
    static const int len = 4;
};

The .cpp file doesn't even have to contain anything in this case. The proper way to do things in a library would be like this though:

The .h file:

class Lib {
  public:
    static const int len;
};

The .cpp file:

#include "Lib.h"

const int Lib::num = 4;

But if done like this, len doen't have a value at compile time since the sketch only includes the .h file and not the .cpp file.

Is there any way to intitialize an array in a sketch with its length coming from a library while maintaining proper library design?


texts:
I basically want to have my Arduino accept MIDI data from my digital audio workstation, my choice is Ableton Live. I would then like it to check the received data and change the state of a digital pin accordingly. I made a pretty basic schematic to show you.

(Just a very quick diagram, I intend to use RGB LEDs and transistors of some sort in the final product)

I would be happy using a Serial>Midi of some sort if it's the only way, but true USB MIDI would be nice.


texts: 16*2 1602A LCD not displaying any character or contrast, although correct wiring

texts:
I've used my LCD display with a lot of small projects. Now it doesn't work anymore. Most of the diagrams you find online use resistors and potentiometers. However I never done that, but still got it to work nonetheless.

I tried different schematics, but none of them seem to work. So I'm thinking I broke my LCD somehow.

I'm pretty sure the schematic I'm currently using works. The backlight works but nothing is being printed.

Pictures of the project (Warning!! wire hell)

The LCD component is a blue 16x2 1602A v2.0 display.
All the components come from the official Arduino starter kit, except for the wires. Though I tested every single wire for continuity, to make absolutely sure the problem was not within the wires themselves.
Also, turning the potentiometer doesn't show any blocks, or change anything on the LCD as expected.

Code:

#include <LiquidCrystal.h>
//LiquidCrystal lcd(RS, E, D4, D5, D6, D7);
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  pinMode(6,OUTPUT);
  analogWrite(6,90); //sweetspot for backlight without using a potentiometer.

  lcd.begin(16, 2);
  //lcd.setCursor(0,0);
  lcd.print("hello, world!");
}

void loop() {
}

I'm not sure what's wrong, I tested everything I can think off.

I can upload more (cleaner) pictures if requested, I just didn't want to tear down my other project.


texts: communication between two ultrasonic sensors on different arduino uno

texts:
I am making a project which requires two ultrasonic sensors(HCSR04) connected to different Arduino Unos to communicate with each other.
By communication I mean, one sensor should just detect that other sensor is pointing towards it.
I've put the receiving sensor on Arduino1 and the transmitting sensor on Arduino2. I have covered the transmitter part of the ultrasonic sensor which is supposed to be receiving the signal from Arduino2 which has the transmitter.
I want that the transmitter on arduino2 should send ultrasonic signals and the receiver on the arduino1 should detect it and give an output.
I don't want to know the distance between the two sensors, just whether the transmitter is pointed towards the receiver or not.
The code I have used was for distance between the two sensors, although it didn't work. The code might be wrong now, because I just changed it to upload it to here, because i had written it for more additional modules on the micro controller and didn't want you to get confused.
Again, I don't want to know the distance, I want the receiver to detect the transmitter pointed towards it.
I am not using that code again. I am starting over.
Can anyone help me in the coding part.


texts: Why can't the Atmel ATtiny family delay over a minute?

texts:
I have some really simple code and tested on an 8 MHz ATtiny85 and ATtiny2313. It's basically a blocking blink:

int relayPin = 7;

long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

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

void loop()
{
  digitalWrite(relayPin, LOW);
  delay(onPeriod);
  digitalWrite(relayPin, HIGH);
  delay(offPeriod);
}

When I assign onPeriod and offPeriod to be 1 * 1000 (1 second), the LED will blink as expected. When I add the 60 second multiplier in, it seems to fail.

For the ATtiny85 I use Arduino Pin 4 (physical pin 3) and for the ATtiny2313, I use Arduino pin 7 (physical pin 9).

I program through the Arduino IDE using boards manager to install the ATTinyCore library for the ATtiny2313 and this for the ATtiny85.

Am I doing something wrong here?

It looks like if I throw the delay in a function, and then invoke it with however many seconds I want, it will work. This is not good as it remains blocking. So perhaps the correct way to do this is to grab timestamps.
Here's the somewhat working code:

int relayPin = 4;
unsigned long offPeriod = 60;
unsigned long onPeriod = 60;

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

void loop()
{
  digitalWrite(relayPin, LOW);
  delaySeconds(onPeriod);
  digitalWrite(relayPin, HIGH);
  delaySeconds(offPeriod);
}

void delaySeconds(int s) {
  for (int i = 0; i < s; i++) {
    delay(1000);
  }
}


texts:
I have found code that can blink an LED on Arduino according to Heart Beat. I am using AD8232 as a sensor for Heart Rate.

Code for it is:

//  Variables
int PulseSensorPurplePin = 0; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED13 = 13; // The on-board Arduino LED
int Signal; // holds the incoming raw data. Signal value can range from 0-1024
int Threshold = 550; // Determine which Signal to "count as a beat", and which to ingore.

void setup() {
  pinMode(LED13, OUTPUT); // pin that will blink to your heartbeat
  Serial.begin(9600); // Sets up Serial Communication at certain speed.
}

void loop() {
  Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor's value.
  // Assign this value to the "Signal" variable.
  Serial.println(Signal); // Send the Signal value to Serial Plotter.
  if(Signal > Threshold) {
    // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
    digitalWrite(LED13, HIGH);
  } else {
    digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
  }
  delay(10);
}

My question is: How can I get BPM?

Edited below:

Is this code for BPM correct?

int x = 0;
int LastTime = 0;
bool BPMTiming = false;
bool BeatComplete = false;
int BPM = 0;
#define UpperThreshold 518
#define LowerThreshold 490
int LED13 = 44; // The on-board Arduino LED
int Signal; // holds the incoming raw data. Signal value can range from 0-1024

void setup() {
  pinMode(LED13, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int value = analogRead(0);
  if (value > UpperThreshold) {
    if (BeatComplete) {
      BPM = millis() - LastTime;
      BPM = int(60 / (float(BPM) / 1000));
      BPMTiming = false;
      BeatComplete = false;
    }
    if (BPMTiming == false) {
      LastTime = millis();
      BPMTiming = true;
    }
  }
  if ((value < LowerThreshold) & (BPMTiming))
    BeatComplete = true;
    // display bpm
  Serial.print(BPM);
  Serial.println(" BPM");
  x++;
  Signal = analogRead(0); // Read the PulseSensor's value.
  // Assign this value to the "Signal" variable.
  if (Signal > UpperThreshold) {
    // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
    digitalWrite(LED13, HIGH);
  } else {
    digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
  }
}


texts:
I'm trying to get this program to use channel B for the output waveform using the phase correct PWM mode and using OCR1A as the top. With a 50% duty ratio I'm attempting to  get a 10 Hz freq. I'm able to adjust the OC1A (Pin 9) if I set TCCR1A to 0x43; but nothing comes from pin 10. Code:

include "avr/io.h"

void setup()
{
 DDRB = 0x6; //set pins 9 and 10 as output

 /*set operation Toggle mode; WGM13:0 = 1011 phase correct PWM
CS12:0 = 101 prescaler = 1024*/
 TCCR1A = 0x23;
 TCCR1B = 0x15;

 OCR1A = 0x187; //391 for 50% duty cycle
 TCNT1 = 0; //clear counter and update OCR1A
}
void loop()
{ }


texts: How does the motor shield determines how much voltage to supply to a motor?

texts:
Can i connect 6v DC motor and 12v DC motor, or 6v DC and 12V stepper to adafruit motor shield v1, and an external 12v power supply?
also, how does it determine how much voltage needs to be supplied to a motor? is it done by code, when we set the speed of the motor, or the frequency?

do i have to take care of how much voltage i am supplying to the motor shield?


texts:
I've been trying to follow a few tutorials on how to get the 7 segment to display simple output but none seem to work 100%.

It starts out fine. It increments the number across the screen and then writes 8s to all of them and then reverses. After a few loops however it starts to act weird. Here's a video link where it acts a bit weird (a few digits don't write correctly and fix themselves) and then at the end, it only displays half of the 8 digit display before it goes to 8s and crashes. https://youtu.be/LD_C7I_bGyc

Here's the code:

//We always have to include the library
#include "LedControl.h"

// pin 4 is connected to the DIN pin
// pin 2 is connected to the CLK pin
// pin 3 is connected to the CS pin
// 1 as we are only using 1 MAX7219
LedControl lc = LedControl(4, 2, 3, 1);

void setup(){
    // the zero refers to the MAX7219 number, it is zero for 1 chip
    lc.shutdown(0, false);// turn off power saving, enables display
    lc.setIntensity(0, 0);// sets brightness (0~15 possible values)
    lc.clearDisplay(0);// clear screen
}

void loop(){
    // numbers 7 to 0
    for (int a = 0; a < 8; a++){
        lc.setDigit(0, a, a, false);
        delay(100);
    }
    delay(1000);
    // display number 8 on all segments
    for (int a = 0; a < 8; a++){
        lc.setDigit(0, a, 8, false);
        delay(100);
    }
    delay(1000);

    for (int a = 8; a >= 0; a--){
        lc.setDigit(0, a, a, false);
        delay(100);
    }
}

Hardware:
   Arduino Uno: https://www.jaycar.com.au/duinotech-uno-r3-development-board/p/XC4410
   8 digit display: https://www.jaycar.com.au/8-digit-7-segment-display-module/p/XC3714

At this stage it's hard to tell if it's a hardware issue or if it's setup related. If someone could please give me some insight or maybe run it if they have the same hardware that would be fantastic.

Thanks!


texts: SerialEvent handling when using multiple serial ports

texts:
I would like to use multiple (three) serial ports on an Arduino Due. Instead of polling the ports continuously, I would like to use a Serial.Event function for each of the ports. These handler functions will read out the incoming string from the port and parse the string (i.e. check for a pre-defined command and call a corresponding sub-routine).

I was wondering what is going to happen when serial data arrives at the same time at two different ports? For example, if the program is in the process of handling/parsing the first serial message, will it interrupt/abandon this process as soon as another SerialEvent on another port is triggered? Or will it complete the first SerialEvent routine before going to the second one?


texts: Is there a way to pause Program execution?

texts:
I understand that Arduino programming is procedural and not so much Object Orientated and also that the Arduino or AVR are only single core processors and any kind of "Multitasking" or "Threading" is emulated at best but I was wondering if there is a way to pause program execution in one area temporarily and give another area control? For example say we have the following class:

Class A{
   void Test();
   void ProgramLoop();
}

void A::Test(){
   for (int i = 0; i < 10; i++){
      //Lots of cool stuff going on here but need to give
      //Control to someone else say ProgramLoop()
      Sleep(10);
   }
}

void A::ProgramLoop(){
   Serial.println("In Program Loop");
}

Then in the main file:

A testClass;

void Setup(){
   Serial.begin(57600);
}

void Loop(){
   testClass.Test();
   testClass.ProgramLoop();
}

I know I could do something like:

void Loop(){
   if (!testClass.isBusy){
      testClass.ProgramLoop();
   }
}

But I am trying to find out if there is a way to control how the program execution gives control? I understand that this is more of a threading topic, thats not what I am trying to get at, I just want to know if this is possible maybe using some sort of built in function or something? Or do my programs have to "Fall Through" being ONLY Procedural?


texts: How does the microcontroller know which clock to use?

texts:
I had seen some tutorials on how to assemble an Arduino on a breadboard. They all just place the external crystal oscillator according to the circuit and then, just burn the bootloader and it starts working. According to my little knowledge the fuse bits have to be set before using the external clock.

My question is - How does the microcontroller know which clock to use internal or external? Is there any setting already in the bootloader that tells the microcontroller to use the external clock?


texts: Using INT2/3 on Arduino Micro (Atmega32u4)

texts:
My project is using almost all the pins on this board and I require an interrupt pin to read radio state (rather than polling). I'm using I2C, so that leaves INT2 and INT3, which are the TX and RX pins for USB/Serial1. According to the documentation, disabling serial, using Serial.end(), should allow me to take control of those pins. However, using the pins as interrupt handlers doesn't work. Here is a sample sketch:

static int ledpin = 13;
volatile byte state = LOW;

void func()
{
  state = !state;
}

void setup() {
  Serial.end();

  pinMode(ledpin, OUTPUT);

  // INT2
  pinMode(0, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(0), func, CHANGE);

  // INT3
  pinMode(1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(1), func, CHANGE);
}

void loop() {
  digitalWrite(ledpin, state);
}

This example is mostly copy-pasted from the Arduino website. All the other interrupts work fine, only INT2 and INT3 don't.

Is there a way to use these interrupts?


texts: Control Android Camera using Arduino over Bluetooth

texts:
I want to Control Android Mobile Camera shutter using Arduino over Bluetooth. So i can click photos using arduino.

I have HC-05 Bluetooth Module and Arduino Nano/Arduino leonardo.

The Connection as shown in figure.

The Android mobile successfully connected to Bluetooth Module but i am not found any code to control camera or any button on android mobile.


texts: During this week i purchased two hc-06 bluethoot module for arduino with the purpose of maintain a stable bluethoot connection between two arduino devices. Most people use hc-05 and hc-06 togheter so my question is if i can make a connection without hc-05 module.


texts: How to determine minimum and maximum angle for cheap servos?

texts:
I have some cheap KY66 (seems to be SG90 clone) servos.

When I turn them to 0°, the servo tries moving and moving, without actually getting to 0°. I read that they are reaching the endpoint but the built-in potentiometer does give a reading of 0.

By changing the code and fiddling with the angle, I find that the minimum for one particular servo is 25°.

I'm now trying to figure out how the Arduino could determine this value automatically. I have tried

servo.write(0);
delay(3000);
int direction = servo.read();

and expected to get back a value near 25, but it was 0 instead. So the result of read() does not seem to be an actual reading, but more the "last known" setpoint.

I've also tried to relax the servo before reading:

servo.write(0);
delay(3000);
int direction = servo.read();

with no better result.

I like to figure out the minimum and maximum angle of the servo

because I don't like the servo to make much noise (it really doesn't sound healthy)
without having the user to figure out by himself and the need of re-programming the Arduino.

I know that these cheap servos only have 3 pins. 2 pins are for power supply only, so there's only 1 pin left.

My questions:

Is the data pin uni-directional (PWM output from Arduino to servo)?
Will it ever be possible to implement what I want without additional hardware?
How do people solve this issue? Do more expensive servos either have better calibration to actually go from 0° to 180° or do they provide a way to read the potentiometer with another pin?


texts: What purpose does the yellow and green LEDs have on the Arduino?

texts:
I have wired up a small project with a shift register (see below), but depending on how I put the 74HC595 IC (8-bit shift register with 3-state output register), the green and yellow LEDs of the Arduino stop shining.

What are these LEDs for? Do they tell something about a possible damage of the IC/short circuit in the setup?


texts: Arduino Square Wave Phase Shift by 270 degrees

texts:
I am using this code to generate a square wave with Arduino and shift it by 90 and 180 degrees. However, this code is not able to shift it to 270 degrees. Could you please suggest how may I modify the code so that it supports a 270 degrees square wave phase shift operation.

void setup() {
  pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
  pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B
  // Both outputs in toggle mode
  TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );
  // CTC Waveform Generation Mode
  // TOP=ICR1
  // Note clock is left off for now
  TCCR1B = _BV( WGM13) | _BV( WGM12);
  OCR1A = 0;    // First output is the base, it always toggles at 0
}
// prescaler of 1 will get us 8MHz - 488Hz
// User a higher prescaler for lower freqncies

#define PRESCALER 1
#define PRESCALER_BITS 0x01
#define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

// Output phase shifted wave forms on Arduino Pins 9 & 10
// freq = freqnecy in Hertz (  122 < freq <8000000 )
// shift = phase shift in degrees ( 0 <= shift < 180 )
// Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC
/// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.
int setWaveforms( unsigned long freq , int shift ) {
  // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.
  unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave
  ICR1 = clocks_per_toggle;
  unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision
  OCR1B= offset_clocks;
  // Turn on timer now if is was not already on
  // Clock source = clkio/1 (no prescaling)
  // Note: you could use a prescaller here for lower freqnencies
  TCCR1B |= _BV( CS10 );
}
// Demo by cycling through some phase shifts at 50Khz
void loop() {
  setWaveforms( 40000 , 0 );
  delay(1000);
  setWaveforms( 40000 , 90 );
  delay(1000);
  setWaveforms( 40000 , 180 );
  delay(1000);
}


texts: Error on sending AT+CWJAP_DEF commands to ESP8266

texts:
I am trying to send AT commands to ESP8266 to get connected with internet with the Wifi.

When I am sending AT and AT+RST command on serial monitor then I am getting OK and ready response which seems perfect.

Then I am sending AT+CWLAP to get list of available wifi networks which is also executing correctly.

AT+CWLAP

+CWLAP:(3,"Moto",-42,"a4:70:d6:7a:fa:6c",1,25,0)
+CWLAP:(4,"PRANJAL",-95,"1c:a5:32:3d:f5:c4",1,-16,0)
+CWLAP:(2,"VIHAN",-94,"c8:3a:35:2f:1d:81",1,-21,0)
+CWLAP:(3,"Tenda",-93,"c8:3a:35:20:a9:b1",9,-4,0)

OK

Then I sent AT+CWMODE? which is also perfect.

AT+CWMODE?

+CWMODE:1

OK

Now I am trying to connect ESP8266 with above listed Wifi with this command, it is sending an ERROR on serial monitor.

  AT+CWJAP_DEF="Moto","reset1234"

Error

⸮=IRe"Moto","reset1234"

ERROR

Can anyone suggest me what could be the reason of this issue ?at