texts: What else is consuming Data Segment reported by avr-size?

texts:
I am facing a low memory available problem in arduino. I am compiling a big sketch for arduino mega 2560.
Analysing a .elf file, the avr-size tool gives:
text    data     bss     dec     hex filename
68524   4392    2560   75476   126d4 C:\Users\LEAN...

And the avr-nm (avr-nm doc) shows only variables with t, T, b, d and B. The following is how the command is executed (the output is being saved in a file called test.txt).
   avr-nm -a -td -C -l --size-sort -r x.elf >> test.txt

Then, I perform a sum to confirm the avr-size result using this Python script:
f = open("test.txt", "r")
lines = f.readlines()
f.close()

su = 0
dsum = 0
bsum = 0
tsum = 0
gsum = 0
for line in lines:
    #print(line, end="")
    s = line.split()
    try:
        val = int(s[0])
        su = su + val
        if(s[1].lower() == 'b'):
            bsum = bsum + val
        if(s[1].lower() == 'd'):
            print(line)
            dsum = dsum + val
        if(s[1].lower() == 't'):
            tsum = tsum + val
        if(s[1].lower() == 'g'):
            gsum = gsum + val
    except:
        print("ERR: ",s[0])
print("\n\nSIZE: ", su)
print("SIZE d/D: ", dsum)
print("SIZE b/B: ", bsum)
print("SIZE t/T: ", tsum)
print("SIZE g/G: ", gsum)

and the sum result of each var type is:
SIZE:  71015
SIZE d/D:  135
SIZE b/B:  2560
SIZE t/T:  68320
SIZE g/G:  0

The question: Here d/D sums is 135 bytes. So, why the data segment reported by avr-size is 4392 bytes? how to find out what is occupying this space?
Best Regards.
EDIT
It must be a Joke!
I have a lot of like this in the code:
Serial.print("QTDE REG: ");

Just changing for this:
Serial.print(F("QTDE REG: "));

I have reduced by 10 the .data size!
So, in this way Serial.print("QTDE REG: "); "QTDE REG: " is stored as a global variable?? I thought the compiler would save locally.
EDIT 2
I have an advance running avr-objdump -s -j .data x.elf as suggested by Edgar below. Now I see that all my string literals are in data! For example:
void myFunction(){
    ...
    sprintf(buf, "{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},", (int)settings.treg);
    ...
}

avr-objdump -s -j .data x.elf shows:
 800660 2c007b22 6e616d65 223a2249 6e746572  ,.{"name":"Inter
 800670 76616c6f 20646520 52656769 7374726f  valo de Registro
 800680 73222c22 76616c75 65223a22 2564222c  s","value":"%d",
 800690 2022756e 6974223a 2243227d 2c007b22   "unit":"C"},.{"

EDIT 3
As commented, all string literals are saved in the (SRAM). So, the problem is, I have a lot of strings literals spread across different functions. How to save this amount of SRAM? Note that using F() for sprintf gives compilation error.
Is there any way to put the literal in stack (release memory when function returns) and not in the global area? Is F() the only solution?
============ SOLUTION ============
For now, I have found this solution: use sprintf_P with PSTR(...) in the same way of F(...):
sprintf_P(buf, PSTR("{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},"), (int)settings.treg);

I will test more...
Thanks for all clarification!
Best Regards!


texts: How to Insert Data in Arduino's Direct Mysql

texts:
As inserted in a Arduino Mysql Direct Tablela I'm new to Arduino and would like to know how to do something in the code to make a copy in the database

This code to pass the RFID and authorized storage software, the green light and the one-touch sound, which actually does the carrying out of an insert into a database.

I'm using ESP01

 #include <SPI.h>
 #include <MFRC522.h>

 //Pinos
 #define LED_VERDE 6
 #define LED_VERMELHO 7
 #define BUZZER 8
 #define SS_PIN 10
 #define RST_PIN 9

String IDtag = ""; //Variable that will store Tag ID
bool Permitido = false; //Variable verifying the permission
//Vector responsible for storing the ID's of the registered Tag's
String TagsCadastradas[] = {"669b5d5e",
                        "ID_2",
                        "ID_3"};

MFRC522 LeitorRFID(SS_PIN, RST_PIN);    // Creates a new instance for the
reader and passes the pins as parameter

void setup() {
    Serial.begin(9600);             // Initializes Serial communication
    SPI.begin();                    // Initializes SPI communication
    LeitorRFID.PCD_Init();          // Initializes the RFID reader
    pinMode(LED_VERDE, OUTPUT);     // Declare the pin of the green led as
output
    pinMode(LED_VERMELHO, OUTPUT);  // Declare the red led pin as output

    pinMode(BUZZER, OUTPUT);        // Declares the buzzer pin as output
}

void loop() {
Leitura(); // Call the function responsible for reading the Tag's
  }

  void Leitura(){

    IDtag = ""; // Initially IDtag must be empty.

    // Check if there is a Tag present
    if ( !LeitorRFID.PICC_IsNewCardPresent() ||
 !LeitorRFID.PICC_ReadCardSerial() ) {
        delay(50);
        return;
    }

  // Get the Tag ID through the functionRFID.uid and store the ID in the
  variable IDtag
    for (byte i = 0; i < LeitorRFID.uid.size; i++) {
        IDtag.concat(String(LeitorRFID.uid.uidByte[i], HEX));
    }

    // Compare the value of the read ID with the IDs stored in the vector
  TagsCadastradas[]
    for (int i = 0; i < (sizeof(TagsCadastradas)/sizeof(String)); i++) {
      if(  IDtag.equalsIgnoreCase(TagsCadastradas[i])  ){
          Permitido = true;
 // Permitted variable assumes true valueif the ID Lido is registered
      }
    }

    if(Permitido == true) acessoLiberado(); // If the Allowed variable is
  the function will be called acessoLiberado()
    else acessoNegado(); // If the function is not called acessoNegado()

    delay(0001); / wait 2 seconds to re-read
  }

    void acessoLiberado(){
    Serial.println("Tag Cadastrada: " + IDtag); //Exibe a mensagem "Tag
    Cadastrada" e o ID da tag não cadastrada
    efeitoPermitido();  //Chama a função efeitoPermitido()
    Permitido = false;  // Set the variable Allowed to false again
   }

  void acessoNegado(){
  Serial.println("Tag NAO Cadastrada: " + IDtag); //Exibe a mensagem "Tag
  NAO Cadastrada" e o ID da tag cadastrada
  efeitoNegado(); //Chama a função efeitoNegado()
  }

  void efeitoPermitido(){
  int qtd_bips = 2; //definindo a quantidade de bips
  for(int j=0; j<qtd_bips; j++){
  //Switching on the buzzer at a frequency of 1500 Hz and turning on the
  green led.
  tone(BUZZER,1500);
  digitalWrite(LED_VERDE, HIGH);
delay(100);

//Desligando o buzzer e led verde.
noTone(BUZZER);
digitalWrite(LED_VERDE, LOW);
delay(100);
}
}

void efeitoNegado(){
int qtd_bips = 1;  //definindo a quantidade de bips
for(int j=0; j<qtd_bips; j++){
// Turning on the buzzer with a frequency of 500 hz and turning on the red
 led.
tone(BUZZER,500);
digitalWrite(LED_VERMELHO, HIGH);
delay(500);

//Desligando o buzzer e o led vermelho.
noTone(BUZZER);
digitalWrite(LED_VERMELHO, LOW);
delay(500);
}
}


texts: I am using an XBee radio setup to transmit bytes over a distance of approximately .25 miles. For the first 20,000, or so, transmissions it was completely error free. However, once there was a single error, every other transmission became an error. For my project a transmission consists of three bytes, with the third byte being an XOR of the first two. The first byte also has a parity bit. The 1st byte is a sensor number and the second byte is data. In the past I've received a few transmissions with errors detectable through the parity or XOR, but these did not cause an "avalanche effect" of errors. However, yesterday when I was running the radio setup, after ~20,000 transmissions (~60,000 bytes) there was an error, and after that error occurred, all transmissions were detected as containing errors. What I am hypothesizing occurred was that a single byte was dropped in transmission completely throwing off the sequence of bytes for a transmission. For example, the second "data" byte was lost, meaning the next transmission would consist of the first "sensor" byte, the third "XOR" byte, and the next first "sensor" byte. This error would continue to effect all later transmissions. I am operating a baud rate of 9600, with a nominal baud rate that is much lower. For this reason, I do not believe this is an issue with the serial buffer instead of a dropped byte, but I could be wrong. Is it possible that a byte would be dropped given the scenario I explained? If so, how could this be fixed in software/hardware? If it is likely to be a serial buffer issue, can this be solved? I know according to the Arduino core documentation increasing the serial buffer size beyond 256 may cause race conditions.


texts: Wire with MCP23008 I/O expander with I2C

texts:
I'm trying to read from an MCP23008 I/O expander using the Wire library over I2C. The MCP23008 is wired to address 0x04, giving an effective device address of 0x24. Writing to the device GPIO seems to work fine, and I'm a bit confused on how to read from the GPIO.

So I set it up for read as follows:

#define MCP23008_DEVICE_I2C_ADDRESS 0x20
#define MCP23008_SLAVE_I2C_ADDRESS  0x04

#define MCP23008_REGISTER_IODIR     0x00
#define MCP23008_REGISTER_GPIO      0x09

#define IO_ALL_PINS_INPUT           0xFF

inline void eeprog::_read_enable()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_IODIR); // Set I/O direction
        Wire.write(IO_ALL_PINS_INPUT);       // Set all pins as input
    }
    Wire.endTransmission();
}

after which I attempt to read from it, by first addressing the GPIO register and then requesting a byte to read:

inline uint8_t eeprog::_read()
{
    Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
    {
        Wire.write(MCP23008_REGISTER_GPIO); // Select the GPIO register
    }
    Wire.endTransmission();

    Wire.requestFrom(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS, (uint8_t)1);

    return Wire.read();
}

Looking at my logic analyzer this is what I get:

The NACK seems to indicate that the read went wrong.. actually a bit unsure what "Data read: 07" means in this context, did it read the value 7, or did it try read address 07?

Any ideas what I could be doing wrong? Am I missing something obvious from the documentation?


texts: Can I charge a 4.2 V battery with a 5 V adapter?

texts: Can I charge a 4.2 V battery with a 5 V adapter without damaging the battery?


texts: Code not working with DHT11; the sensor returns 0 values now and before that the LED wasnt turning on

texts:
I know my code will not be great and this is very basic code, however this is my first (and last) time ever coding for a project, I have very little knowledge of code. The aim of my code is to make a LED light turn on when the humidity reaches above 70 using a DHT11 sensor. My sensor used to work before I changed the code somehow and now it does not, and also the LED has never turned on as my if statements intend it to. How do I need to adjust/redo my code for it to work and to achieve my aim?
#include <SimpleDHT.h>

// for DHT11,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11;
const int ledPin = 13; // We will use the internal LED

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); // Set the LED Pin as an output
}

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT11...");
  float h = SimpleDHT.readHumidity();
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if (h >= 70) {{
    digitalWrite(ledPin,HIGH); //Turn the LED off
  else {
    digitalWrite(ledPin,LOW);
  } else if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("uh oh not working ! :(  "); Serial.println(err);delay(1000);
    return;
  }
  Serial.print("Sample OK: ");
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");
  // DHT11 sampling rate is 1HZ.
  delay(1500);
}


texts: C Serial Communication Code is unreliable

texts:
This going to be a difficult to debug problem but I hope some ppl here have C knowledge and idea what's going on. Given an arduino nano which is controlled by a C program from WRT54G.

Here is the relevant part of the arduino code:

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

 int integerValue=0;

                              // Max value is 65535
char incomingByte;

void loop() {
  if (Serial.available() > 0) {   // something came across serial
    integerValue = 0;         // throw away previous integerValue
    while(1) {            // force into a loop until 'n' is received
      incomingByte = Serial.read();
      if (incomingByte == '\n') break;   // exit the while(1), we're done receiving
      if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
      integerValue *= 10;  // shift left 1 decimal place
      // convert ASCII to integer, add, and shift left 1 decimal place
      integerValue = ((incomingByte - 48) + integerValue);

    }
   Serial.print("Command: ");
   Serial.println(integerValue);

  }
}

Pretty straight forward (it converts serial received ascii chars to numeric format), arduino receives a simple integer and it runs a function. For example 1-> turn on relay1. This work's reliably for sure because I can just do:

echo "1" > /dev/tts/1

from the terminal.

Now here is the relevant part of the C code:

    int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
    {
        char b[1];  // read expects an array, so we give it a 1-byte array
        int i=0;
        do {
            int n = read(fd, b, 1);  // read a char at a time
            if( n==-1) return -1;    // couldn't read
            if( n==0 ) {
                usleep( 1 * 1000 );  // wait 1 msec try again
                timeout--;
                continue;
            }
    #ifdef SERIALPORTDEBUG
            printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]); // debug
    #endif
            buf[i] = b[0];
            i++;
        } while( b[0] != until && i < buf_max && timeout>0 );

        buf[i] = 0;  // null terminate the string
        return 0;
    }

    /* Only use integer commands */
    int serialport_write(int fd, int comm_no)
    {
        char command[6];

        sprintf(command,"%d\n",comm_no);
        printf("Sending Command:%s",command);

        int len = strlen(command);
        int n = write(fd, command, len);
        if( n!=len )
            return -1;
        return 0;
    }

void *ardu_handler(void *fdfd)
{
  int fd = *(int*)fdfd;
  char buf[256];
  char getback[10];

  while (1)
   {
     memset(buf, 0, sizeof(buf));
     serialport_read_until(fd, buf, '\n', 256, 5);
     fprintf(stderr, "Received: %s\n", buf);
   }
}

Then a C thread will be started with the ardu_handler which in this case doesn't do anything else just print's back the response from the ardu.

What's happening is when I send a command I start getting back infinite amount of commands (up until I close the C app and start it again) and to make it worse it is even inconsistent.

For example:

Command: 62143
Command: 7891
Command: 3216
Command: 11287
...
runs forever.

What I asking myself is whether these responses coming out from the arduino or they are just coming out from the bogous C program...
It's not possible to connect to see what's coming out on the serial port unfortunately until this program holds the port open.

Although I run the C code on mips this was doing the same thing back on x86 PC with an arduino uno (sometimes it is stable but then it falls into this unstable state and floods the serial port). It was unreliable and I would like to make it reliable.


texts: How to programmatically upload an Arduino sketch generated by node.js (electron) or from browser?

texts:
We are trying to make an app that generates an Arduino sketch (.ino) using Google's Blockly and node.js, and uploads it to Arduino.

Even after searching a lot, I am unable to find how to build and upload the generated code to the board. Is there any tool or API available for node.js to do the same?

Or could I call some binary for this function. Please help.


texts: how long should interrupting signal last?

texts: I want to apply the interruption of a program with a RISING signal from a pin. How long should the signal rise to be considered as the interruption?


texts: Bootloader is not burned in Arduino Uno R3 board (ATmega 328P)

texts:
I have tried many times to burn the bootloader on an Arduino Uno R3 (ATmega328P-PU) using a Chinese clone, also shown in the image

I used Arduino IDE 1.8.5. I have to make sure that all the connections are made correctly as shown in the Arduino website. The image for the target is:

.

I made the following connections:


texts: Why Blynk code doesn't have anything in the loop except for one statement

texts:
When I was trying to use the Blynk app for the first time I got code from their website that had only one statement in the loop.
How does the code determine what to do when we press a button in the app? Does the app have the code and is that why it tells us to select the pin for the buttons? Can I add my own code after the main Blynk code?
I'm doing a project to control lights in my home with WiFi (Blynk) and an IR remote using an IR receiver with an Arduino. Can I combine and do both, like accept inputs from both Blynk and IR remote or can I use only one?


texts: Why is the piezo buzzer not making any sound?

texts:
My ciruit:

My code:

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   tone(12,260);
  {
 }
  }
}

What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the tone(12,260); that I added?


texts: Arduino changing output based on wire voltage

texts:
I’m new to arduino and I want to build myself smart switch that can be turned of both manualy and via wifi, is there any way to change position of relay based on if another wire is live or not? Im from europe so we have 230V  outlets.
Thanks for the answer.


texts: "variable must be const" fix for Arduino progrem

texts:
I am trying to upload to my nano the code attached. It is giving me an error saying variable must be const about something I am trying to put in progrem. I learned that installing a older version of the compiler worked. However I was wondering is there a way to just edit the code to make it work. I tried putting const before it but it didn't work. It is on line 78 and 79 of the first file.

const extern PGM_P *NApowerCodes[] PROGMEM;

const extern PGM_P *EUpowerCodes[] PROGMEM;


texts: Inaccurate PWM Signal Frequency and Timing

texts:
I have a Teensy 3.2 and I am using the Arduino IDE to program it. I am trying to generate 8 pulses with the frequency of 40 kHz and this needs to be repeated every second. I have written 3 different codes and none of them is working quite the way I wanted. The duty cycle of the pulses are not always constant (i.e. the falling edge often shifts in the time axis), indicating an inaccuracy with the delay between the analogWrite commands. There seems to be an issue with delays not being consistent and changing within the 8 pulses and between the 8 pulses. This inaccuracy is different between the 3 different codes, but exists in all of them. Changing the processor speed between 16 MHz and 120 MHz does not appear to change the problem (except in code 3 where NOP is dependent on it). Is there a way to make the cycles more consistent at 40 kHz? Do I need to use an external timer or oscillator? The two images below display the two problems. The first image shows the differences in time delays and output frequency. The red dashed lines are provided to show the discrepancy in the same pulse at successive iterations of the code. The second image shows a recurring issue where the square wave is not in fact a square, and doesn't seem to be caused by software problems.

Image 1:

Image 2:

The codes I have written can be found below:

Code 1:

const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  analogWriteFrequency(pin1, 40000);
  analogWriteFrequency(pin2, 40000);
}

void loop() {
  analogWrite(pin1,128);   //for 50% duty cycle
  delayMicroseconds(188);  //It takes 187.5us to generate 8 pulses at the given frequency
  analogWrite(pin1,0);
  delay(1000);
}

Code 2:

const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayMicroseconds(10);
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayMicroseconds(10);
      analogWrite(pin2, 0);
  }
}

Code 3:

const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

// Variable N determines the length of the delay.
// Execution of NOP corresponds to 62.5ns delay
// when the processor speed is 16 MHz.
const int N = 50;
#define NOP __asm__ __volatile__ ("nop\n\t")

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayNOP();
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayNOP();
      analogWrite(pin2, 0);
  }
}

void delayNOP(){
  for(int j =0; j<=N; j++){
    NOP;
  }
}


texts: Serial.write displaying repeating output from Xbee communication

texts:
I want to use xbee's to communicate between two different arduinos.  I'm using this tutorial as a guide to setup my xbee's. I've already used XCTU to setup one xbee as a router and another as a coordinator (both in ZIGBEE AT mode).  I used XCTU's terminal feature to verify that info was being sent and received properly.

Basically, I have both arduinos connected to the same PC via USB cables, but the communication is taking place through the Xbee's.  I also made sure to disconnect the TX & RX wires when uploading the sketches to avoid an AVRDUDE error.

I wanted to test the communication by sending a "hello world" message once every five seconds, from the router to the coordinator.  To do this, I wrote the following code:

//Code for Arduino attached to Xbee in Router AT mode
void setup(){
 Serial.begin(9600);
}

void loop(){
  Serial.println("Hello World!");
  delay(5000);
}

and

//Code for Arduino attached to Xbee in Coordinator AT mode
void setup(){
  Serial.begin(9600);
}

void loop(){
  if (Serial.available()>0){
    Serial.write(Serial.read());
  }
}

I checked the serial monitor for the arduino connected to the router, and it does exactly what I expected to see:  a new Hello World message once every 5 seconds.  However, the serial monitor on the arduino connected to the coordinator does not produce the desired effect:  the "hello world" message instantly displays the message over a hundred times per second and repeats without end, each time on a separate, new line.  Sometimes, when I turn the serial monitor on, the message instantly appears with a few repetitions before displaying some strange characters and stopping altogether.

I'm not sure if the problem is with the serial monitor or with the xbee.  Any help with this problem would be greatly appreciated.


texts: Arduino Due SAM3X ADC programmable input offset not working

texts:
In the datasheet of the SAM3X8E in Section 43.6.9 Page 1327 it clearly states that the SAM3X/A has a programmable offset for ADC input in Single-Ended mode and I believe that the Atmel ASF library also has a function dedicated to configuring analog offset for SAM's ADC (adc_enable_channel_input_offset). However the following lines of code did not work:

  adc_set_writeprotect(ADC,0);
  adc_enable_anch(ADC);
  adc_disable_channel_differential_input(ADC, ADC_CHANNEL_5);
  adc_set_channel_input_gain(ADC, ADC_CHANNEL_5, ADC_GAINVALUE_2);
  adc_enable_channel_input_offset(ADC, ADC_CHANNEL_5);
  adc_set_writeprotect(ADC,1);

Why??


texts: Got Trouble with ESP8266 and Arduino Yun using REST control

texts:
Sorry about my English.

I'm a new bie in program Arduino and interested in ESP8266. I'm trying to use ESP8266 control Arduino Yun using REST API.

Like you know, we using web browser as

http://<Arduino_Yún_Address>/arduino/<status>/<pin>/<value(optional)>

Example: http://<Arduino_Yún_Address>/arduino/digital/13/1

you bring pin 13 to high, by closing the relay and giving light to the LED,

while with: http://<Arduino_Yún_Address>/arduino/digital/13/0

the relay is opened and the LED is turned off

and I want to use ESP8266 to send command like using web browser and it didn't work.

After connect to Wifi access point and Server of Yun done, I've tried to send command like

GET /http://<Arduino_Yún_Address>/arduino/digital/13/1

Please give me some idea or move advices about this situation. Thanks for reading my topic.  :D

Here is my problem:

AT+CIPSTART="TCP","192.168.0.150",80

OK
Linked
AT+CIPSEND=58

> GET /http://192.168.0.150/arduino/digital/13/1 HTTP/1.0\n

wrong syntax

ERROR


texts: Powering arduino and 12V Fan from same supply

texts:
I have found a relatively small 12V switching power supply that I want to build into my device, using it to power both the Arduino Pro Mini and a couple of 12V cpu fans.

Am I correct in assuming that I can have the Arduino RAW pin and Fan+ on the same power supply lead? Or do I need to protect the Raw pin in any way? Also, I need to power 2x cpu fans, can this be done with one transistor or do I need one for each fan?

If I stay within the Current specs of my supply (6A) could I keep adding other 12V components on the same +lead as in the diagram below?


texts:
New to Arduino and was hoping to figure this out. I am working with a bill acceptor and getting the value once you insert the money. The code works fine with an older Arduino, but I am using Arduino Uno Wifi Rev2 and getting some major issues. I finally go it down to just this error and i cant figure this one out (Help Please!):

invalid type argument of unary '*' (have 'uint8_t {aka unsigned char}')

On line:

*digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

Library that is giving the issue:

ReceiveOnlySoftwareSerial


texts:
I decided to make a pcb based on the atsam3x8e (microcontroller used in Arduino Due). For the design I copied most of the layout that I found on this site and looked at the official Arduino Due schematic as well but decided that I didn't need everything. This is the schematic that I made and the pcb:

The problem is that my laptop doesn't see the "Arduino Due / atsam" when I connect the USB to my pc with a USB cable (with data lines). I understood that the chip chips with the SAMBA bootloader in ROM and that it should be programmable via native usb connection to the chip.
I supply 3V3 with a bench power supply.
Then I tried to follow the checklist for this microcontroller: checklist.
All voltages seem to arrive on the chip. VDDout makes a 1.7 voltage as it should.
I have a clocksignal on my 12Mhz crystal. I don't have a clock signal on my 32khz crystal but when measuring on an official arduino due I also didn't see a clock signal here so I guess this oscillator isn't always on.
I made some wire patches: decoupling cap were not ground referenced and one oscillator pin of 12 Mhz wasn't connected.
Any ideas on how I could further debug this?


texts: Having problems with I2C - Slave is receiving "b ~ ,,,"

texts:
so I'm facing a pretty large problem. I'm experimenting with I2C and using one Arduino that acts as a countdown timer to send the current reading on the timer to another Arduino. I'm pretty new to electronics in general so bear with me.

The way the countdown timer works is it stores the time as a String, and uses substring and toInt() to adjust the timer.

I know that with I2C you can only send some data, Strings not included, so I tried converting the String to an array of characters using toCharArray(). My conversion seems to be working well, as I have tested it with the Serial.println() and it displays the time correctly.

Therefore, I am convinced the problem lies with the Slave code. I'm not sure how to set up the Slave Arduino to receive the actual time. Below, I've pasted links to the code of both the Master and the Slave respectively.

Master: https://pastebin.com/AFjTDZB7

Slave: https://pastebin.com/viNGWn9c

How should I change my slave code so everything works?

Also, when I changed the datatype of "time" in the Slave code from char* to int, all I got in the Serial Monitor was 48. Weird.

Would really appreciate any help and guidance cause I'm pretty stuck. All the tutorials I find online are pretty complicated.

Thanks!

Master Code:

#include < Wire.h >
String time = "10:11";
boolean doubleDigits = false;

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

void loop() {
  Serial.println(time);
  sendTime(time);
  int First2 = time.substring(0, 2).toInt();
  if (First2 > 9) {
    doubleDigits = true;
  }

  int Last2 = time.substring(3).toInt();
  if ((time.substring(3) == "00") && (time != "00:00")) {
    First2 = First2 - 1;
    Last2 = 59;
    if (doubleDigits == false) {
      time = "0" + String(First2) + ":" + String(Last2);
    } else {
      time = String(First2) + ":" + String(Last2);
    }
  } else if (time != "00:00") {
    Last2 = Last2 - 1;
    if (Last2 < 10) {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":0" + String(Last2);
      } else {
        time = String(First2) + ":0" + String(Last2);
      }
    } else {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":" + String(Last2);
      } else {
        time = String(First2) + ":" + String(Last2);
      }
    }
  }
  if (time.substring(1, 2) == ":") {
    time = "0" + time;
  }
  delay(1000);
}

void sendTime(String time) {
  Wire.beginTransmission(9); //transmit to device 9
  char buffer[32];
  time.toCharArray(buffer, 32);
  Wire.write(buffer);
  Serial.println(buffer);
  Wire.endTransmission(); //stops transmitting
}

//master

Slave Code:

#include <Wire.h>
char* time;

void setup() {
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
  Serial.begin(9600);
}

void receiveEvent(int bytes) {
  time = Wire.read(); //read one character from the I2C

}

void loop() {
  Serial.println(time);
  delay(1000);
}

//slave

Edit: added code


texts: How to change i2c address of Lidar Lite v3 using LidarLite library (Solved)

texts:
I have 2 Lidars which are Lidar Lite v3 and Lidar Lite v4, both of these sensor having the same i2c address.
I'm trying to change my Lidar Lite v3's i2c address on arduino mega2560 using a function from LidarLite library from 0x62 to 0x63. However it doesn't seem to work, after I uploaded a code the serial monitor display
> nack

and when I'm using i2c scanner it still show a default address (0x62).
here is my arduino code
#include <Wire.h>
#include <LIDARLite.h>

LIDARLite myLidarLite;

void setup(){
  Serial.begin(115200); // Initialize serial connection to display distance readings
  char newAddress = 0x63;
  myLidarLite.setI2Caddr(newAddress , true);
  Wire.begin();
}

void loop(){

  **** i2c scanner code ****

}

setI2Caddr function from library
void LIDARLite::setI2Caddr(char newAddress, char disableDefault, char lidarliteAddress)
{
  byte dataBytes[2];

  // Read UNIT_ID serial number bytes and write them into I2C_ID byte locations
  read ((0x16 | 0x80), 2, dataBytes, false, lidarliteAddress);
  write(0x18, dataBytes[0], lidarliteAddress);
  write(0x19, dataBytes[1], lidarliteAddress);

  // Write the new I2C device address to registers
  dataBytes[0] = newAddress;
  write(0x1a, dataBytes[0], lidarliteAddress);

  // Enable the new I2C device address using the default I2C device address
  dataBytes[0] = 0;
  write(0x1e, dataBytes[0], lidarliteAddress);

  // If desired, disable default I2C device address (using the new I2C device address)
  if (disableDefault)
  {
    dataBytes[0] = (1 << 3); // set bit to disable default address
    write(0x1e, dataBytes[0], newAddress);
  }
}

I've checked a read function and found this condition
    // A nack means the device is not responding, report the error over serial
    int nackCatcher = Wire.endTransmission();
    if(nackCatcher != 0)
    {
      Serial.println("> nack");
    }

the datasheet of Lidar Lite v3 is here and changing i2c address topic can be found in 5th page
I've tried to compare the function to a datasheet but still have no idea why it didn't work.
So, how can I change an I2C address of Lidar Lite v3 to make them able to work together?

Update
Finally I have found the mistake. The simple way to fix is just call function Wire.begin() or myLidarLite.begin() (which containing Wire.begin inside the function) before using setI2Caddr().
So, the code will be like this
#include <Wire.h>
#include <LIDARLite.h>

LIDARLite myLidarLite;

void setup(){
  Serial.begin(115200); // Initialize serial connection to display distance readings
  Wire.begin(); // or myLidarLite.begin();
  char newAddress = 0x63;
  myLidarLite.setI2Caddr(newAddress , true);
}

void loop(){
  **** i2c scanner code ****
}

After upload to the board, the address is finally changed.
Ps. Btw, when I set 0x64 to setI2Caddr it changed to 0x63 instead of 0x64 and still keep the old address eventhough I set disabledefault as true.


texts:
I want to control speed of an AC Motor using phase cutting..
Well, I already have zero cross detector and SSR but don't know how to program Arduino to phase cutting using SSR..
And to connect the motor to SSR, do I need some protective circuit or not? Thanks!


texts:
I'm using RTClib for my DS3231 module, the problem is the library is displaying the second without zero behind it: 22:1:1 and when i print the time on my 16x2 LCD time is displaying like this:

  22:22:59

  22:23:19

  22:23:29

  ...

  22:23:59

  22:23:10

  22:23:11

the second number of seconds is not getting cleared.
i know one solution to this is to use lcd.clear() function to update the LCD in each loop but is there any other way to clear that second number or do something so library show zero behind second?


texts:
The title sums it all up. While testing  the new proximity detector I bought off of Amazon, a spark flew from some random area and my Arduino's On LED went off while its Loop LED stayed in a dim state. I am here to ask you guys if this basically counts my Arduino as fried and that I need a new one, or if I should wait and see if it works again, being that I wrote this 5 minutes after the thing happened.

Thanks in advance,

afroraydude


texts: How can I read data from power analyzer with arduino NANO through rs485

texts:
well I have this power analyzer. And I want read data with Arduino NANO, through rs485

here is product   and here is the register table of this device.
I am using boud rate 9600, no parity, slave 1
also I had read those link and this video
but still i cant read data from power analyzer with arduino.
there 3 topic I am not sure:

Which library sould ı use? now ı am using modbus master

How should be connection of arduino and tll/rs-485 converter?

How to read data such as:

Address Dec: 0, Address Hex: 0000, Format Word: uint32,  Counts : 2, Unit:
V, Remarks: Voltage L1-N,  Multiplier: 0.1

for example I used this codes
#include <SoftwareSerial.h>

#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin

#define SSerialTxControl 3   //RS485 Direction control

#define RS485Transmit    HIGH
#define RS485Receive     LOW

#define Pin13LED         13

/*-----( Declare objects )-----*/
SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX

/*-----( Declare Variables )-----*/
int byteReceived;
String ph_hexa, ph_hexa_hight_byte, ph_hexa_low_byte, ph_hexa_value;
byte request [] = {
    0x01,
    0x03,
    0x17,
    0x70,
    0x00,
    0x01,
    0x65,
    0x80
};

//01 03 17 70 00 01 65 80 from register table example at last page

void setup()   /****** SETUP: RUNS ONCE ******/
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("YourDuino.com SoftwareSerial remote loop example");
  Serial.println("Use Serial Monitor, type in upper window, ENTER");

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  // Start the software serial port, to another device
  RS485Serial.begin(19200);   // set the data rate

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

void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
   if (RS485Serial.available())  //Look for data from other Arduino
   {
    Serial.print("Response: ");
    for (int i = 0; i <= 6; i++) {
        byteReceived = RS485Serial.read();    // Read received byte

        ph_hexa = String(byteReceived, HEX);

          // index 3 = high byte
          if(i == 3)
          {
            ph_hexa_hight_byte =   ph_hexa;
          }

          // index 4 = low byte
          if(i == 4)
          {
            ph_hexa_low_byte =   ph_hexa;

            ph_hexa_value = ph_hexa_hight_byte + ph_hexa_low_byte;

            Serial.print(ph_hexa_value);// Show on Serial Monitor
          }
        Serial.print(" ");
      }
      /*
      Serial.println(ph_hexa);
      ph_hexa = "";
      */
      Serial.println();
   }
   else
   {
      Serial.println();
      Serial.print("Request: ");
      digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
      for (int i = 0; i < 8; i++) {
        Serial.print(request[i], HEX);
        RS485Serial.write((byte)request[i]);
      }
      Serial.println();
      digitalWrite(SSerialTxControl, RS485Receive);  // Init Transmit
   }
   delay(1000);

}

but there is no Response return
23:17:17.663 -> YourDuino.com SoftwareSerial remote loop example
23:17:17.709 -> Use Serial Monitor, type in upper window, ENTER
23:17:17.756 ->
23:17:17.756 -> Request: 131770016580
23:17:18.691 ->
23:17:18.691 -> Request: 131770016580
23:17:19.719 ->
23:17:19.719 -> Request: 131770016580


texts: Is there some kind of timer function that returns the amount of time passed?

texts: I'm doing a project and I want to get the amount of time between two sensor inputs.  i.e. the sensor detects something, and it triggers a timer, and when the sensor picks up something else, it stops the timer and stores the amount of time the passed in a variable.  Is there a library or a specific function that exists?


texts: I want to run more stepper motors and would like to know if there is a way to connect the Arduino and the ESP8266 NodeMCU together for more functioning.


texts: Communication with Arduino and electronic device(for example tv or computer) through rs 232 cable

texts:
Say some electronic device (TV OR Computer) has an inbuilt program. Depending on received data from Ardiuno, it displays some text based on requirement. For example, if it receives 1 it should display 'error', else if it receives 0 it should display 'ready'.

  I am working on only sending signals/bytes from Arduino Uno to some device which already has an inbuilt program. I just want to send 0 or 1 byte from the Ardiuno to the device using TTL to RS 232 COVERTER.
  this is the code

#include<SoftwareSerial.h>

 #define rxPin 0 //make pin o as rx pin

 #define txPin 1//make pin 1 as tx pin

 SoftwareSerial mySerial(rxPin ,txPin);//i donot undersatnd this line (i got
 the code from net//

 void setup()

 {

     pinMode(rxPin,INPUT);//making rx as input//
     pinMode(txPin,OUTPUT);//making tx as output//
     Serial.begin(9600);
     mySerial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
Serial.print(0x00);//i want to send 0 byte data from ardinuo to device //
delay(200);
}

  I am using RealTerm software to check if the signals I have sent from the Arduino Uno are received as they have to be (without any interference).

  I am sending continuously 0 from ardinuo to realterm in this case(for testing purpose). I am receiving in RealTerm in Hexadecimal format. Since I'm sending 0s continuously, I should be getting a continuous output of 0s on RealTerm as well. Instead, I am getting some random values initially (while uploading the sketch) and RealTerm stops displaying output soon after.

  Can someone please help me solve my issue.

  Update 1: i have modified my code as per @chrisl's  suggestion. Now, whn i send 0 i am getting a correct ouput ,but whn i am sending 1 contineosly i am  getting many 0's and random values

#include<SoftwareSerial.h>
#define rxPin 2
#define txPin 3
SoftwareSerial mySerial(rxPin ,txPin);
void setup()
 {
 pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  mySerial.begin(9600);
  }

  void loop() {
     // put your main code here, to run repeatedly:
  Serial.print(0x01);//i want to send 1 byte data from ardinuo to
  device(realterm)
  delay(200);
   }


texts: Efficient way to store array with repeating values?

texts:
So I have about 2000+ X and Y values where I will look up the Y value for a given X value. If I store the values naively they won’t fit in memory, however there are a lot of repeating values and the X values are arranged in numerical order so I don’t really need to store them explicitly.

So my plan is to use the 3 most common Y values and have an array for all the Y values with only 4 possible values (So using only 2 bits with a bitfield), where 0,1 and 2 corresponds to the most common Y values and 3 tells the program to go fetch the value somewhere else, and here I am thinking a hash table/tree.

Before implementing all this stuff I thought I would ask here if anyone has a better way of doing this, such as if it’s possible/recommended to use the flash memory on the arduino for this or if there’s some better way to store the data. The Y data consists of analog read values which hover around a specific value (say 800) and vary +- 20 or so. I think a histogram of the Y data follows a normal distribution, but I currently do not have enough data to tell.


texts: The Seeeduino Wiki claims that it can run on 3.3V/5V. It doesn't specify if it can step down higher voltages. I am looking to power the XIAO using a battery. It usually uses a USB-C cable which can provide 5V. Will I need to step the voltage down, or does it behave like a normal Arduino Nano and automatically step down the voltage?


texts:
Appears to be something to with Apache configuration, swapping to Nginx solved my issue.

I'm getting slow responses when using localhost with a NODEMCU 1.0 and esp8266 WiFi library.

If I GET a PHP file on a remote server the response is almost instantaneous and the output of the PHP file is printed extremely quickly after the HTTP headers. If I GET the same PHP file on localhost the response takes over 5 seconds even if that PHP files is echoing just a single character.

I've tried with XAMPP and a local server configuration on a Raspberry Pi but both have the same slow response speed.

void loop() {
  WiFiClient client;

  if (wiegand.available()) {
    // Convert the code into a suitable type and construct the GET request
    double readWiegand = wiegand.getCode();
    String readWiegandStr = String(readWiegand, 0);
    String httpGet = "GET /verify.php?code=" + readWiegandStr;

    Serial.printf("\n[Connecting to %s ... ", host);

    if (client.connect(host, 80)) {
      Serial.println("connected]");
      Serial.println("[Sending a request]");
      client.print(httpGet + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" +
                   "Connection: close\r\n" +
                   "\r\n"
                  );
    }

    Serial.println("[Response:]");

    while(client.connected() || client.available()) {
      if(client.available()) {
        String line = client.readStringUntil('\n');
        Serial.println(line);
        if(line == "ACCEPT") {
          Serial.println("Code accepted");
        } else if (line == "DECLINE") {
          Serial.println("Code declined");
        }
      }
    }
    client.stop();
    Serial.println("\n[Disconnected]");
  }


texts: I need 70 or more input pins for the Arduino -how to do this?

texts:
I have some SN74HC165N, CD4021B chips. How many (minimally) such ICs would I need to get 70 inputs to an Arduino Uno? What is the exact circuit diagram and the code? Im not sure how the wring cascades into each of the chips to make it grow to over 70 inputs, or what the code is for the 70 input circuit. I do understand how to use one of those ICs though. My second easier question is -is there an development board with 70 or more inputs?

CD4021B,SN74HC165N are the chips, you know the ones, that has a parallel input pins that are listened to by latch pin, and the clock pins such outputs the parallel data into the serial data-so I am interested with solution with this pin because I know how it works.

It is for sure 70 pins that are required -not any less-I am sure of that. Because the inputs cannot be further simplified to less than 70. The reason the inputs are 70 is because the algorithm used has 70 free variables in it. Hence by definition it uses 70 or more variables. The input for each of the 70 inputs can be a digital high or a digital low but this is not known before hand. So it cant be simplified because it like saying you can simplfy the information from 70 or more sensors at runtime, and each sensor has an unpredictable value. Anyway this explanation is moving away from the point of my question. I just want to know the circuit that does 70 inputs or more using the mentioned IC-I can live with that answer even if its not the most efficient.


texts: Can adjustable constant current/voltage source be made with Arduino?

texts:
I would like to create a 18650 battery automatic management system that can handle and restore used up cells using solar panels for power. To do that I need to create adjustable constant current source that will limit the current/voltage going into the cell/cells to a small enough value.

Since there are more features I would like to implement (like checking cell capacity) I would love to use Arduino with least amount of components as possible to keep the cost down.

My first question is: Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

The pseudocode for logic I'm proposing is simpe:

Use ADC to check voltage on the capacitor (or a very small value power resistor when working as current source)
Calculate required voltage adjustment
Use AnalogWrite to set new PWM value into internal PWM controller.

Second question: PWM causes a lot of "switching" in the MOSFET. When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss? Since the batteries have some internal resistance voltage variation of +-20% should be acceptable.


texts: YL-38 output to NodeMCU v1.0 analog input

texts:
Using a YL-38 and NodeMCU v1.0 I am trying to achieve what the first link is doing, take a soil moisture reading. I've done this on an arduino, but the conversion from an arduino nano to a nodemcu is proving difficult.

To my understanding, the nodemcu A0 pin operates from 0v-3.3v but the YL-38 analog output operates from 0-4.1v. So first off, is my understanding correct?

I struggle with hardware, so looking around I found these resources:

How to set up a simple level shifter: this setup seemed pretty much like what i wanted, but the 5v input was off

This thread was verbatim what I wanted but I am terrible with circuit math, so I couldn't solve or understand the provided formulas.

Attempt 0: Initially had sensor analog out connected to a0 on nodemcu. Saturated or dry the mcu read 1023. Thought this must be because the signal out is above the A0 mapping range.

Attempt 1: I figured I'd try out the level shifter. Wired it all up as indicated. Now my readings were 760 saturated and 765 dry.

runHygrometer(index);
delay(2000); //allow hygrometer to wake up
reading = (DEBUG) ? analogRead(HYGROMETER_READ_PIN) : 1023 - analogRead(HYGROMETER_READ_PIN);

As shown, my code does no scaling, It's a direct read (DEBUG is true here). So what gives? When using an arduino the range of readings was typically from 20 dry to 180 saturated (DEBUG false, so raw 1003 dry and 843 saturated)


texts: Checking if Arduino board works or is damaged

texts:
I have an Arduino Uno and Mega, but when I connect them to a computer with the USB they came with, there is no green light near the reset button that illuminates.
On the Uno board the pin 13 continuously flashes with red light while on the Mega board the R17 and R18 both illuminate red light but no flashing.
How do I know if the boards work or are damaged?


texts:
I am trying to use esp8266 version of SoftwareSerial,  espsoftwareserial, on an esp-12f.

If I initialize an object using:

SoftwareSerial gpsSer(14,12, false, 256);

or

SoftwareSerial gpsSer(12,14, false, 256)

then gpsSer.write works in all both cases, using ports 12 and 14 for transmit appropriately,  but gps.read fails.

I would be grateful for any advice.

Paul


texts: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function

texts:
This question comes on the heels of this question
In the last question I learned how to use an initializer list to solve my issue, but working with ros::Subscriber is requiring a different solution.
I'm dealing with a callback in this scenario. If I leave the callback as a standalone function then the program runs but I have no access to class members and methods inside the function which defeats the purpose. Here is my standalone callback:
void setPRYCallback( const std_msgs::Empty& toggle_msg) {}

Once I move this into my class is when I encounter the error.
steps to implementing into class
// add member variable for callback
protected:
  void setPRYCallback( const std_msgs::Empty& );

...

// ass method
void ROSController::setPRYCallback( const std_msgs::Empty& toggle_msg) {}

...

// set initializer list
ROSController::ROSController() : sub("setPRY", &setPRYCallback )

How do I thwart this error while keeping my callback as a class method?
Program with Standalone Function Callback (program runs)
#include <ros.h> // https://github.com/ros-drivers/rosserial/blob/jade-devel/rosserial_arduino/src/ros_lib/ros.h
#include <std_msgs/Empty.h>

class ROSController {
  protected:
    ros::Subscriber<std_msgs::Empty> sub;
    ros::NodeHandle _nh;
  public:
    void loop();
    ROSController();
};

void setPRYCallback( const std_msgs::Empty& toggle_msg) {}

ROSController::ROSController()  {
  this->_nh.initNode();
  this->_nh.subscribe(sub);
}

void ROSController::loop() {
  this->_nh.spinOnce();
  delay(1000);
}

Program with Method Callback (program fails)
#include <ros.h> // https://github.com/ros-drivers/rosserial/blob/jade-devel/rosserial_arduino/src/ros_lib/ros.h
#include <std_msgs/Empty.h>

class ROSController {
  protected:
    ros::Subscriber<std_msgs::Empty> sub;
    ros::NodeHandle _nh;
    void setPRYCallback( const std_msgs::Empty& );
  public:
    void loop();
    ROSController();
};

void ROSController::setPRYCallback( const std_msgs::Empty& toggle_msg) {}

ROSController::ROSController() : sub("setPRY", &setPRYCallback )  {
  this->_nh.initNode();
  this->_nh.subscribe(sub);
}

void ROSController::loop() {
  this->_nh.spinOnce();
  delay(1000);
}

arduino mega


texts: How to user timer interrupts for times longer than can TNCTx can keep track of?

texts:
I am trying to program my Arduino Mega 2560 to effectively create a PWM signal on any digital pin using timer interrupts and timer1. The pins will pulse a finite amount of times (not indefinitely). I am first trying this with a 256-prescaler value, which I believe means that each increment of my TCNT1 is 16.0 microseconds, and since it is a 16-bit register, it can reach a max. value of 1048567 microseconds.

I am designing the program so that the period and duty cycle are changed by Serial commands that the user can send (I already have that part figured out). I am using clear timer on compare mode and OCR1A and OCR1B to toggle the digital pin between HIGH and LOW.

If the desired period is less than 1048567 microseconds, I can divide the period by the modified clock (modified by the prescaler) to figure out the OCR1A value, and then based on the desired duty cycle, calculate OCR1B. Then I set the ISR vectors for A and B to toggle the pin and count down until the desired number of cycles is completed.

What I would like to also allow the user to do is set periods/duty cycles that would be longer than 1048567 microseconds, but I'm not sure how to accomplish that. For example, if I wanted to have the pin be HIGH for 2 seconds with a total period of 10 seconds, I would choose values for OCR1B and OCR1A that, through the ISR(TIMER1_COMPA_vect) and ISR(TIMER1_COMPB_vect), I could keep track (through a counter variable) of how many interrupts had occurred. If enough interrupts had occurred to equal the time of that the pin had to be HIGH and/or LOW, the ISRs would actually trigger the toggling of the pin (instead of just counting the number of interrupts).

How could I choose the OCR1B and OCR1A values that would accomplish this optimally? Is it reasonable to keep track of time this way as a workaround to the limitation of the timer counter max value? I am open to any suggestion and I appreciate any input. Thank you.


texts: Measure revolutions per second with reed switch

texts:
I'm trying to measure speed of a fly wheel with a reed switch with one magnet (1 pulse per full rotation). I have an 100nf cap connected to switch to help with debounce.

#include <Arduino.h>

int speedPin = 2; // switch is connected to pin 2
int ledPin = 13;

int debounceTime = 7;

long speedPulseTime = 0;
int speedPulseCount = 0;
int speed = 0;
long speedLastSample = 0;

long serialLastReport = 0;
int serialReportFreq = 40;

void speedPulse()
{
  long time = millis();
  if ((speedPulseTime + debounceTime) < time)
  {
    speedPulseCount++;
    speedPulseTime = time;
  }
}

void setup()
{
  pinMode(ledPin, OUTPUT);

  pinMode(speedPin, INPUT_PULLUP);     // Set the switch pin as input
  attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);

  Serial.begin(115200);
  Serial.println("Ready...");
}

void loop()
{
  long time = micros();
  if (speedPulseCount >= 4 || (speedLastSample + 1500000) < time)
  {
    detachInterrupt(speedPin);
    int tempSpeed = 1000000 / ((time - speedLastSample) / speedPulseCount);
    if (tempSpeed < 0)
    {
      speed = 0;
    }
    else
    {
      speed = tempSpeed;
    }

    //reset sample
    speedLastSample = time;
    speedPulseCount = 0;
    attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);
  }

  if ((serialLastReport + serialReportFreq) < millis())
  {
    Serial.print(millis());
    Serial.print(",");
    Serial.println(speed);
    serialLastReport = millis();
  }
}

Here the code I have so far. The problem I have it jumps around a little bit. What could I change to ensure more accurate readings?


texts: Multiple transmitters and problem with ref

texts:
There are three Arduinos on a model. Each of them has a DS18B20 Dallas temperature sensor and an nRF24L01 antenna wireless communication. There is also an independent device consisting of an Arduino and an nRF24L01 antenna. Device acts as a receiver. Arduino and antenna play the role of transmitter. The code is:

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

int temp1;
int WindSpeed;
int temp2;
int temp3;
RF24 radio(7, 8);
const uint64_t pipes[3] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL};
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(0, pipes[1]);
  radio.openReadingPipe(1, pipes[2]);
  radio.openReadingPipe(2, pipes[3]);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&temp1, sizeof(temp1));
     Serial.println("Temp1:");
     Serial.println(temp1);
     delay(50);
     radio.read(&WindSpeed, sizeof(WindSpeed));
     Serial.println(" WindSpeed Bf : ");
     Serial.println(WindSpeed);
     delay(50);
     radio.read(&temp2, sizeof(temp2));
     Serial.println("temp2:");
     Serial.println(temp2);
     delay(50);
     radio.read(&temp3, sizeof(temp3));
     Serial.println("temp3:");
     Serial.println(temp3);
     delay(50);
  } else {
    Serial.println("No radio Data avaliable");
  }
  delay(3000);
}

The problem is that the code sends some values but the correspondence isn't right in AnalogRead. How can I watch each pipe with the antenna of corresponding Arduino in order to have the right results, and each Arduino sends to the receiver through its own antenna the value of its sensor?

Thanks all for your time!


texts:
I found some code that works to transmit the required signal to an RX-2B RC receiver, the code works great from my Uno but when I tried to run it from my Yún nothing happens.

The code has definitely uploaded as I tested with an LED and the pin is getting a HIGH voltage written to it.

Does anyone have any idea what the issue might be? Code below.

Thanks.

/**
* Control Realtek RX2 (RX2 -G) RC Receiver with Arduino
*
* @author Mircea Diaconescu, Octomber 28, 2013
* @source https://github.com/dimircea/
* GPL v3 License
*
 * Many cheap RC toys are based on TX2 / RX2 transmitter / receiver ICs.
 * This Arduino sketch allows to replace the TX2 based Remote Control with Arduino.
 * Just one single pin is used from the Arduino board.
 *
 * Connect Arduino pin 10 to the solder point where the toy antenna is connected or         to the toy antenna cable.
 * One can replace pin 10 with other free digital pin available on the Arduino board.
     *
 * TX-2B/RX-2B datasheet: http://www.datasheetarchive.com/dl/Datasheet-    035/DSA0017137.pdf
 */

/** Functions (aka W1) - as defined by the IC datasheet */
#define COMMAND_ENDCODE         4
#define COMMAND_FORWARD        10
#define COMMAND_FORWARD_TURBO  16
#define COMMAND_TURBO          22
#define COMMAND_FORWARD_LEFT   28
#define COMMAND_FORWARD_RIGHT  34
#define COMMAND_BACKWARD       40
#define COMMAND_BACKWARD_RIGHT 46
#define COMMAND_BACKWARD_LEFT  52
#define COMMAND_LEFT           58
#define COMMAND_RIGHT          64

//output pins
#define ANTENNA_PIN 9

/** Initialize the Arduino data and pin */
void setup() {
 pinMode( ANTENNA_PIN, OUTPUT);
}

/** Loop code */
void loop() {
 // add here your commands to control the RX2 module...
 // for test purposes, here a continuous forward command is sent

 sendCommand( COMMAND_FORWARD);

}

/** Send command to the RX2 IC */
void sendCommand( int command) {
 int w1 = 0, w2 = 0;

 /** start code sequence 4 x W2, ~625Hz, Duty Cycle 75% */
 for ( w2 = 0; w2 < 4; w2++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 1200);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
  }

 /** function code sequence, n x W1, ~1.25KHz, Duty Cycle 50% */
 for ( w1 = 0; w1 < command; w1++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 400);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
 }
}


texts: Why is the result of this product operation wrong?

texts:
I had a problem in a program where the result of product is not what it's supposed to be. For example: 775*775 gives 10801 instead of 6006025.

To try to isolate and resolve the problem, I made a simple sketch to test the result of different products. What I found is that if I do the same product in this way: 775/100.00*775/100.00 then multiply the result by 10000 I get the right value: 600625.00

The attached pictures illustrate what I said.

While I can use this solution in my initial program by I still want to do the multiplication directly as more operations means more time.

I would appreciate any help. Thank you.


texts: Looking at Adafruit's website I'm confused which wallcharger I should get

texts:
As the title says there are many different wall chargers to choose from.

12v, 9v, 5v, with different mA amounts...

The starter kit on Adafruit's website mentions to get the 9V 1000mA switching power adapter, so I'm curious if that's what we should get?

here is the link to all of them.

There are regular wall adapters, and these big power supplies...

http://www.adafruit.com/search?q=switching+power+adapter&b=1

I'm just looking to run some LED Strip lights from the arduino and power some joystick buttons, some rotary encoder/knobs, and a keypad to work the LED lights

Thoughts?

Thanks!


texts:
We know watchdog timer if enabled RESETs when Arduino is locked up somewhere inside the code. As the title suggests has anyone experienced this unless they put deliberately a while(1) loop inside the code? Of course, buffer overflow or memory related issues are excluded.

I mean is it worth in Arduino to use watchdog and RESET rather than to fix the code to not get locked up. Are there still some behavior which are not predictable here?


texts: Arduino Leonardo - Using ICSP pins for serial

texts: I'd like to know if it's possible to use the ICSP header pins on the Leonardo as GPIO pins, for example for software serial, and how to address them. I've a project which needs all available I/O pins, and I could use having serial comms on those "extra" pins.


texts: Simplest/best way to control a set of 8-10 PWM signals from a smartphone

texts:
As part of a larger project, I would like to be able to control a set of 8-10 PWM signals remotely, from a smartphone at a distance of 10 meters or more.  I will probably convert the PWM signals to analog voltages, and reduce their voltage swings to more like 0-1v, using a resistor divider and RC filter; they will drive high impedance loads in the remainder of the project.  I’d write an app for the smartphone allowing user control over the duty-cycle of each PWM signal (and thus the analog signal levels).

It seems to me that the way to go is Arduino, interfaced to the phone with Bluetooth.  I'd need one of the higher end Arduinos to get enough PWM signals (the basic ones like Uno only have 6 PWM outputs).  Software-generated PWMs are probably not high-frequency enough, as I’d like the filtered analog signals to be as ripple-free as possible. There seem to be several ways to interface Bluetooth to Arduino, such as the HC-05.

If people here concur with this approach, I shall move this question to the Arduino forum.

`


texts: Controlling ceiling fan speed using Arduino

texts:
Reference: https://arduino.stackexchange.com/a/12000/37585

Based on this post, if I want to control a 120V AC ceiling fan with an Arduino, there's a complicated bit of electronics that needs to be put in place.

There are only 3 wires that go to the ceiling fan itself, load, neutral, and ground. Hooking up a relay in the middle of the connection allows me to turn on and off the fan; cutting the power. This does not allow me to change the fan's speed.

There's a pull-switch inside any 3-speed ceiling fan that lets you alter the speed. Whatever this is doing, it should be able to be replicated. The question is, does it require a 4-channel relay and some extra electronics or does it require converting the 3.3V GPIO to 120V and enabling AC-style PWM? Or is it something completely different?


texts: Why it's not possible to manipulate the TWSR directly?

texts:
I think I forgot the reason for this SFR manipulation in microcontrollers; like, checking the TWSR in twi.

The technique for checking the values of the TWSR is by masking it with another variable or a value.

So, why not checking the TWSR directly in; for example, switch function for checking the values of TWSR?

Like, switch (TWSR)

instead of

uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)

Or, substitute it in any function; like, Serial.println(TWSR); or digitalRead(TWSR);. DO I have to mask it? If so then why?


texts: How to connect Android phone to Arduino?

texts:
Is it possible to connect an Arduino to an Android Phone and use it for input/output?
Are connections possible over USB? Or do I need to have a wifi or Bluetooth shield?


texts: Programming ATmega2560 processor with FTDI instead of ATmega32

texts:
Has anyone tried to program an ATmega2560 with an FTDI chip as is done in the Arduino Nano (this is for a custom design).

Will it work?


texts: eps32 bad adc even with external adc (ADS1115)

texts:
Im trying to read an analog value with my esp32 and send it over wifi to another esp32. The wifi part works flawless, however when i try to read an analog value form the esp32 its not useable. It jumps around +-100 on range 0-2000. Now i tried to use an external adc, because i heard that some have problems using the internal one with wifi. However i connected it via pins 21 and 22 (SDA Scl) and i have the same problem.

Internet couldnt help me at all, i hope you guys can.

Br
Felix


texts: Replicate output of pwm pin on another output pin?

texts:
Ardiuno Mega 2560

I have a legacy PCB that connects PORTA, pins = {22, 23, 24, 25, 26, 27, 28, 29} to the PWM input of a set of actuators. The accompanying code made use of an interupt service routine to generate PWM signals. This in turn caused all sorts of other problems for the system.

So, I would like to leverage the Mega's internal counters & use the PWM available on pins = {2, 3, 4, 5, 6, 7, 8, 9} & use the analogWrite() function. At present there is nothing else connected to these pins but access is limited.

Before I go down the route of redesigning the PCB I was wondering if it was possible to replicate the outputs of pins {2, 3, 4, 5, 6, 7, 8, 9} to pins {22, 23, 24, 25, 26, 27, 28, 29}?


texts:
Should this code pulse the PB3 and PB4 pins (MOSI and MISO of an Arduino Uno) at 2ms interval ?

#include <avr/io.h>

int main(void)
{

//  for (byte i = 0; i < 32; i++)
//    pinMode(i, INPUT);

  DDRB |= (1 << PB4);
  DDRB |= (1 << PB3);
//  pinMode(PB4, OUTPUT);
  while (1)
  {
    PORTB &= ~(1 << PB4);
    PORTB &= ~(1 << PB3);
  //  digitalWrite(PB4, LOW);
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//    delayMicroseconds(10000);
    delay(1);
    PORTB |= (1 << PB4);
    PORTB |= (1 << PB3);
  //  digitalWrite(PB4, LOW);
//    delayMicroseconds(10000);
    delay(1);

  }
}

If used for SPI MOSI can do 1 MHz just fine - so my logic analyzer says. MISO would not behave when used by SPI. MISO works in other non-SPI scenario: I am able to use the Arduino for in-system programming other AVR boards.

But the code above pulses neither MISO nor MOSI, as pointed out by the same logic analyzer in the same setup. Should it?

update

There has been some issue with the board. Changed it and all works fine now, regardless of using int main() alone or also calling init() as per @Majenko 's answer


texts: Configure input pullup through registers

texts: I can set pin mode to input or output through the DDRx registers. How can I enable the internal pullup resister through a register?


texts: How to use a variable format in `sprintf`

texts:
How should I make a variable format sequence for sprintf?.

int i=2,d=9;
String sf;
sprintf(sf,"%%0%d",i);
fprintf(sf,d);

While expecting the output.

09

The compilation fails, with several errors, according the failing change I apply.

Invalid cast from type 'String' to type 'char*'


texts: Is there a real alternative now to using GSM for data sending?

texts:
I would like to create an Arduino system that sends the temperature in a place outdoors to a server.

I've read in Internet forums that there might be alternatives to GSM and GPRS technology for sending data remotely, but I'm not sure about them. In absence of WiFi, is GSM the best technology today, even that you have to use the SIM plan to use it?


texts:
Does anyone know if there is a way to create a queue of some sort for arduino?

My project consists of simulating multiple traffic lights with crossing pedestrians on an Arduino breadboard. Since I need to assume the situation where on all sides are cars waiting + pedestrians having pressed the button, I needed to figure out a way to store these inputs into an array of some sort.

However, the problem with array I believe is that it doesn't allow me to shift the data to the left, so that the next one will be selected in the queue. Deleting the data inside an array would only merely make it null, which doesn't work.

Greatly appreciated if someone can help me by pointing to the right direction.


texts:
I have the following screen:

I want to connect it to a NodeMCU device:

I read somewhere that it is not possible. However, I am not interested in the touch ability nor the SD card. I just want to draw something on the screen.

Is it possible to make the connection in somehow?


texts: Am I maximising my A0 readout rate with this peak-detection code?

texts:
I have a pulse going into A0 on a Nano, and want to detect the peak voltage.  With low-pass filtering to slow down the input pulse I'm still reading marginally too slow.
The code overall inhibits a laser except for 50ms after a button is pressed.  During that 50ms I read A0 to look for the peak voltage/laser pulse energy.  The pulse is negative, several volts, and is AC-coupled into A0, pulled up to a 5V baseline.
The monitoring loop is simple:
while (millis() < (PulseStart + LaserPulseWidth)) { // monitor ADC (PbSe amplified photodiode with negative output, AC coupled and pulled up
  if (V_in <= V_old) {
    V_old = V_in;
  } // this will report the minimum voltage seen on the monitor pin.  Should be near enough proportional to the pulse energy.
  V_in = analogRead(MonitorPin);
}

Outside the monitoring loop, but in the main loop, I toggle various status LEDs etc.  The resulting laser pulse energy is sent using softwareSerial to (a Raspberry Pi in) the box with the trigger button, about 12m away. softwareSerial requires interrupts, but anyway so does millis()

Channel 1 (yellow) is measured at A0.  Channel 2 is the unfiltered output from the PbSe amplified IR photodiode, and is used to trigger the scope.  Note the timebase is 100us, close to the nominal readout time of A0; I thought this would effectively average over approximately 1 division, which might be OK, but taking some rough calibration data suggests otherwise.
Here's my circuit:

A simplified version of the whole code follows. I've removed some status outputs (LEDs, beeps, USB serial transmssion) from the main loop and the code to set them up; the ADC read-in loop is unmodified from my running code.
#include <SoftwareSerial.h>

int MonitorPin = A0;
int FireButton;
int stopbutton;
int lastFireButton = LOW;
int V_in;
int V_old;
char message[8];
int V_base;
int LaserPulseWidth = 50; //in ms.  50 ms should be right for 20 Hz laser

SoftwareSerial mySerial = SoftwareSerial(2, 3); // RX, TX

void setup() {
  pinMode(pin7, INPUT_PULLUP);  // fire laser
  pinMode(pin8, INPUT_PULLUP);  // disable
  stopbutton = digitalRead(8);
  FireButton = digitalRead(7);
  pinMode(LaserPin, OUTPUT); // Laser trigger pin
  Serial.begin(9600); // for comms to a host PC (includes debug info)
  mySerial.begin(9600); // for comms to RPi
  mySerial.println("Second serial port");
  interrupts();
}

void loop() {
  stopbutton = digitalRead(8);
  FireButton = digitalRead(7);
  while (stopbutton == HIGH) { // not actually used, but implemented in case we want to suppress firing (pin internally pulled up so just ground to suppress)
    lastFireButton = FireButton;
    stopbutton = digitalRead(8);
    FireButton = digitalRead(7);
    V_old = 1024; // initialise to max so anything we read is less

    if (FireButton != lastFireButton && FireButton == LOW) { // detect negative edge
      digitalWrite(13, true); // flash the onboard status LED on
      V_old = 1024;
      for (int i = 0; i < 10; i++) {
        V_in += analogRead(MonitorPin); // read ADC before firing to provide a baseline
      }
      V_base = V_in / 10;
      digitalWrite(LaserPin, true); // laser trigger on
      PulseStart = millis();
      while (millis() < (PulseStart + LaserPulseWidth)) { //monitor ADC (PbSe amplified photodiode with negative output, AC coupled and pulled up
        if (V_in <= V_old) {
          V_old = V_in;
        } // this will report the minimum voltage seen on the monitor pin.  Should be near enough proportional to the pulse energy.
        V_in = analogRead(MonitorPin);
      }
      digitalWrite(LaserPin, false); // laser trigger on

      int V_peak = V_base - V_old;
      sprintf(message, "ADC=%d", V_peak);
      mySerial.println(message);
    }
  }
}


texts: Speaker & Piezo when beeping both cause CapacitiveSense to sense

texts:
I am using this speaker:  CUI part number CSS-I4B20-SMT-TR as an alarm on a clock using atmega328 chip and Arduino IDE with the tone function. Works great.

I am also using Arduino CapacitiveSensor.h library.  Also works great.

Problem:  Want to touch the clock to put it in snooze when the alarm starts.  But when the speaker beeps, the speaker affects the Touch Sensor so it puts itself in snooze after one beep!

EMI is not the issue.  Tested with a second speaker beeping, running from a different Arduino.  Brought speaker close to the Touch Sense circuit and it DID NOT trigger. Can something be added/changed to prevent the beep pulses from affecting the rest of the circuit?

Change Speaker to Piezo Buzzer which does not have a coil.  I thought that was the answer until I read about the Piezo being a risk to the atmega328 from sending  voltage into the circuit and/or possibly drawing too much current.  I would think this could be solved using a resistor, transistor and diode.
This was tried. Piezo in circuit also was sensed when beeping.

Any thoughts would be greatly appreciated, or Options I have not thought of. Thanks.

Update:  Changed to Murata piezo sounder with circuit shown below.  Still triggers Touch Sensor when beeping.

Question:  Is there a circuit change that could reduce the effect of the speaker on the rest of the circuit?


texts:
I have an ic (CT1642 1442) it's a led driver 8 bit, i want to use it with my arduino nano and i don't have any idea how to use it.
If someone can help me ill be thankfull.


texts:
So I've been playing with the esp8266 controller lately and today my Usb Host Mini came in that I wanted to connect. So for this I followed the following tutorial https://www.hackster.io/139994/plug-any-usb-device-on-an-esp8266-e0ca8a

The only thing is that I didn't do the following, because I wanted to see that it actually wouldn't work without damaging the Usb Host Mini.

Now I am wondering, because I didn't do that, and just went on with the wiring, did I actually kill my ESP8266 now? Whenever I remove all the wires, and just connect the ESP8266 to my computer, it just won't show up in the ports.

If I did kill it, what did I actually do here? Did I allow 5V to run through the board and did I fry it that way? If I would've actually made the cut shown above, would it have lived? (Because I think what the cut does, is it stops the 5V from going through the circuit.)


texts:
Yeah yeah, I know people ask this type of thing a lot, but I couldn't find an answer anywhere.

I understand that you can have multiple .ino files in one sketch, but I don't just want functions and variables separated, I want functionality.

I am writing a Braille program for the NodeMCU -- It takes a message from a served website and moves servos to emulate the appropriate Braille. I want to have 2 files: one to serve the website and get input from it (website.ino), and the other one to manipulate the servos(braille.ino). The only problem is, I can't figure out where to declare/attach the servos.

I plan to have a list of servos in braille.ino that will be looped over with each servo being set to a different value. If I declare them  in website.ino (my "main" file, ie, with a setup and loop), I will have to pass them to my braille function every time. On the other hand, if I choose to declare them as globals in my braille.ino, where would I attach them? Can I have another setup in braille.ino?


texts: Interrupt volatile variable doesn't work as expected

texts:
Please examine the following code.

volatile uint8_t myVar;

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), isr, FALLING);
  Serial.begin(115200);
}

void loop() {
  myVar = 0;
  while (myVar != 5) {
  }
  Serial.println("ISR called");
}

void isr() {
  myVar = 5;
}

From this code, I expect that every time the pin 2 is falling, I get one single print statement ISR called.

However, when dropping the voltage on pin 2 ONCE, the serial monitor shows ISR called TWICE.

Why is this? This is a simplified, stripped-down example of the problem I am facing with my current project.

Edit:
After reading the comments, here is a bit more info. I am using a 64-button shield that is triggering the interrupt. The process is time critical since I am measuring the time it takes for the button to be pressed (I am testing people's reflexes). I will add a print statement in the interrupt to see how many times it gets called. However, I believe the interrupt is only getting called once per buttonPressed.

Thank you for your help!


texts: less expensive alternative arduino board to CMUcam4

texts:
Is there any similar (less expensive alternative) arduino board to CMUcam4?

CMUcam4:The CMUcam4 is a fully programmable embedded computer vision sensor. The main processor is the Parallax P8X32A (Propeller Chip) connected to an OmniVision 9665 CMOS camera sensor module.


texts:
I have a silly question that came to my mind
when communicating between HC-05 and A smartphone, the smartphone is considered as the master,
and the HC-05 is considered a slave.
master will send data to the slave and then the slave will send these data to the MCU.
my question here is that, what is the MCU considered if it is not a master or slave?
if I got something wrong, I'll be glad if you correct it for me.
thank you


texts:
I'm trying to make a speedometer, with utilization of interrupt for get number of pulse and some calculation for getting speed, but when compute speed the arduino freeze for some second and i lose alot of impulse and false all my successive capture of impulse. Why? thanks for reply

const int contaImpulsi = 2;
volatile int impulsi =  0;
int impulsiOld = 0;
static int appoggio = 0;
unsigned deltaT[3];
unsigned vel = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(contaImpulsi, definisciTempi, RISING);
}

void loop() {

  if (impulsiOld == impulsi || impulsi > impulsiOld)
  {
    if (appoggio == 3) {
      deltaT[3] = millis();
      appoggio = 0;
    }
    if (appoggio == 2) {
      //Serial.println("ASSEGNO DELTA T 2");
      deltaT[2] = millis();
      //Serial.println(deltaT[2]);
      appoggio = 3;
    }
    if (appoggio == 1) {
      //Serial.println("ASSEGNO DELTA T 1");
      deltaT[1] = millis();
      appoggio = 2;
    }
    if (appoggio == 0) {
      //Serial.println("ASSEGNO DELTA T 0");
      deltaT[0] = millis();
      appoggio = 1;
    }
  }
  impulsiOld = impulsi;

  if (appoggio == 3) {

    int t1 = (deltaT[1] - deltaT[0]);
    int t2 = (deltaT[2] - deltaT[1]);
    int dividi = t1 + t2;
    vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85; // here i think is where the program freeze

    Serial.println("------------------------------------------");
    Serial.print("SPEED: ");
    Serial.println(vel);
    Serial.println("------------------------------------------");
  }
}

void definisciTempi() {
  impulsi++;
}


texts: Washing machine controlled by Arduino for homebrewing

texts:
So, this question might sound a bit silly at first glance (no, I know, it sounds flat out insane), but not all that silly at second.

I have heard once about a guy who transformed some (presumably old-ish) washing machine into his own personal home-brewing apparatus. It is quite some idea if you think about it. Washing machine can easily solve most issues people have with homebrewing. It can carefully control and adjust temperature throughout the long and complicated process of brewing, it can stir, it can pump in fresh water.

Main question is, how to control washing machine to do what I want it to do.  Most automatic washing machines already have some controllers, but I don't see much chance in trying to simply reprogram them (Am I wrong?). Arduino seems like best choice for its simplicity and expandability. However I am still fairly new to Arduino and have trouble imagining how would connecting everything from washing machine (motor, pump, maybe water and temperature sensors) to Arduino actually look like.

So is it even possible? Are there any projects to "bounce of"? (I couldn't find any, but maybe I looked for wrong projects) Should I expect any major problems?


texts:
I receive strings over the serial port like so:

VLT=53.0, AMP=-30.2, AHR=-10, SOC=98, TMP=136, STS=192

I want to reduce the use of string functions with the idea of dropping all non-digits, keeping numbers dot and comma, to get this:

53.0,-30.2,-10,98,136,192

in an array and simple read [0], [1], etc.

Regular expressions would be idea, but do not exist like in PERL.
Any hint would be much appreciated.

Relevant code used:

    char inByte = SerialPortOne.read(); // read byte
    strRecordIn.concat(inByte);         // add byte to receive buffer
    for (int i = 0; i <= 3; i++) {    // VLT, AMP, AHR, SOC
    strWord = getValue(strRecordIn, ',', i);  // get data item from RecordIn array
      strWord.remove(0, 4);           // remove field identifier (1st 3 char plus =)
      strRecordOut += ',';            // add delimiter
      strRecordOut += strWord;        // add value
      strWord = "";                   // reset strWord
    }

Ideally:

    char inByte = SerialPortOne.read(); // read byte
    if (inByte = [%d.,]+) {
      strRecordIn.concat(inByte);       // add byte to receive buffer
    }


texts: Output of mlx90614 to mcufriend tft/lcd, not getting displayed

texts:
Newbie here !! Im trying to display the output of my MLX90614 sensor on mcufriend tft display (with arduino UNO). But unable to do so. I can only see the TFT being lit to white color, text -> "Target" flashes on screen for millisecond and then again white lit screen.

But I tried tft-lcd sample codes, which are working fine &
I also tried mlx90614 (mlxtext code), which is also working fine.

But I combined the two codes so as to output it on TFT, which doesnt work. Hence I think this code might have some issue.
Im a beginner pls help!!

#include <Adafruit_TFTLCD.h>
#include <Adafruit_GFX.h>
#include <TouchScreen.h>
#include <Wire.h>
#include <Adafruit_MLX90614.h>

#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
#define LCD_RESET A4

#define BLACK   0x0000
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
Adafruit_MLX90614 mlx = Adafruit_MLX90614();

boolean buttonEnabled = true;

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

  mlx.begin();
  tft.reset();
  uint16_t identifier = tft.readID();
  tft.begin(identifier);
  tft.setRotation(1);
  tft.fillScreen(WHITE);
  tft.drawRect(0,0,319,240,YELLOW);

}

void loop() {

  tft.setCursor(0,1);
  tft.setTextSize(2);
  tft.print("Target  ");
  tft.setTextColor(BLACK);
  tft.print(mlx.readObjectTempC());
  tft.print(" C");
  Serial.print("*C\tObject = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");
  Serial.println();
  delay(500);

}


texts: Upload with esptool fails with "espcomm_send_command: can't receive slip payload data"

texts:
Uploading a sketch to an ESP8266 board fails with:

error: failed reading byte
warning: espcomm_send_command: can't receive slip payload data
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

...or:

espcomm cmd: receiving 2 bytes of data
warning: espcomm cmd: no final C0
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

This is on OS X with a PL2303HXD USB-to-Serial cable, using the latest official Prolific signed OS X El Capitan-compatible drivers.


texts:
I'm hoping to construct a feedback loop for a laser using an Chipkit UC32 and an analog-digitial converter ( the one of I have is an AD5780 evaluation board). I've been reading through Digilint's  SPI library but I admit I am pretty lost.

( I believe this is on topic to Arduino because I am using an Arduino API. The micro-controller I use is basically an Arduino so I see no difference. )

I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?

Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?


texts: Why connect a diode between the reset pin of Arduino and 555 timer?

texts:
I am trying to create a watchdog timer using 555 IC and I am following this.

I do not understand why a 1N4148 diode is connected between the reset pin of Arduino and the output of the 555 timer.

As far as I understand, the reset pin of the Arduino should be high, and when it is pulled low, the Arduino resets. But why should we add a diode over here? What purpose does it serve?


texts: ESP32: How to run two independent PID controllers, one per core?

texts: I want to control 2 independent processes with 2 PID controllers. Is it possible to run each controller on a separate core? I'm using this PID library. According to its documentation, the PID::Compute() function should be called once every loop(). How can this be achieved when using RTOS tasks (for multi core execution)?


texts:
i'd like to have a esp-01 powered on and controlled with a push button only.
so imagine the device is off, the user press the momentary push button. in the setup the esp8266 turn on a mosfet or something similar to give himself power using another line. the user release the button and the device is on. i want to be able to understand long button press and double press and similar stuff too. even when device is already powered on. so i need to have a pin attached to the button somehow
this is what i have till now, thanks to a very skillfull friend of mine

the vcc is 5 v and pin tollerance is only 3v

it must be completely off when not pressed for long battery duration


texts: ESP8266 NodeMCU CP2102 ESP-12E I2C with MPU 6050 Error

texts:
So the previous two questions could be found here:
ESP8266 computtion error and ESP8266 not working with MPU 6050 over wire library and I2C

However, it was not resolved, and with updates and debugs, I'm going to delete them later and summarize in this single post.

Issue:

An ESP8266  CP2102 ESP-12E was trying to access MPU 6050. However, it's not working.

Attempts:

You can see the diagram picture. I tried pairs of pull up resistor from 0 to 100 k(the one used in the picture was standard 4.7 k).
Many MPU 6050s have been attempted and tested. They were working, and you can see in the picture, the green light lighted up.
Different ESP 8266 -12E from two different brands have been attempted, both have the same issue.
Various of version of board manager has also been attempted.
Different wires have been attempted. The I2C bus in the graph are twisted wires.
The adjustment of the program has also been attempted. Eventually, an online version of code  was attempted, and not working.
The power supply was ruled out through the usage of power board, capacitors, and external power sources. The issue persisted.
Wire library pins, frequencies, have been checked as correct. As well as constant restart of IDE and hardware.
Different bread boards and have also been attempted, the issue persisted.

The above attempts all resulted failure. Could you help me to figure out why ESP 8266 does not work with MPU 6050 over I2C?


texts: How to control 6 servo motors with an Arduino Mega board?

texts:
I am trying to make autonomous hexapod with an Arduino Mega board. I have followed tripod mechanism of hexapod movement. First I could control simultaneously legs (0, 2, 4) and (1, 3, 5) separately but whenever I tried to combine both i.e control 6 legs at a time I could not see any movement in the hexapod. Even in the IDE I am not getting any error.

I have connected the legs (0 to 5) to signal pins (2 to 7) respectively. I have connected a common +5v voltage and common ground voltage to individual legs using a breadboard. Can anyone give me a proper solution to overcome this issue and further would like to know how to control multiple servos and source code for it?

Here is my Arduino source code for controlling 6 servo motors.

#include <Servo.h>
Servo myservo[6];
int f=0;// create servo object to control a servo
//[0] -tibia , [1] -femur , [2] -coxa motors
void setup() {
  myservo[0].attach(2);
  myservo[1].attach(3);
  myservo[2].attach(4);
  myservo[3].attach(5);
  myservo[4].attach(6);
  myservo[5].attach(7);
}

void loop() {
  //alternatively making hexapod stand at its place
  //f is just flag variable to make it stop
  if(f==0) {
    myservo[0].write(130);
    myservo[2].write(130);
    myservo[4].write(90);
    myservo[1].write(130);
    myservo[3].write(90);
    myservo[5].write(0);
    f=1;
  }
}

Note the values that are added above are calculated separately for individual legs to mount legs on ground.


texts:
newbie here. So I've been trying to upload StandardFirmataPlus into my Arduino Nano 33 IoT so that I can program in Johnny-Five. However I have this issue.

I've checked that my port is connected and that the libraries are up to date. The docs say that if my board does not enough flash or RAM then the code wouldn't work. The code seems to work fine on other boards which have the same memory such as the Arduino UNO. My board is not a clone. And I've also checked that my Board Manager is set to "SAMD". If anyone has faced this issue and resolved, do share how you did it. Thanks in advance. If I've mentioned anything wrong do correct me =).
EDIT 1: I'm using macOS Catalina 10.15.5. Arduino version 1.8.13. All I did was to try compiling the code. This is the Arduino IDE.
EDIT 2: Error Messages:
In file included from /Users/thebird/Desktop/Code/Arduino1/libraries/Firmata/Firmata.h:17:0,
from /Users/thebird/Desktop/Code/Arduino1/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino:49:
/Users/thebird/Desktop/Code/Arduino1/libraries/Firmata/Boards.h:824:2: error: #error "Please edit Boards.h with a hardware abstraction for this board"
#error "Please edit Boards.h with a hardware abstraction for this board"
^~~~~
Multiple libraries were found for "Firmata.h"
Used: /Users/thebird/Desktop/Code/Arduino1/libraries/Firmata
Not used: /private/var/folders/kx/l1lw7kfn0t387jt7bd3ccg3h0000gn/T/AppTranslocation/D1572E71-F02B-4F61-BAF9-E73A3ABEB39A/d/Arduino.app/Contents/Java/libraries/Firmata
exit status 1
Error compiling for board Arduino NANO 33 IoT.


texts:
I'm setting up a grid of 200+ slave modules which will be about 12 inches apart and the master will be anywhere from 5 to 10 meters away from the closest module. Each slave module will have a ATtiny85 to manage the sensor reading, LEDs and the network protocol.

The communication packets will be small and will probably be at 115200 baud if using ATTiny85's TTL serial or 1MHz if using SPI. In either case, the modules will be connected in a daisy chain to each other.

Each module will have a resistive touch sensor and be driving about 12 - 16 RGB LEDs (I'm making a step responsive disco dance floor). There will be 12v+ running to each module to drive the LEDs and regulated down to 5V for the ATtiny.

Which brings me to my question. With these constraints, do you think the ATtiny85's built-in serial or SPI would still work well over the 5 to 10 meters from the closest module to the master.

I know some people push towards RS422 or RS485 transceivers for distance applications, but I'd like to keep the total part count down, if possible.


texts: How to on/off light dimmer using another pin?

texts:
In recent project, I'm working with light dimmer.

Let me explain with example of fan. In switch board, we have a fan switch which can able to ON/OFF our fan & FAN REGULATOR which vary speed of our fan. Now, when our switch ON then our fan start and then with help of regulator we can vary speed of fan. And when we switch OFF then our fan stop and we can't do anything means not vary fan speed. Same things I want in my light dimmer. One push button pressed once then it's just start my light dimmer and vise versa operation. And When push button pressed again then it's just stop my light dimmer.

Here is my full code.

int kPinPWM = 9; // This pin provides PWM values

int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

int i = 0;

int temp = 0; // Flag

void setup()
{
  pinMode(kPinPWM, OUTPUT);

  pinMode(kPinSW1, INPUT);
  pinMode(kPinSW2, INPUT);

  digitalWrite(kPinSW1, HIGH);
  digitalWrite(kPinSW2, HIGH);

  pinMode(kPinSw, INPUT);

  digitalWrite(kPinSw, HIGH);
}

void loop()
{
  if(digitalRead(kPinSw) == LOW && temp == 0) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 0
  {
    temp = 1; // Change value to 1 // temp = 1

    digitalWrite(kPinPWM, HIGH); // Turn ON PWM pin (PIN 9)

    if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
    {
      i++;

      if(i > 4)
      {
        i = 4;
      }

      while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON pressed
    }

    if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
    {
      i--;

      if(i < 0)
      {
        i = 0;
      }

      while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
    }

    switch (i)
    {
      case 0:
              analogWrite(kPinPWM, 0); // When Button pressed not pressed send 0 value
      break;

      case 1:
              analogWrite(kPinPWM, 64); // When Button pressed and i = 1 send 64 value
      break;

      case 2:
              analogWrite(kPinPWM, 128); // When Button pressed and i = 2 send 128 value
      break;

      case 3:
             analogWrite(kPinPWM, 192); // When Button pressed and i = 3 send 192 value
      break;

      case 4:
             analogWrite(kPinPWM, 255); // When Button pressed and i = 4 send 255 value
      break;
    }
  }

  if(digitalRead(kPinSw) == LOW && temp == 1) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 1
  {
    temp = 0; // Change value to 0 // temp = 0

    digitalWrite(kPinPWM, LOW); Turn OFF PWM pin (PIN 9)
  }
}


texts:
I am working on connecting two Arduino boards (Arduino Uno & Arduino Nano). I am trying to run a stepper motor  connected to Arduino Nano with two digital Pins on Arduino Uno to alter the direction of the stepper motor(BYJ48) connected to the arduino Nano.
While making connections I attached the pins as:

1] 5V  (UNO) -> 5V (NANO) & GND (UNO) -> GND (NANO)

2] 5V (UNO)  -> 5in (NANO) & GND (UNO) -> GND (NANO)

Both [1] & [2] worked fine initially but I kept the arduino powered and tried toggling the Vin with 5v. Nothing went wrong in the beginning but later fumes started coming out and I dont know the reason why?
Was that because I kept the power on while toggling between Vin & 5v ?
NOTE: besides the code and success in running the possible reason of fumes is much important here.


texts:
Why does this throw the error: "void value not ignored as it ought to be

returning = printTemperature(returnLine);"

void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
     return 0;
  } else {
    return tempC;
  }
}

void loop(){

   delay(2000);
   feeding = printTemperature(feedLine);
   returning = printTemperature(returnLine);
    mySql;
    feeding = 0;
    returning = 0;
}

Both 'feeding' and 'returning' are declared as a float too.


texts: Right now I have DHT11, PIR sensor, relay, and a photocell on the same board. I am planning to upload the data to a web server. But I want both DHT11 and photocell to be uploaded hourly; PIR and relay by every 3s. Is it possible for a single Arduino to perform such thing?


texts:
I have a problem , when send 1 or 0 by Bluetooth module the serial monitor print two time (RECEIVED SMS) . what's the wrong ?

This is my code  :

   char BluetoothData = 0 ;
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
    for (int pin = 1; pin <= 13; pin++)
     {
       pinMode(pin, OUTPUT); // sets the digitals pin  as outputs
       digitalWrite(pin, LOW); // sets the digitals pin off defult intial states
     }
       Serial.println("ALL LEDs NOW OFF \n ");
       Serial.println("Please, Enter : ( 1 to Turn on All LEDs )  or ( 0 to Turn off LEDs ) \n");
}
void loop() {
  // read the sensor:
  if (Serial.available() > 0) {

        BluetoothData = Serial.read();
            Serial.print("*** RECEIVED SMS *** : ==>> ");
            Serial.println(BluetoothData);

        if (BluetoothData == '1'){
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, HIGH);
          }
          Serial.println("ALL LEDs NOW ON");
         }
        // turn all the LEDs off:
   else if (BluetoothData == '0') {
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, LOW);
          }
          Serial.println("ALL LEDs NOW OFF");
         }
  }
   delay(100);
}

This is photo for serial monitor