texts: Arduino to read from RS232 converter to TTL serial module (updated)

texts:
Here's the system I want to work on:

The weight controller device detects weight which can transfer data via RS232 serial connection
I used RS232 converter to TTL serial module to connect the weight controller device to Arduino
The TTL connections were made to respective pins of Arduino UNO Board (GND-GND, VCC-5V, RX-0, TX-1)

The serial print from serial connection should produce 17 character length string : ST,GS    1.58,kg

Why am I getting strange results at times?

// Read Serial (RS232) data from Weight Controller Device via RS232 to TTL Converter Module

// Ignore the include statement, the editor does not allow pasting certain characters

include SoftwareSerial.h

int RX_PIN = 2;
int TX_PIN = 3;
int BAUD_IDE = 9600;
int BAUD_WEIGHT_SENSOR = 9600;

// serial port from weight controller
SoftwareSerial mySerial = SoftwareSerial(RX_PIN, TX_PIN);

void setup() {
  mySerial.begin(BAUD_WEIGHT_SENSOR);
  Serial.begin(BAUD_IDE);
}

void loop() {
  while (mySerial.available()) {
    int inChar = mySerial.read();
    if (inChar != '\n') {
      serialData += (char)inChar;
    }
    else {
      int dataSize = serialData.length();
      Serial.print(serialData);
      Serial.print(" length:  ");
      Serial.print(dataSize);
      Serial.print("\n");
      delay(3000);
      serialData = "";
    }
  }
  serialData = "";

}

// this one works perfectly but i want to store as string to process
// information and use for other functions
/*void loop() {
  if (mySerial.available()){
    Serial.print((char)mySerial.read());


texts: Sending data from a GUI to an Arduino nano via USB

texts:
Can somebody point me in the right direction for information on sending data to an Arduino nano?

My project is to send data that is updated from a GUI (presently written in Python) to an Arduino nano that then makes adjustments to a number of servo motors.

I have the servo code working but am presently using potentiometers to control the servo positions & would like the control done via a GUI.

What libraries would I need to be looking at. Have any of you done anything similar.

Thanks

Nic


texts: Level tracking using optical or capacitance sensors

texts:
I am looking to devise a level tracking system using arduino and some sensors. My particular situation is I have solute that is coming out of solution and I want to track the formation rate of the solid phase as the salts settle at the bottom and build a bed of particulates.

I am looking for precision at about 0.5mm and over a range of like 6 inches. My initial idea was to get a sensor bar that could detect when and where light is hitting the sensor and post processes that signal. I have to design this device to sit outside the cylindrical vessel. The solvent is transparent so any form of light would work. I am stuck on finding the parts that could pull this off and I was hoping the more experienced community could point in the right direction.

* UPDATE *

a little cartoon for a clearer picture of the idea
I am leaning towards capacitance since using light seems like a rabbit hole. I was playing with some foil and it may work but I need a much more sensitive tool on the order of pico-Farads to work.


texts: how to use hx-53 (IR Transmitter Infrared Sensor Module) with ESP32?

texts:
ESP32 tx2 (pin17) and rx2 (pin16) uses 3.3v based signals.

HX-53 data connect to tx2, gnd to gnd and vcc to vin(5v).

But as i can understand HX-53 data input should be 5v based.

How can i solve this problem?

HX-53: https://www.amazon.com/Electronic-Infrared-Emission-Transmitter-Arduino/dp/B07PJC7WSQ

Best regards.
GA


texts: Why should I connect the l289n motor driver wires to specific arduino pins only?

texts:
So, I am new with arduino and am to build a robot using motors, for that I have bought l298n H bridge motor driver. I have watched various site and videos ,to make sure not to make a mistake but, in every video and sites
I have found their connecting the motor direction controller to

IN1 -> Arduino Pin 8 (digital) and IN2 -> Arduino Pin 7 (digital)
Till then it was fine ... Now the fishy thing for me is
IN3 -> Arduino Pin 5 (PWM) and IN4 -> Arduino Pin 4 (Digital)
Why connect to a Digital and a PWM?
For E1 and E2 I am sure that the wires should be connected to the PWM (~) pins for arduino, to control speed of the motor..
But, Should not I be able to connect IN3 and IN4 both to rest of the digital pins 12, 13 or 2,4 Just Like IN1 and IN2 is connected to 7 and 8.
But the IN3 and IN4 is connected to a PWM and a Digital pin.
Conclusion,
So can I use all the unused non PWM digital pins to connect the motor direction control?
Thanks for your precious time..!


texts: How to increase SD card write speed in arduino

texts:
I'm creating a data-logger system which logs data in SD card at a high speed of about 20000-30000 bytes per second. But the SD library in arduino currently writes data at about 4500-5000 bytes per second which is too slow.

I've read this hack to improve the write speed, but I'm wondering if a more direct approach is possible, maybe by adjusting the SPISettings.


texts:
I have a sketch with multiple source files and folders arranged like so. I've divided up the project like this to keep things clean.

|
\---project
    |   project.ino
    |   types.h
    |
    +---sub1
    |       gadget1.c
    |       gadget1.h
    |       gadget2.c
    |       gadget2.h
    |
    \---blarg
            foobar.c
            foobar.h

The sketch file includes the headers via quoted include directives (rather than the lib alternative with angled brackets). This seems to work for compilation.

However, when the IDE tries to link, all references to implementations (c source files) in the subfolders generate "undefined reference" errors. Almost as if the IDE is completely ignoring the C source files.

In trying to resolve this I've discovered that apparently the handling of subfolders by the IDE seems to be all over the place. Some versions only acknowledge headers in subfolders, others work if you put everything in a "src" folder (I've also seen mention of a "utility" folder), some people suggest modifying environment variables, etc. I've even tried manually adding source files via the "sketch/add file" option which makes the files visible in the IDE but does not solve the linking problems. All these methods seem to depend on IDE version, and I couldn't distill what was the correct way vs a hack or work-around.

So my question is what is the correct/current way of organizing the above project so that it can be compiled/linked using the IDE? I am using IDE version 1.8.5 which I believe is either the latest version, or close too it.


texts: Can't connect to my ESP32 board via serial

texts:
I'm completely new to electronics work.

Today I've received the ESP32 board that I ordered. (It's a WROOM-32.) I followed the instructions here. I connected the board to my computer via USB and I successfully installed the CP210x drivers and got a new serial port COM3, but when I tried to connect to the board with that serial port, I got nothing. I'm on Windows 7.

I tried with Tera Term, and it just shows an empty screen.

I tried type COM3 in the shell, but got an empty string.

I tried doing esptool.exe --chip esp32 -p com3 erase_flash, but I get "Failed to connect to ESP32: Timed out waiting for packet header".

I tried playing with the two buttons on the WROOM32 board, but that didn't help.

Any idea what I'm doing wrong? I'm a complete newbie so it's likely that I'm forgetting something basic.


texts:
I wish to blink all the strip. In the code below it just blink the first LED, how can I fix it?

Code:

#include <Adafruit_NeoPixel.h>

#define PIN 6
#define NUM_LEDS 24

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

void setup() {
  strip.begin();
  strip.show();
}

void loop() {
  strip.setPixelColor(0, 255, 255, 255);
  strip.show();
  delay(1000);
  strip.setPixelColor(0, 0, 0, 0);
  strip.show();
  delay(1000);
}


texts: getting the error "expected unqualified-id before 'if' "

texts:
I'm new to programming and cant seem to understand Whats going on
but here is my code
https://pastebin.com/W55B7RAk
#include <Servo.h> // servo library
#include <IRremote.h> // ir library

Servo servo123; //servo object

int redled =3; // redled at 3 pin
int servopin =9; // servo at 9 pin
int buttonpin =2;//where button pin is
int buttonstate =0; // variable for button pin status
int buzzer = 4; //buzzer to arduino pin 4
//int PIRval=0;// variable storing PIR value
//int   PIRpin=7; //Pin of PDR
int ServoTime= 3000; //Time to wait for sevo
int IRsensor = 7; // assignig varaible to 7

IRrecv irrecv(IRsensor);// Creates receive object and attacbes variable
decode_results Results123; // decorder results stored into variable named Results123

void setup()
{

  servo123.attach(servopin); // attaching pin to servo
  pinMode(redled, OUTPUT); //making led output
  pinMode(buttonpin, INPUT); // making it a input
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 4 as an output
  //pinMode (PIRpin, INPUT); //PIRpin as input
  irrecv.enableIRIn(); // begin the receiving process

  Serial.begin(9600);// intialise communications at 9600 bits p second
}

void loop()
{
    buttonstate=digitalRead(buttonpin);//checking state of buttonpin
  //PIRval=digitalRead(PIRpin); // storing value at pin into Variable

  // if an IR signal received , returns true and stores value into Results123

  if (irrecv.decode(&Results123))
  {
    //Serial.println(Results123.value); // print the code

    switch (Results123.value){

      case 16582903: // button 1
        servo123.write(180);// make it rotate cw to open gate
        delay(3000);//wait for 3s (To allow the pet food to get dispense
        digitalWrite(redled, HIGH); // makes red led glow
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(500);        // ...for 0.5 sec
        noTone(buzzer);     // Stop sound...
        delay(1000);        // ...for 1sec
        break;

      case 16593103: // button 0
        servo123.write(0);// rotate to close gate and stop flow
        digitalWrite(redled, LOW);// turns led off
      break;

   }

     irrecv.resume(); // reset the receiver and prepare to recieve another code
   }
      delay(100);
   }

 if (buttonstate == HIGH) {
    servo123.write(180);// make it rotate cw to open gate
    delay(3000);//wait for 3s (To allow the pet food to get dispense
    digitalWrite(redled, HIGH); // makes red led glow
    tone(buzzer, 1000); // Send 1KHz sound signal...
    delay(500);        // ...for 0.5 sec
    noTone(buzzer);     // Stop sound...
    delay(1000);        // ...for 1sec
  }

  else{
     servo123.write(0);// rotate to close gate and stop flow
     digitalWrite(redled, LOW);// turns led off

  }


texts: How do I hook up a 3V device to a 74AHCT125 (Quad Level-Shifter)?

texts:
I have this level shifter that I'm trying to feed a 5V power source and then hook up a 3V device.

I've got the 5V source hooked up fine (on the top pinouts), but having trouble figuring what the "power out" would be that's 3V.

Here's the data sheet.


texts: How to get text to flash on ssd1306 i2c screen

texts:
I am trying to alternate a string back and forth on the SSD1306 oled screen.
So I want the display to show "test1" for 0.5 seconds, then "test2" for 0.5 seconds, repeating. the code below is just showing "test1" for 0.5 seconds then going blank...
I am using a ssd1306 128_32 i2c screen, and using the adafruit library.

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);

  display.setTextSize(4);             // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);

}

void loop() {
 testdrawstyles1();
 testdrawstyles2();
}

void testdrawstyles1(void) {
 display.clearDisplay();
 display.print(F("test1"));
 display.display();
 delay(500);
}

void testdrawstyles2(void) {
 display.clearDisplay();
 display.print(F("test2"));
 display.display();
 delay(500);
}


texts:
I have an Arduino UNO and sim808 EVB-V3.02.4.
I want to send a GET request to my url but I always receive 400 Http bad request error.

#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX    7
#define PIN_RX    8
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n\r\n";
char buffer[512];

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

void loop() {
  //*********** Attempt DHCP *******************
  while(!sim808.join(F("cmnet"))) {
      Serial.println("Sim808 join network error");
      delay(2000);
  }

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //*********** Establish a TCP connection ************
  while(!sim808.connect(TCP,"39c309ae.ngrok.io", 80)) {
      Serial.println("Connect error");
  }
  Serial.println("Connection success");

  //*********** Send a GET request *****************
  Serial.println("waiting to fetch...");
  sim808.send(http_cmd, sizeof(http_cmd)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }
      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

  //************* Close TCP or UDP connections **********
  sim808.close();

  //*** Disconnect wireless connection, Close Moving Scene *******
  sim808.disconnect();
  delay(5000);
  }

My php code:

<?php
file_put_contents('test.txt', $_GET['lat'] . '---' . $_GET['lon']);
print '
<html>
<head>
<title>Good</title>
</head>
<body>
Was Good
</body>
</html>
';
?>

I want just open http://39c309ae.ngrok.io/index.php?lat=10&long=100 with arduino and sim808.

What is wrong in my codes?


texts: PUT request: PHP code to Arduino HTTPClient

texts:
I'm uploading a file to Azure blob storage using REST API request. The file uploaded successfully using PHP curl request. But when I transfer the code into ESP32 HTTP client I'm getting an Authentication error. I also verify the HMAC key generated by the ESP32 Arduino code in PHP code.
I'm thinking that I'm missing something in adding header.
Here is my PHP code :

       $header = array (
        "x-ms-blob-type: BlockBlob",
        "x-ms-date: " . $date,
        "x-ms-version: " . $version,
        "Authorization: SharedKey account_name:" . $signature_str,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Length: " . strlen($fdata),
        );

    $url =  "https://acount_name.blob.core.windows.net/container/test.txt";
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata);
    curl_setopt ( $ch, CURLOPT_HEADER, True );
    echo($ch);
    curl_exec ( $ch );

and here is the corresponding Arduino IDE code:

    String sig = get_hmac();
      Serial.println(sig);

      if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        HTTPClient http;
        http.begin("https://account_name.blob.core.windows.net/container/test.txt");  //Specify destination for HTTP request

        http.addHeader("x-ms-blob-type", "BlockBlob");
        http.addHeader("x-ms-date", Date);
        http.addHeader("x-ms-version", "2018-03-28");
        http.addHeader("Authorization", "SharedKey account_name:"+sig);
        http.addHeader("Content-Type", "text/plain; charset=UTF-8");
        http.addHeader("Content-Length",  "20");

        int httpResponseCode = http.PUT(d);
        if (httpResponseCode > 0) {
          String response = http.getString();
          Serial.println(httpResponseCode);
          Serial.println(response);
        } else {
          Serial.print("Error on sending POST: ");
          Serial.println(httpResponseCode);
        }
        http.end();  //Free resources
      } else {
        Serial.println("Error in WiFi connection");
      }

The error I'm getting is :

  The MAC signature found in the HTTP request
  'sVrSFpplX+Gkcb4R/iSDf6eqUP4srkZuVD68/pAeYwE=' is not the same as any
  computed   signature.....

Although the HMAC signature created from same String works in PHP
here is the reference page of the API:
https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob
Thanks


texts: Getting two Arduinos to talk to each other via an optocoupler

texts:
I've setup two Arduinos connected via an optocoupler on a breadboard.

One Arduino is a sender and sends pulses to the optocoupler causing the diode to turn on.

When this happens the other Arduino has it's input connected to the emitter. This is interpreted as 1 on the receiver side. Or if the diode is off it's a 0 on the receiver side.

My problem is getting them to sync. I'm currently using delay which I'm starting to realize is a horrible idea since they go out of sync after about 2 characters have been sent. So I wonder are there any better solutions to syncing them?


texts: Cloud function getting stopped Parse.com in loop when calling from Arduino-yun

texts:
I have created a cloud function using the Parse.com Javascript SDK and I am calling those functions from Arduino. Following is code for the hello function:

Parse.Cloud.define("hello", function(request, response) {
                response.success("This is hello function");
}); //hello function Block

I am calling this function from the Arduino side using the following code:

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

  while (!Serial);

  Parse.begin("***zE0uUjQkMa7nj5D5BALvzegzfyVNSG22BD***", "***Ssggp5JgMFmSHfloewW5oixlM5ibt9LBSE***");
  //commented my keys with * here only

  // In this example, we associate this device with a pre-generated installation
  Parse.getInstallationId();
  Parse.startPushService();
}

void loop() {
  Serial.println("Start loop");
  demoBasic("meeting", 0);
}

void demoBasic(String functionname, int light) {
  char fnname[11];
  functionname.toCharArray(fnname, 11);

  Serial.print("In ");
  Serial.print(functionname);
  Serial.println(" Function");

  ParseCloudFunction cloudFunction;
  cloudFunction.setFunctionName(fnname);
  cloudFunction.add("light_sensor", light);
  cloudFunction.add("value", "Arduino Hello");//parameters

  ParseResponse response = cloudFunction.send();
  Serial.println(response.getJSONBody());
}

Problem is that I am getting response 8 times only. After that whole program flow gets blocked. What is the problem?


texts:
I have a new ESP32 Wroom attached to my USB and it shows up in the settings on my mac:

I do have another ESP thing from sparkfun which I can access via  /dev/cu.usbserial-DN02N1D8. This device I can flash without problems or read its mac address using esptool.py.

Connecting........_____....._____....._____....._____....._____....._____....._____

So I wonder how I can flash the ESP32.

Update: Added a picture of my board.


texts: Error: request for member 'RGB' in 'redLed' , which is of non-class type 'int'

texts:
My 10 year old received great gift from older brother (Crate Creations) and I am trying write the program and getting this error. It looks to me that I matched the required code word for word symbol for symbol but I just can't figure out what I did wrong:

void loop () {

  for (float x = 0; x < PI; x = x + 0.00001) {
    RGB[0] = power * abs(sin(x * (CommonMathVariable)));
    RGB[1] = power * abs(sin((x + PI/3) * (CommonMathVariable)));
    RGB[2] = power * abs(sin((x + (2 * PI) / 3) * (CommonMathVariable)));
    ambientLight = analogRead(ldrPin);
    if (ambientLight > 600) {

    analogWrite (redLed.RGB[0]);
    analogWrite (greenLed.RGB[1];
    analogWrite (blueLed.RGB[2];

  }

I get this error:

request for member 'RGB' in 'redLed' , which is of non-class type 'int'


texts: Boolean Logic With Chars For Motor Input Selection

texts:
Context of the code:

I am trying to control 2 DC motors through an H-gate, this means there are 4 inputs in total:
For DC motor 1: Input 1 (VCC) and Input 2 (GND).
For DC motor 2: Input 3(VCC) and Input 2 (GND).

Summary of the code:

The global variables are motinpN which are the pins connected to the different inputs.

An array, which is where the different PWM for the motor speeds are stored.

Char x, which is the variable used for the boolean logic.

Then comes the actual loop which consists of 4 similar functions, the "input selector" function and then the statements that turn the integers stored in the inpSpeedS[] arrays into motor speeds.

The issue:

The code won't enter the first loop, i.e it won't advance past

Serial.println("X equals:");
  Serial.print(x);"

I would like to know then, what I am doing wrong in order for this not to work?

   int Speed = 0;
const int motinp1 = 2;
const int motinp2 = 3;
const int motinp3 = 4;
const int motinp4 = 5;

char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

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

void loop() {
  Serial.println("X equals:");
  Serial.print(x);

  if (Serial.available () && (x == '0')) {
    Serial.print("Which input?");
    x = Serial.read();
    Serial.println(x);
  }
  if (Serial.available () && (x == 'a'))
  {
    Serial.println("Input 1 selected");
    inpSpeedS[0] = Serial.parseInt();
    Serial.print("Input 1: ");
    Serial.println(inpSpeedS[0]);
   x = '0'; //reset x, goes back to input selection
  } if (Serial.available () && (x == 'b'))
  {
    Serial.println("Input 2 selected");
    inpSpeedS[1] = Serial.parseInt();
    Serial.print("Input 2: ");
    Serial.println(inpSpeedS[1]);
   x = '0';
  }
  if (Serial.available () && (x == 'c'))
  {
    Serial.println("Input 3 selected");
    inpSpeedS[2] = Serial.parseInt();
    Serial.println("Input 3: ");
    Serial.print(inpSpeedS[2]);
   x = '0';
  }
  if (Serial.available () && (x == 'd'))
  {
    Serial.println("Input 4 selected");
    inpSpeedS[3] = Serial.parseInt();
    Serial.print("Input 4: ");
    Serial.println(inpSpeedS[3]);
   x = '0';
  }
  analogWrite(motinp1, inpSpeedS[0]);
  analogWrite(motinp2, inpSpeedS[1]);
  analogWrite(motinp3, inpSpeedS[2]);
  analogWrite(motinp4, inpSpeedS[3]);
}

EDIT - I have turned the char 0 from a string literal null to an ASCII code for 0, and same for the other chars. It is still stuck outside of the function loops.


texts:
I'm using an Arduino Uno with Funduino I2C 1602 LCD display. The LCD display is connected as

LCD

SCL--> A5
SDA -->A4

I need to measure the temperature, pressure and the velocity of a duct flow. So I connected a BMP180 to my arduino with the following connection

SCL--> A5
SDA -->A4

As you can see, both of them are connected to same pins. The connection works fine just for BMP180 but when I add a rotary encoder and print its value on LCD, I'm getting delayed and wrong data.

I'm using this BMP180 library
https://github.com/adafruit/Adafruit_BMP085_Unified

The LCD uses this library (v1.2.0)

https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads

how can I change bmp180 or LCD analog pins in these libraries?


texts:
I need some help with programming Arduino with EMG signals to control the solenoid pressure valve.
I wrote some program which is setting high and low state on the output pin, but it's not working properly.
First I create a plot to observe the signal level. And the plot looks like in the picture which I attached.

The basics concept of program is setting the high signal on the output when I flex muscles and when I relax the muscle it's should write low state on the output. My idea was based on triggering the on-off signals at the moment when the muscle is flexed, the value of signal is above 600 (now the diode should be ON and stay in ON state) and it drops and when I relax muscles the value rises once again to value around 600 more or less (now the diode should be OFF) and drops under 100.

const int ledPin=13;

const int sensorPin= 0;

int level;

const int threshold1=400;

const int threshold2 =500;

void setup() {

    pinMode (ledPin, OUTPUT);

    pinMode (sensorPin, INPUT);

    Serial.begin(9600);
    }

void loop(){

    level= analogRead(sensorPin);

    if (level > threshold1){

    digitalWrite(ledPin, HIGH);

    if (level > threshold2)

    digitalWrite(ledPin, LOW);

    }

I wrote new code, but I still have problems with proper sending of an ON and OFF     signal to the output.

When I flex the muscle I have high state on the output causing by first peak (LED is ON) but when I relax the muscle the second peak won't set the low state on the output. But when I flex the muscle once again the output change state to low and the diode is OFF. Do you have any suggestions what part of the code do I need to improve?

Here's the code:

const int ledPin=13;

const int sensorPin= 0;

int level;

int flex= 0;

int PreviousState = 501;

const int threshold1=600;

void setup() {

    pinMode (ledPin, OUTPUT);

    pinMode (sensorPin, INPUT);

    Serial.begin(9600);
}

void loop() {

    level= analogRead(sensorPin);

          if (level > threshold1 && PreviousState < threshold1){

          {

            flex =!flex;

          }

          if (flex == 1)
          {

            digitalWrite(ledPin, HIGH);

          }

          else

          {
            digitalWrite(ledPin, LOW);

          }

          PreviousState = level;

        }

    }

}


texts: What does using [i] consecutive in a function means?

texts:
I read a code but i could not understand it!

for (int i = 0; i < msg->length(); i++) {
    uart_->send(msg->data()[i]);
}

In above code what does this line means? data()[i]


texts: SCLK pulses not seen when using SPI on ESP32

texts:
I am using the following code in my esp32 using arduino IDE for spi communication which is an example code -

#include <SPI.h>

static const int spiClk = 1000000; // 1 MHz

//uninitalised pointers to SPI objects
SPIClass * vspi = NULL;
SPIClass * hspi = NULL;

void setup() {
  //initialise two instances of the SPIClass attached to VSPI and HSPI respectively
  vspi = new SPIClass(VSPI);
  hspi = new SPIClass(HSPI);

  //clock miso mosi ss

  //initialise vspi with default pins
  //SCLK = 18, MISO = 19, MOSI = 23, SS = 5
  vspi->begin();
  //alternatively route through GPIO pins of your choice
  //hspi->begin(0, 2, 4, 33); //SCLK, MISO, MOSI, SS

  //initialise hspi with default pins
  //SCLK = 14, MISO = 12, MOSI = 13, SS = 15
  hspi->begin();
  //alternatively route through GPIO pins
  //hspi->begin(25, 26, 27, 32); //SCLK, MISO, MOSI, SS

  //set up slave select pins as outputs as the Arduino API
  //doesn't handle automatically pulling SS low
  pinMode(5, OUTPUT); //VSPI SS
  pinMode(15, OUTPUT); //HSPI SS

}

// the loop function runs over and over again until power down or reset
void loop() {
  //use the SPI buses
  vspiCommand();
  hspiCommand();
  delay(100);
}

void vspiCommand() {
  byte data = 0b01010101; // junk data to illustrate usage

  //use it as you would the regular arduino SPI API
  vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(5, LOW); //pull SS slow to prep other end for transfer
  vspi->transfer(data);
  delay(500);
  digitalWrite(5, HIGH); //pull ss high to signify end of data transfer
  vspi->endTransaction();
}

void hspiCommand() {
  byte stuff = 0b11001100;

  hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(15, LOW);
  hspi->transfer(stuff);
  delay(500);
  digitalWrite(15, HIGH);
  hspi->endTransaction();
}

I am able to see the toggling of the SS pin, but the SCLK pin does not show any pulses on the oscilloscope. It is a constant low. Should the pulses be given from an external source? If so, what is the purpose of this line - static const int spiClk = 1000000; // 1 MHz?


texts: Relationship between baud rate and the frequency of vibration read using ADXL

texts:
I am doing a project using Arduino Uno and ADXL 345.
I am quite new to this and I came across this post  in the link" : https://www.sparkfun.com/tutorials/240. Here, a user had posted the below question in the forum.

"Im trying to use this accelerometer to test various frequencies of vibration on a cantilevered beam and I wanted to know what the maximum vibration frequency I could find with using this accelerometer, connected to a 16MHz processor, connected to my laptop. I’m mainly a mechanical person, but after doing some research I found the following: Accelerometer has a maximum of 3200Hz output data rate (so maximum frequency would be 1600Hz) Processor can execute 16,000,000 instructions/sec so this probably is okay Communication rate is 9600 bits/sec so in the program above we read at a minimum 6 bytes for each axis, so that’s 24 bits, leaving you able to read 9600/24 = 400 reads/sec resulting in a one to be capable of reading vibrations at 200Hz. If I bump up the baud rate to 115200, I should be able to then read 4800 times a second, thus measuring 2400Hz vibrations?"

But I do not see any replies to this question. I feel the above analysis mostly makes sense. It would be helpful if someone could confirm that the above analysis is right. If not right , then why isn't it right?

Thanks


texts:
I have a robot that uses two motors to skid steer. The robot gets input from three ultrasonic sensors (left, middle, and right) and a passive infrared sensor. If the robot detects a person in front of it, then it follows.

The sensors seem to work as they are intended. The infrared sensor sees a person and the ultrasonic sensors see that the person is between 65cm and 150cm and it follows. If the left ultrasonic sensor has the person in range, it turns left, and if the right ultrasonic sensor has the person in range, it turns right.

The problem is that the robot gets stuck turning left or turning right depending on which sensor it checks first in the code. It's like it's stuck in a while loop even though I'm not using a while loop.

I have adapted NewPing and library. The code in question is at the bottom in the last function. The rest is part of NewPing to read the ultrasonic sensors.

If anybody has any suggestions, it would be greatly appreciated.

#include <NewPing.h>

#define SONAR_NUM     3 // Number of sensors.
#define MAX_DISTANCE 170 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 35 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
uint8_t currentSensor = 0;          // Keeps track of which sensor is active.

NewPing sonar[SONAR_NUM] = {     // Sensor object array.
  NewPing(11, 4, MAX_DISTANCE), //Left -- Each sensor's trigger pin, echo pin, and max distance to ping.
  NewPing(8, 3, MAX_DISTANCE),  //Center
  NewPing(7, 9, MAX_DISTANCE),  //Right
};

int ledR = 13;
int ledG = 2;
int ledB = A0;
int motorPinL = 5;
int motorPinR = 6;
int ePIR = 10;
boolean epirVal;

void setup() {
  Serial.begin(115200);
  pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
  for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
  pinMode (ledR, OUTPUT);
  pinMode (ledG, OUTPUT);
  pinMode (ledB, OUTPUT);
  pinMode (motorPinL, OUTPUT);
  pinMode (motorPinR, OUTPUT);
  pinMode (ePIR, INPUT);
}

void loop() {
  for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
    if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
      pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
      if (i == 0 && currentSensor == SONAR_NUM - 1)
        oneSensorCycle();                             // Sensor ping cycle complete, do something with the results.
      sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
      currentSensor = i;                          // Sensor being accessed.
      cm[currentSensor] = 155;                      // Make distance 155 in case there's no ping echo for this sensor. changed from zero
      sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    }
  }
  // Other code that *DOESN'T* analyze ping results can go here.
}

void echoCheck() { // If ping received, set the sensor distance to array.
  if (sonar[currentSensor].check_timer())
    cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
}

void allStop () {
  analogWrite (motorPinL, 0);
  analogWrite (motorPinR, 0);
  digitalWrite (ledG, LOW);    //LED corresponding to right ultrasonic sensor
  digitalWrite (ledR, LOW);    //LED corresponding to left ultrasonic sensor
  digitalWrite (ledB, LOW);    //LED corresponding to center ultrasonic sensor
}


texts: How would I use Arduino microcontroller separately?

texts: I'm learning Arduino. I use Arduino Uno board with ATMEGA328-PU. I tried basic codes like LED blink, control of DC motor etc. Arduino board is used only when we program microcontroller, right? I mean, when we finish programming it, we can use microcontroller separately? If it can be used separately, we must have some "external" circuit as replacement for Arduino board, which allow us to use microcontroller in specific application. What type of circuit is used? I'm new in this field so don't blame me because of amateur questions.


texts:
I was looking for a websocket server for my MKR100 but nothing I found looks it works. I tried all the  libraries that come with arduino but half of those doesn't compile on MKR1000 and those that did it doesn't work at all.
Your help would be greatly appreciated!


texts: How to convert read characters to strings?

texts:
How can I append a string e.g. "AA 00 01 00 FF FF A2" to serial data using Arduino?

The following code does not seem to be correct:

String comdata;
void loop() {
  while (Serial2.available() > 0) {
    c = Serial2.read();
    //c is "AA 00 01 00 FF FF A2"
    comdata +=c;
  }
  if(comdata.length()>0){
    Serial.println(comdata);
    //YES on HEX mode ;print "AA 00 01 00 FF FF A2"
    }
    delay(1000);
}


texts: getting error 'Serial' was not declared in this scope

texts:
I am adding Dust Sensor to my particle photon project at home,

I got this GitHub project that I want to test before implementing a final code.

I am not an expert in cpp, I wanted to modularise the dust sensor codebase to separate library so I created new dustSensor.cpp file and kept the code linked above.

but I keep getting error:

'Serial' was not declared in this scope

'Serial1' was not declared in this scope

'DEBUG' was not declared in this scope

'DEC' was not declared in this scope dustSensor.cpp:13:57:

I do have Serial.begin(57600) called in setup() function but still get the above error


texts: Arduino escape characters not working when not defined in code

texts:
I am making an Arduino ethernet and serial communication program.
The point of my program is to "SendKeys" the received message from Arduino that received the message from HTTP request query, like if I type "10.0.0.45/?hello world" (10.0.0.45 is my Arduino's IP) it should retrieve the "hello world" message and send it via serial.
Everything works fine, but when I am trying to send escaped characters, such as "\n", it will not work, it will type the same thing.
But, I can use the replace function in my Arduino code, like this: query.replace("{ENTER}","\n");
Then it will work, but I want to make it work even without the replace function.
I am not good at explaining, so you can ask for details.
Here's my code:
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>

File file;
String clientGetUrl;
String query;
String readString;
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
EthernetServer server(80);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  SD.begin(4);
  Ethernet.begin(mac);
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.Sorry, can't run without hardware. :(");
    while (true) {
      delay(1);
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }
  server.begin();
  Serial.print("IP Address: ");
  Serial.println(Ethernet.localIP());
  pinMode(2, OUTPUT);
}

void loop() {
  EthernetClient client = server.available();
  if (client) {
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n' && currentLineIsBlank) {
          clientGetUrl = readString.substring(readString.indexOf("/"), readString.lastIndexOf(" HTTP"));
          if (clientGetUrl.indexOf("?") > 0) {
            query = clientGetUrl.substring(clientGetUrl.indexOf("?") + 1, clientGetUrl.length());
          } else {
            query = "";
          }
          query.replace("%20", " ");
          query.replace("{ENTER}", "\n");
          query.replace("{BP}", "\b");
          query.replace("{ESC}", "\x1B");
          query.replace("{SHIFT}", "+");
          query.replace("{CTRL}", "^");
          query.replace("{ALT}", "%");
          Serial.print(query);

          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();

          file = SD.open("baduino/sendkeys.htm");
          if (file) {
            while (file.available()) {
              client.write(file.read());
            }
          }
          file.close();
          break;
        }
        if (c == '\n') {
          currentLineIsBlank = true;
        } else if (c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(1);
    readString = "";
    client.stop();
  }
}

And again, if i go to my Arduino's page, "http://10.0.0.45/?hello \n", it will retrieve the hello message and send it to my PC via serial, and then my PC receives the message and makes a "SendKeys" with my message.
But the problem is instead of making the new line at the end of the message, it types "hello \n".


texts:
I'm running the following code:

#include <XBOXRECV.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
XBOXRECV Xbox(&Usb);

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nXbox Wireless Receiver Library Started"));

}

void loop() {
  Usb.Task();
  if (Xbox.XboxReceiverConnected) {
    if (Xbox.getAnalogHat(LeftHatY) == 0) {
      Serial.print(Xbox.getAnalogHat(LeftHatY));
    }
   Serial.print("TEST");
  }
}

After running the example that the library includes and a spin off I wrote for test purposes I keep getting random output, this is just some of it:

  9�]==�=�~=���y��:.�:�:����9�=��������:�:�\=���^=�?�}�:^���:�|]=9�\=��������:�ܗ��.\�~=���


texts:
I tried regular RFID tags and It works but when I tried NTAG203 it won't detect.

P.S. I used the code "dump_data" example of MFRC library.


texts: Interfacing Arduino with matplotlib animation

texts:
I've also asked this question over on stack exchange so I'll link the actual question here.

The short story is I have a plot that updates in real time from data collected on an Arduino. The plot updates on a 50ms + overhead interval and I can either choose on the Arduino side to either delay the loop 50ms + compensation or use flush(). I'm running into some problems with the delay option where my program begins to lag (Python side). I'm wondering if flush will work as I expect and hold the output until my python program reads from the serial port. So then the Python program is completely controlling the flow of data every time it polls for an update.

Edit: Here's a snippet of the code.

void loop() {
  // put your main code here, to run repeatedly:
  val1 = analogRead(0);
  val2 = analogRead(1);
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  //Serial.flush();
  delay(50);
}


texts: i2c scanner stuck on scanning for my 0.96in OLED screen with my Arduino Nano

texts: My pins are connected as follows; vcc-3v3, gnd-gnd, sda-A4, scl-A5.


texts: Getting error 32 in multi-master I2C sketch with library https://github.com/rambo/I2C

texts:
I am developing a multi-master scenario sketch with the https://github.com/rambo/I2C library, because this library will handle multi-master data collisions.

I created a setup with two Arduino nano's which act both as master and slave.
My sketch works as long as I use only one master. Sending data from one Arduino to the other works fine. The other receives the data.

But when I sequentially try to send data from the second Arduino to the first, I get an error (32). After that even sending data from the initial Arduino results in error 32.

This is the used sketch for both the Arduino's.
The only difference is that I switch the values of rel_address and own_address when programming the seconds Arduino.

Sending data is done by pressing a button on pin 2 (switchPin)

/**
   atme328 = ATmega328
   SDA --> Pin A4
   SCL --> Pin A5
*/
#include <I2C.h>
#include <Wire.h>

int switchPin = 2;
int relayOnPin = 3;
int relayOffPin = 4;

uint8_t broadcast_address = 0;
uint8_t own_address = 11; // CHANGE FOR EVERY MODULE!!
// rel_address = address of relay to switch; SET to own_address if relay is connected to this chip!
uint8_t rel_address = 10; // CHANGE FOR EVERY MODULE!! SET to own_address if relay is connected to this chip!
uint8_t rpi_address = 1;

unsigned long counter = 0;

void setup() {

   Serial.begin(9600);
   pinMode(switchPin, INPUT_PULLUP);

   pinMode(relayOnPin, OUTPUT);
   pinMode(relayOffPin, OUTPUT);
   // start condition
   digitalWrite(relayOnPin, HIGH);
   digitalWrite(relayOffPin, LOW);

   I2c.begin();
   I2c.timeOut(50);
   // I2c.pullup(true); // done by external 4.7kOhm resistors

   // config Wire library for I2C slave functionality
   Wire.begin( own_address );

   TWAR = (own_address << 1) | 1;  // enable broadcasts to be received!

   // set slave receive callback
   Wire.onReceive( onI2CReceive );

}

void loop() {
   counter = counter + 1;
   if (counter == 20000) {
      digitalWrite(relayOnPin, LOW);
      digitalWrite(relayOffPin, LOW);
   }
   if ( digitalRead(switchPin) == LOW ) {
      sendCmd('d', rel_address); // send command to remote relay
   }
}

void sendCmd(uint8_t cmd, uint8_t address) {
   uint8_t status = I2c.write(address, cmd); //configure device for continuous mode
   if (status > 0) {
      // error codes at https://github.com/rambo/I2C/blob/master/I2C.cpp
      Serial.print(status, DEC);
      Serial.print('!');
      digitalWrite(relayOffPin, HIGH);
      delay(50);
   } else {
      digitalWrite(relayOnPin, HIGH);
      Serial.print('.');
   }
   counter = 0;
}

void onI2CReceive(int howMany) {
   // loops, until all received bytes are read
   while (Wire.available() > 0) {
      digitalWrite(relayOffPin, HIGH);
      Serial.write(Wire.read());
   }
   counter = 0;
}

What do I need to do to be able to send from two units using this library?
Thanks!


texts: Understanding Soil Moisture Sensor Values


texts: ATTiny85 won't boot if PIN2 is not pulled high

texts:
I had some problem setting up a working ATTiny85 outside of its development board.Connection on my breadboard:
pulled high (10K R)  -- 1  PIN 8  -- VCC (+5V)
     trouble here!!  -- 2  PIN 7  --
                     -- 3  PIN 6  -- LED
               GND   -- 4  PIN 5  --

as you can guess pins are referred to actual chip's pins enumeration.My simple test code:
void setup() {
  pinMode(1, OUTPUT);
}
void loop() {
  if (analogRead(A1) > 512) {
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
  } else {
    digitalWrite(1, HIGH);
    delay(1000);
    digitalWrite(1, LOW);
    delay(1000);
  }
}

I'm using Arduino IDE v1.8.13 with digistump avrboards v1.6.7.
I flashed t85_default micronucleus v2.5 bootloader in my chip with fuses set to lfuse:0xe1, hfuse:0xdd, efuse:0xfe.The problem is that if I power the chip with PIN2 not pulled high it won't start execution of the code, it won't blink.  If it’s started from pulled high, it will start code about 5s after power on. If it’s started pulled low code won’t execute until is pulled high. As I pull high, even just for a second, PIN2 it will start blinking and executing code.
Is it normal? I think I have missed something.


texts: Arduino - stepper motor wrong steps number

texts:
I just bought a new stepper motor (400 steps for revolution, 0.9°/step) and I would like make a turn of 180° by 200 steps, but it doesn't work as expected.
It looks like the motor needs only 110 steps to make a turn of 180° and I don't know the cause. The driver motors is the Keyes L298. It is wired to my Arduino UNO rev3.

In order to clarify, please see the image below:

The code is as follows:

#define negativeSteps -55
#define positiveSteps 55
#define Speed 7500

int motorPin1 = 11;
int motorPin2 = 10;
int motorPin3 = 9;
int motorPin4 = 8;

int steps;
unsigned int tmp2;

byte modeR[] = {B00001001, B00001010, B00000110, B00000101};
byte modeF[] = {B00000101, B00000110, B00001010, B00001001};

void setup() {

  Serial.begin(115200); //Opens serial connection at 115200 baud.

  pinMode(11,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(8,OUTPUT);

  pinMode(3,OUTPUT);    // Enable pin motorA
  pinMode(2,OUTPUT);    // Enable pin motorB

  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
}

void loop()
{
    while (Serial.available())
    {
      char cmd = (char)Serial.read();
      if (cmd == 's')   while(1) Seek();
    }
}
void motorR(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeR[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void motorF(){
  int bitMask=B00001111; // bitmask to modify only last 4 bit

          for (int id = 0; id <4; id++) {
            PORTB = (PORTB &~bitMask) |  modeF[id];
            while (tmp2++<Speed);
            tmp2=0;
          }
}
void Seek() {
  steps = negativeSteps;      //Init Steps
  while (1)
  {

    while (steps<positiveSteps) //  starts from "negative" steps to "positive" steps ( -55 to +55)
    {
       if (steps<0) motorF(); // if steps = 0 it will change the direction
       else motorR();

      Serial.println(steps);
      steps++;
   }
 }
}


texts:
I want to display the DHT22 temperature and humidity sensor in a 3 digit 7 segments display. It's always showing the  sensor value and after 2 or 3 sec the display turns off, and then the display turns on, and so on.
I need help to understand where is the mistake on the code to make the display always turned ON.

#include <SevSeg.h>
#include <EEPROM.h>
#include "DHT.h"
#define COMMON_ANODE 0
#define DHTPIN A0     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value
SevSeg sevseg;

void setup(){

byte numDigits = 3;
byte digitPins[] = {1,2,3};
byte segmentPins[] = {4,5,6,7,8,9,10,11};
sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
 dht.begin();
}

void loop(){
   temp= dht.readTemperature();

   sevseg.setNumber(temp,1);
   sevseg.refreshDisplay();
}


texts: Problem with LED (Builtin) connected to pin 13

texts:
This is Aakash. Student of Electrical Engineering in a University.
I want to ask some information. Today I Purchased Arduino UNO R3 board. and facing some problem which are :

          "**Builtin LED at pin#13 is always ON on my board**".

Is there any problem with the board ?

I tried to upload these sketches and got these results::
1)...with empty setup(){} and empty loop(){}, Still LED is ON.
2)...When I uploaded these command "pinMode(LED_BUILTIN,OUTPUT);" in setup() and "digitalWrite(LED_BUILTIN,LOW);" in loop(), LED turned OFF
3)...If i touch pin13 and Ground both by a wet finger at back of board, LED turns OFF.
4)...but on uploading empty or any other code, BUILTIN_LED turns ON again and do not turns OFF.

Kindly reply me ASAP! So that if i have got faulty Board then i might go for claim.


texts: ESP8266 Blink sketch - does not blink / or stays constant

texts:
I uploaded the Blink sketch (from the ESP8266 examples, in the Arduino IDE) successfully.

Depending on which wire configuration I am using two different things happen:

wiring 1:

CH_PD -> 3.3V
VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

wiring 2:

VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

There are TX/RX lines in the picture from when I was flashing - they aren't being used for running the sketch.

With wiring 1 the LED stays on (doesn't blink) - I was wondering if this was because I still had the VCC -> 3.3V connected. So I disconnected that, which gives way to wiring 2.

With wiring 2 the LED doesn't come on at all, it is the same as wiring 1 except without VCC -> 3.3V.

Why is it constant when 3.3V is going to VCC, and constantly off when I disconnect it? Why doesn't it blink using wiring 2?

UPDATE

A diagram as requested, sorry it was my first time doing this:

Code:

/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}


texts: DigiSpark attiny85 computer not detecting

texts:
I purchased a DigiSpark attiny85 off of ebay. Over the weekend I tried to get my computer to recognize the DigisSpark, but it won't recongnize it. When I plug the device in, the 'Device Connection' Sound alerts me and then a second or two the 'Device Disconnection' Sound alerts, then 'Device Connection' Sound, then the 'Device Disconnection' sound. This happens until I unplug the device. The light does turn on, but Windows (10) doesn't recognize the device, it just loops the sounds.
I am trying on a Windows 10 machine.
I installed the drivers from the DigiStump Github: https://github.com/digistump/DigistumpArduino/releases/download/1.6.7/Digistump.Drivers.zip
I do see 'Digispark Bootloader' in my device manager for a couple of seconds in my device manager.
I tried different cables. I tried to install the drivers on another computer and the same thing happens.
What should I try next? Am I missing other drivers?


texts: How to connect 10 coin vibration motors to UNO?

texts: I am new to arduino and anything related to electricals and electronics. I need info on how to connect 10 vibration motors to arduino uno without damaging the board. Do I need an external circuit to regulate and control power supply or can I directly plug in all 10 motors to the board directly?


texts:
I have this simple function that produces 2 float values sum and product from which i calculate another varaible NodePrio.
I had the value of NodePrio coming wrong so i decided to put in some console debug messages to read these values as they were being modified in the loop
Here is the code

void cycPrioCalc(){
float sum = 0.0, product = 1.0;
for (int i = 0; i< 4; i++){
    if (loads[i].state == LOW){
        if (loads[i].dynPrio > 1.0){
            loads[i].dynPrio -= Pstep;
        }
        if (loads[i].dynPrio < 1.0){    // stop overshoot
            loads[i].dynPrio = 1.0;
        }
    }

    else if (loads[i].state == HIGH){
        if (loads[i].dynPrio < loads[i].fixPrio){
            loads[i].dynPrio += Pstep;
        }
        if (loads[i].dynPrio > loads[i].fixPrio){    // stop overshoot
            loads[i].dynPrio = loads[i].fixPrio;
        }
    }
    // CAlculate the priority of the node
    sum += loads[i].dynPrio;
    Serial.print(sum);
    Serial.print("\n");
    product *= loads[i].dynPrio;
    Serial.print(product);
    Serial.print("\n");
}
NodePrio = product / sum;
}

The values for loads[i].dynPrio goes 1.0, 2.0,3.0 and 4.0 for the 4 elements of the loop.
so according to this logic at the end of the loop
sum should be 1.0+2.0+3.0+4.0 = 10.0
and
product should be 1.0 * 2.0 * 3.0 * 4.0 = 24.0

and NodePrio should be __ 24.0 / 10.0 = 2.40 __

strangely, what i receive in serial output are the last values that were computed,

** sum = 4.0**
and
** product = 1.0 **
thus setting
**NodePrio = 0.25 **

here is the serial output

1.00    -> Sum at  i=0
1.00    -> Product at  i=0
2.00    -> Sum at  i=1
1.00    -> Product at  i=0
3.00    -> Sum at  i=2
1.00    -> Product at  i=0
4.00    -> Sum at  i=3
1.00    -> Product at  i=0
0.25    -> NodePrio

First place to look was the braces, which look fine to me.
All help is apprecieated.


texts: how to send data to 15 meters with KY-005

texts:
I am using the LED KY-005 as emitter and the KY-022 as a receiver, according to their specifications they reach 18 meters.
I have performed the tests and it supports more than ten meters, however after the 6 meters the data is not received correctly. For example, I send 0xa90 but any other value except the desired one arrives at the receiver.
Here I leave the connection diagram:

This is the code that I use to send data:

#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     delay(40);
   }
}


texts: Arduino Zero AnalogReadFast Compiling Error

texts:
#include <Streaming.h>
#include <StopWatch.h>
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"

const byte adcPin = A1;

void setup(void)
{ Serial.begin(9600);
  while(!Serial);
  Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
  for(int i=0; i<10; i++) testAnalogRead();
}

void testAnalogRead()
{ static Stopwatch stopwatch(micros);
  //delay(1000);

  stopwatch.start();
  int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
  stopwatch.stop(); int t1 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc2 = analogRead(adcPin); // 425us on SAMD21
  stopwatch.stop(); int t2 = stopwatch.interval;

  analogReadResolution(10);
  stopwatch.start();
  int adc3 = analogReadFast(adcPin); // 23us on SAMD21
  stopwatch.stop(); int t3 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc4 = analogReadFast(adcPin); // 24us on SAMD21
  stopwatch.stop(); int t4 = stopwatch.interval;

  Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
  analogReadResolution(10); // restore default
}

void loop(void)
{
}

When I try to compile this code in the Arduino Zero, it throws out the following errors:

/Users/RAJU/Documents/Arduino/libraries/avdweb_AnalogReadFast/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino:1:23: fatal error: Streaming.h: No such file or directory
 #include <Streaming.h>
                       ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Zero (Programming Port).

Can anyone help to resolve this error?


texts:
I'm making a JSON lib dedicated for my own needs, based on ArduinoJSON v6.

I try to define StaticJsonDocument<_docSize> doc in a parametric way but I get this error and I cant find the reason for it:

/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp: In constructor 'myJSON::myJSON(char*, int, bool)':
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:28: sorry, unimplemented: use of the value of the object being constructed in a constant expression
         StaticJsonDocument<_docSize> doc;
                            ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: error: 'this' is not a constant expression
         StaticJsonDocument<_docSize> doc;
                                    ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: note: in template argument for type 'unsigned int'
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:41: error: invalid type in declaration before ';' token
         StaticJsonDocument<_docSize> doc;
                                         ^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

I paste only relevant part of the code

myJSON.h :

#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
int _docSize=100;
bool useSerial;
char _filename[30];

public:
myJSON(char *filename, int docsize, bool useserial=false);
bool file_exists();//char *file=_filename);
bool file_remove();
bool format ();

};
#endif

myJSON.cpp:

#include "Arduino.h"
#include "myJSON.h"
#include "FS.h"
#include <ArduinoJson.h>

myJSON::myJSON(char *filename, int docsize, bool useserial) {

        _docSize = docsize;
        useSerial = useserial;

        StaticJsonDocument<_docSize> doc;

        if (useSerial) {
                Serial.begin(9600);
        }
        if (!SPIFFS.begin()) {
                if (useSerial) {
                        Serial.println("Failed to mount file system");
                }
        }
        else{
                sprintf(_filename,"%s",filename);
        }
}


texts: How to receive data via Bluetooth on an Arduino 101?

texts:
The Arduino 101 came out recently, and it has built-in "Bluetooth Low Energy" capabilities. The tutorials and code examples that can be found for the 101 all seem to be about transmitting data, but I can't find anything about receiving data. I've tried to go through the source code of the CurieBle library to find some hints, but I feel a little overwhelmed/lost. Could someone point me to a code example which demonstrates how to do this?

Context: I was previously using an HC-05 module paired with an Arduino Nano in order to receive data. In this case it is quite easy to connect the HC-05 to the Nano's digital pins and receive data like so:

#define RxD 7 // This is the pin that the Bluetooth (BT_TX)
              // will transmit to the Arduino (RxD)
#define TxD 8 // This is the pin that the Bluetooth (BT_RX)
              // will receive from the Arduino (TxD)

SoftwareSerial blueToothSerial(RxD,TxD);

void setup() {
  blueToothSerial.begin(9600);
  Serial.begin(9600);
  // Allow Serial communication via USB cable to computer
  pinMode(RxD, INPUT);
  // Set up the Arduino to receive INPUT from the HC-05 on Digital Pin 7
  pinMode(TxD, OUTPUT);
  // Set up the Arduino to send OUTPUT to the HC-05 on Digital Pin 8
}

void loop() {
  char recvChar;
  while(1) {
    if(blueToothSerial.available()) {
      recvChar = blueToothSerial.read();
      Serial.print("Read character: ");
      Serial.println(recvChar);
      // Print the character received to the Serial Monitor
    }
  }
}

Is there equivalent, and equally simple, code available, which would do the same thing via the BLE built into the Arduino 101?


texts: Arduino Mega with SIM800L running Modbus TCP/IP

texts:
I'm trying to set up an Arduino Mega with a SIM800L module and trying to get Modbus TCP running on said Mega. I've set Modbus TCP over wifi and serial before but I used libraries for those. The problem is, I can't find a suitable library for SIM800L that has Modbus support in it. The project is supposed to get Modbus TCP to places without wifi, using a static IP enabled sim card. My question here is, am I missing something? While working with ESP8266 and Serial, I was able to find a ton of libraries to work with, but SIM800 series returns nothing for me.
Thanks!


texts: What would be the architecturally-right place to put custom -D defines?

texts:
What I am trying to accomplish is to include information about the state of my environment at build time in my code. For example, I may want the setup() code to print the git sha it was built against, and the time of build.

There are two related issues here:

How to include that information in the code
How to specify to the build environment what to generate in the first place.

The first can be addressed in a number of ways:

-D options can be generated at build time, and the corresponding defined macros expanded in the code. For example, the compiler could be invoked as g++ -DGIT_SHA=$(git rev-parse HEAD) -DDATE=$(date '+%Y%m%d-%H:%M:%S'), and my code could have something like #define strfy(_x) #_x followed by Serial.println(strfy(GIT_SHA));. Or the build tool could generate a header file that would define these as external string variables, which the main sketch could then include and print. Or any other number of tricks.

The question I am really asking is: how should I specify this sort of stuff for arduino-builder?

Ideally, it would be a custom recipe in platform.txt, but if there is a way to invoke shell commands in recipes and use the results to modify other variables (such as preproc.macro.flags), I haven't been able to find it (if there is documentation, it's really well hidden). Ideally I would want to be able to say preproc.macros.flags=-w -x c++ -E -CC -DGIT_SHA=$(git rev-parse HEAD) and have the shell command be executed at the point.

So, before I set out to hack arduino-builder, do people have any opinion on this? My main criterion is something that would be of general value and has a chance of being incorporated in the code, rather than a kludge that only works for me and which I have to patch every time I upgrade. Please do not suggest workarounds. I can think of several myself!

I did try to search, and this sort of issue has come up before, but I didn't see any satisfactory answers from people who knew what they were talking about.

Thanks!

/ji


texts:
I have this code:

void setup() {
  pinMode(11, OUTPUT);
  TCCR2B = 0;
  TCNT2 = 0;
  TCCR2A = _BV(WGM21);
  TCCR2A |= _BV(COM2A0);
  OCR2A = 249;
}

void loop() {
  soundBuzzer();
}

void soundBuzzer() {
  TCCR2B |= _BV(CS21);
}

void silenceBuzzer() {
  TCCR2B &= ~_BV(CS21);
  TCNT2 = 0;
}

(Got it from here).

And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.
Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?


texts: I just had a pretty simple question about the RTC Clock Modules, more specifically the DS3231 RTC. Once calibrated and running on my Arduino if I were to unplug it and plug it back in, will the time and everything reset and require another calibration, or will it work like a computer that, even when reset, retains the correct time and date. Thanks!


texts: I want to use the Ino command line toolkit to build and upload my HEXes. It works well for the regular Arduino, however when I try to upload code to a Mini Pro 3.3V at 8 MHz, the code has the timing wrong. The serial output is garbled (I tried at different baud rates and was garbled each time) and delay(1000); seems to take double the time. I have selected the correct board (pro328 in my boards.txt), but it didn't seem to make a difference in the generated code. Has anyone used this and encountered a similar problem?


texts:
I'm trying to use a MOSFET (BS250P datasheet) to switch a circuit on and off while the MCU is asleep. It's a P-channel MOSFET that closes the circuit when the gate is pulled low. The most power hungry module in my circuit is a HC-05 bluetooth module. The specs on the website I bought it at rates it at 3.3V - 6V and a max current draw of 50mA when pairing and around 9mA when connected. Hooking it up to an Arduino 3.3V source confirms that it works at that voltage and pairs it up with another identical module just fine.

Now when I put that same 3.3V source through the MOSFET with a 10k pull up resistor and connects the HC-05 to the drain, the module does not power up. I measured the voltage on the drain and when nothing is connected it's the same as the source. After connecting the HC-05 it's about 2.4V (maybe this is a clue). Even if I run the power through a step up converter to 4.10V it does not power up through the MOSFET. If I increase the voltage to 5V it all works fine. I would ideally run the circuit at 3.6V in order to preserve current for the rest of the modules, and not having to use a voltage regulator for the RX of the HC-05.

I assume the issue is with the MOSFET properties, but as far as I can read from the datasheet it can sustain 230mA current. It has a VGS(th) of 3.6V, but since I'm always pulling the MOSFET low in this scenario that shouldn't be an issue? Measuring the resistance when the gate is pulled low indeed gives just a few ohms as the datasheet suggests.

So basically, what am I missing here? :-) Thank you for any help with this!


texts:
Please help me about this program uploading problem.
 Arduino: 1.6.13 (Windows 10), Board: "Arduino Nano, ATmega328P"

Sketch uses 930 bytes (3%) of program storage space. Maximum is 30,720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "\.\COM1": The system cannot find the file specified.

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

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


texts:
I've been working on a project (Arduino Uno: Atmega328) that implements a gyroscope (which is used with the LSM9DS0 spark-fun library) that is communicated with through I2C and uses a Servo library. Due to a timer conflict with the standard Servo library and another library I've been using, I am now using the ServoTimer2 library which obviously uses timer 2. This is when the problem started.

When I call the attach() function of the ServoTimer2 library, it allows the gyroscope to be read a few times and then the gyroscope feed cuts out. I am using the serial monitor (115200 baud) to read the gyroscope data. The Serial monitor is not the problem because it uses a UART interrupt for Serial.

To fix this error, I modified the ServoTimer2 library to run on Timer0 (Yes I know this handles the delay functions, but they are not needed in my case), which is now called ServoTimer0. This modified version of the library works perfect except for when I attempt to use it with the gyroscope. The same problem still arises though. I've traced what causes this failure down to one line of code that sets up the interrupts:

TIMSK0 =  _BV(OCIE0A) //This is in my own modified version of the library.

That is what causes it to fail. I believe the AtMega328 can run I2C natively, and my thought is that this native running somehow uses these timers.

Any solutions?
Thanks


texts: It seems like the math of arduino is off

texts:
[SOLVED] By changing the offset for the incoming data into int16_t type there won't be any rounding errors and the values I'm getting are all back to zero in the sensor its base position

This is my first project where I use Arduino.

Until today everything went good with the Arduino Pro Mini (3.3v).
But as of today I got a bit of a weird problem.
I am using a MPU gy-521 (doesn't really matter) and I'm working on calculating the actual movement.

The problem which occured is that I'm using a deadzone to negate the smallest numbers (I know, this isn't the right way to use data). The way I negate the numbers is with the following code

// Check deadzone values
  if (ax+axo < adz && ax+axo > -adz) ax = -axo;
  if (ay+ayo < adz && ay+ayo > -adz) ay = -ayo;
  if (az+azo < adz && az+azo > -adz) az = -azo;

  if (gx+gxo < gdz && gx+gxo > -gdz) gx = -gxo;
  if (gy+gyo < gdz && gy+gyo > -gdz) gy = -gyo;
  if (gz+gzo < gdz && gz+gzo > -gdz) gz = -gzo;

ax is accelerometer data over the x-axis, axo is the offset, adz is the accelerometer deadzone.

gx is gyroscope data over the x-axis, gxo is the offset, gdz is the gyroscope deadzone.

All of the other letters are the same, for different axis.
After getting the values within the offset basically set to 0 with the offset I'm doing the following.

// Calculate acceleration
  axa = (ax+axo) / aFactor * g;
  aya = (ay+ayo) / aFactor * g;
  aza = (az+azo) / aFactor * g;

  gxa = (gx+gxo) / gFactor;
  gya = (gy+gyo) / gFactor;
  gza = (gz+gzo) / gFactor;

The a- and gFactor are mentioned in the datasheet, but these values should all be 0 if the value of axis plus the offset is within the deadzone.
The problem is that I'm not just getting 0.00 values.
I'm also getting -0.00 and 0.01.

0.00    0.00    -0.00   0.00    0.01    0.01

Could someone enlighten me about what's wrong in my situation or if this is just a Arduino issue.

[EDIT]

The data originally from the sensor is from type int16_t (ax, ay, az, gx, gy, gz) and the other variables are doubles.

The values which are off are always the same ones: Accelerometer Z, Gyroscope Y and Z.


texts: How to continuously monitor range finder and immediately interrupt code to run a different code in pedestrian traffic lights setup?

texts:
I am currently doing part 2: Pedestrian Mode of my project below:

Regular Mode: This is the regular mode of operation. In this mode the
three lights (Red, Yellow and Green LEDs) should operate in the following
order. The Red LED lights for 2 seconds, followed by the Yellow LED for 1
second, the Green LED for 2 seconds and then the Yellow LED again for 1
second. The cycle should repeat until the mode changes.
Pedestrian Mode: This mode uses the SRF05 Ultrasonic Range Finder to
detect the proximity of any object. The lights should operate as defined in
the regular mode UNTIL an object is detected less than 10 cm from the
TLC. The buzzer should then beep and the Yellow LED must blink ON/OFF
(flashing intervals of 0.1 sec) repeatedly 10 times. The buzzer should then
stop beeping and the operation of the lights (not the system) must behave
as it would in the regular mode. The operation stays the same until the
mode changes

My code works, however it waits for the entire regular cycle to finish before sensing a pulse with the ultrasonic range sensor to determine if an object is near or not. Therefore, when I put my hand near the sensor, it has to finish running the regular mode before it detects my hand and switches to pedestrian mode. What I would like is for the range finder to continuously fire the pulse and immediately switch to pedestrian mode when it detects an object less than 10 cm away.

Code below:

int red_light = 12;
int yellow_light = 10;
int green_light = 8;
int ECHOPIN = 3;
int TRIGPIN = 5;
int buzzer = 7;
float distance;

void setup() {
  Serial.begin(9600);
  pinMode(red_light, OUTPUT);
  pinMode(yellow_light, OUTPUT);
  pinMode(green_light, OUTPUT);
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  range_finder();
  if (distance < 10) {
    pedestrian_mode();
  } else {
    regular_mode();
  }
}

void regular_mode() {
  digitalWrite(red_light, HIGH);
  delay(2000);
  digitalWrite(red_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
  digitalWrite(green_light, HIGH);
  delay(2000);
  digitalWrite(green_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
}

void range_finder() {
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN,LOW);
  distance = pulseIn(ECHOPIN, HIGH);
  // return 0 if no high pulse in 1 sec
  distance = distance/58;
  Serial.print(distance);
  Serial.println("cm");
  delay(200);
}

void pedestrian_mode() {
  digitalWrite(buzzer, HIGH);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
}

Also I have a feeling some parts of my code may be unnecessarily long and could be shortened. If so, I would appreciate any advice and how to do that. Thank you.


texts:
I am carrying out a physics experiment using an Arduino. This experiment requires accurate time measurements of upto a millisecond. However I am using a relay to turn on/off an electromagnet and there is a maximum lag of 10ms due to the relay. I am a complete beginner. Please suggest alternative mechanisms to switch the electromagnet and save those precious milliseconds.
P.S. - the magnet is driven by 12V 2.5A DC.


texts: Why doesn't data return when I use Sim808 http request

texts:
Why is it that when i use this code for http request on DFRobot_sim808 , I get 'fetch over' message, that means that no data is being returned?

char strings:

char http_cmd[] = " HTTP/1.0\r\n"
                        "Host: 5ac80719.ngrok.io\r\n"
                        "\r\n";
char first[] = "GET /index.php?lat=";

char requestion[100];

functions to join them:

void setup() {
  float lat = 32.685362, lon = 48.411512;
  char char_coor[10];

  mySerial.begin(9600);
  Serial.begin(9600);

// Set Http Cmd
  strcpy(requestion,first);
// For Convert latitude float to char
  dtostrf(lat, 4, 6, char_coor);
  strcat(requestion,char_coor);
// For Convert longitude float to char
  dtostrf(lon, 4, 6, char_coor);
  strcat(requestion,"&long=");
  strcat(requestion,char_coor);
  strcat(requestion,http_cmd);

.
.
.

and fetching:

sim808.send(requestion, strlen(requestion)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }

/*
The program stops at above
*/

      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

thanks


texts: Potentiometer on motor for position control

texts:
I am using a wiper motor as a rotor. I am trying to get it to at least point in different azimuths (compass azimuths eg. 180 degrees) In order to do this, I am thinking about attaching a potentiometer on the axle inside the motor housing to see where the motor is pointing.

So lets say the pot gives me a range of 0-1023. If I divide 1023 by 360 i get 2.84. So lets say the pot gives the Arduino a 1, I can relate that to 2.84 degrees?

Also, what if the motor is pointing at 350 degrees, and I want it to point at 2 degrees. Instead of it turning around 348 degrees, it just cross pass 360 and go to 2 degrees.  How would a pot handle going over a single step? If the motor passed a single step would it consistently give me a 1023 reading?

I am trying to get a wiper motor to have a known position 360 degrees around.


texts:
I wander what is the best option for formatting strings in Arduino for output.
I mean what's a preferable way in the point of view of performance, memory usage  – things like that.
I see, people usually use direct Serial.print/println, like this:

  int x = 5;
  // 1st option
  Serial.print("x = ");
  Serial.println(x);

Or like this:

  // 2nd option
  Serial.println("x = " + String(x));

But what is wrong with, I believe, more traditional way of doing this:

  // 3rd optoin
  char strBuf[50];
  sprintf(strBuf, "x = %d", x);
  Serial.println(strBuf);

  // better one?


texts:
As you know, the Arduino IDE resets the Arduino when the Serial Monitor is opened. I want also my program to do it. But I don't know how.

I examined the source code of the Arduino IDE (Serial.java & SerialMonitor.java), but I can't find where it sends the reset command. Where is it?

I use C# to communicate with serial.


texts: Send JSON via POST on SIM900 shield with AT commands

texts:
I'm trying to send a JSON POST in SIM900 shield with AT commands. After I call the  AT+HTTPACTION=1 command, it returns a 601 error: +HTTPACTION:1,601,0.

I saw here that the error was 601 Network Error. Could someone help me? Following is my code.

void connectInternet() {
  if(digitalRead(9 != LOW)) {
    Serial.print("\r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print(" CONNECT ON INTERNET \r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print("\r\n");
    Serial.println("Connecting...\r");
    cmdAT("AT");
    cmdAT("AT+CIPSHUT");
    cmdAT("AT+CIPMUX=1");
    cmdAT("AT+CSTT=\"zap.vivo.com.br\",\"vivo\",\"vivo\"");
    cmdAT("AT+CIICR");
    cmdAT("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
    Serial.print("IP Device: ");
    cmdAT("AT+CIFSR");
  }
}

void send2Api() {
  Serial.print("\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print(" SEND TO API\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print("\r\n");
  cmdAT("AT+CSQ");
  cmdAT("AT+CGATT?");
  cmdAT("AT+SAPBR=2,1");
  // Query if the connection is setup properly, if we get back a IP address then we can proceed
  cmdAT("AT+HTTPPARA=\"CID\",1");
  // Set the HTTP session.
  cmdAT("AT+HTTPPARA=\"URL\",\"http://api.com.br/endpoint\"");
  // set endPoint
  cmdAT("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  // set content json
  cmdAT("AT+HTTPDATA=100,5000");
  // POST session start
  // JSON payload
  cmdAT("{\"timestamp\":\"2016-03-08T19:36:45.000Z\",\"latitude\":\"-24.9458581\",\"longitude\":\"-53.4968357\"}");
  delay(100);
  cmdAT("AT+HTTPACTION=1");
  // POST session start
  cmdAT("AT+HTTPREAD");
  // Read the data of HTTP server
  cmdAT("AT+HTTPTERM");
  // terminate http
  ShowSerialData();


texts: delete or free on object causes Arduino to hand or reboot

texts:
I've read a lot about dynamic allocation for strings or buffers, but that's not my case.

I plan to implement much blinkers types as classes, all inheriting from a base Action class.

I declare an array of 10 pointers because I want to limit to 10 blinkers simultaneously at most :

Action** actions = new Action*[10];

In the code, I will do something like :

int i = GetFreeActionID();
actions[i] = new ActionLightBlinkerMono(myPin, onDuration, offDuration);

Then the loop will call a method of the object and it works fine.

When it comes to stop the blinking, I would just destroy the object and set the pointer to zero, so the loop will not try to call the method of the object anymore :

if (actions[i]->Do() != 0)
{
  delete(actions[i]);
  actions[i] == 0;
}

Howerver, I see in the serial console that when it comes to the delete instruction, the Arduino just reboots itself ...

Tryed also free instead of delete with same result.

How could I safely free the object when it's not used anymore ?

It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes.


texts: Making tmrpcm.play("1.wav") depend on LDR feedback?

texts:
I have the speaker working with the tmrpcm.play working, but this only plays when the arduino is powered up or reset. Can i make the .wav play in anther other ways?
I wan't the file to play when i open a closet and my LDR resistor is affected by light.
#include <SD.h>                           //include SD module library
#include <TMRpcm.h>                       //include speaker control library

#define SD_ChipSelectPin 4                //define CS pin

TMRpcm tmrpcm;                            //crete an object for speaker library

const int ledPin = 8;
const int buzzerPin = 10;
const int ldrPin = A0;
int ledState = LOW;
int buzstate = 600;
unsigned long previousMillis = 0;

int ldrStatus = analogRead(ldrPin);  //read the state of the LDR value

const long interval = 400;

void setup () {

  tmrpcm.speakerPin = 9;
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(ldrPin, INPUT);

 }
void LedAndBuzzer(){
   unsigned long currentMillis = millis();
  int ldrStatus = analogRead(ldrPin);  //read the state of the LDR value

 if (ldrStatus >= 400) {

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
    digitalWrite(buzzerPin, ledState);
}}
}
void soundon(){
    if (!SD.begin(SD_ChipSelectPin)) {      //see if the card is present and can be initialized

    return;                               //don't do anything more if not
  }
  else {
  tmrpcm.setVolume(6);                    //0 to 7. Set volume level
  tmrpcm.play("4.wav"); }
}

void loop() {

  }


texts: Interfacing Arduino UNO with TFT LCD and WiFi Shield

texts:
I'm trying to interface my Arduino UNO with both a 1) TFT LCD screen and 2) WiFi Breakout board/shield.
The WiFi breakout board uses many of the same Digital pins as the LCD screen so is it possible for the arduino to interface with both devices simultaneously?

I also noticed that the shield goes over the arduino, but covers the header pins. Does this mean that I can't use these pins?

I've never worked with shields or breakout boards and would like some advice before I purchase either component.
If neither of these solutions will work, please provide me with alternate methods.

Your time/feedback is greatly appreciated :)

-Vip


texts: RadioHead library nrf24 sending and receiving struct data problem

texts:
I am using RadioHead library for the communication between nrf24l01.
I am sharing the snippet of my code below because the code is too huge.
The problem i am facing here is on the receiver side i am not be able see the data i am sending , it is showing squares and not the proper characters.
my output showing to me is :

name :?!

skill :

Sender Code :

struct DataHolder {
  String name;
  String skill;
};

DataHolder dh;

RH_NRF24 nrf24(10, 9);

//THIS METHOD I AM USING TO SEND DATA FROM SENDER NRF
void sendtonrf(){

 dh.name = "xyz";
 dh.skill = "classA";

 nrf24.send((uint8_t *)&dh, sizeof(dh));

}

receiver code:

struct DataHolder {
String name;
String skill;
};

 DataHolder dh;

 void loop{

 if (nrf24.available()) {

  uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);

    if (nrf24.recv(buf, &len)) {

    String str1 = (((DataHolder*)buf))->name;
    String str2 = ((DataHolder*)buf)->skill;
    Serial.println("name :" + str1);
    Serial.println("skill :" + str2);

    }
 }
}


texts: Sending multiple byte data from Arduino as Slave on SPI

texts:
I have been working around the teardown of an induction cooktop and thought of having a tweak in the system. So far, I have deduced following circuitry out of the cooktop-
There are two devices communicating with each other in 3-wire SPI mode. The master, which controls power management and Induction circuitry, continuously sends commands and data to the slave. The slave, which is TM1628, receives the master commands and data, then accordingly displays the data on the seven segment or responds with the switch pressed, if any.

The above picture explains it better. Now, I thought of replacing TM1628 with an Arduino. So far so good. I gathered all the data that was being sent by the master and the reply sent by the slave.

But, when I started to code, I got stuck in one place. So the data as sent by the master and its response looks like this -

(Master to Slave)**Command1 - Command2 - Data1 - Data2 - ... - Data 14 - Command1 - Command2 - **(Slave to master)**Data1 - Data2 - ... - Data5 - **(And now the repetition)

When the master is sending the data, I have no issues as the data will continuously be read by Arduino and I can take the action accordingly.
But when the Arduino (Working as a slave) needs to send continuously 5 streams of data, depending only on the clock input timing from the master, how could I know that one stream has been written and now the next data has to be written to the SPDR register.


texts: Can't connect to Arduino Uno + Wifi webpage

texts:
I am using this board:

Arduino Uno Wifi

In the manual it says I should connect to its wifi which I did and it says unidentified network. When I go to 192.168.240.1 nothing shows up. How do I find out which ip address I should use? I tried ipconfig /all but it doesn't show anything for the wifi connection.

EDIT:

When I try to flash my ESP8266 with the ESP8266 Download tool it gives me this error:

test offset :  0 0x0
case ok
test offset :  0 0x0
case ok
test offset :  2080768 0x1fc000
case ok
test offset :  2088960 0x1fe000
case ok
test offset :  4096 0x1000
case ok
======
CONNECT BAUD: 115200
============
....._____....._____....._____....._____....._____....._____.....
_____....._____....._____....._____
[2017-11-22 12:00:42,029][ESP8266Loader_spi[1]]
[espDownloader.pyo][line:349][ERROR]: Chip sync error: Failed to connect to
ESP8266: Timed out waiting for packet header
[2017-11-22 12:00:42,029][ESP8266Loader_spi[1]][espDownloader.pyo][line:437]
[ERROR]: ESP8266 Chip sync error esp_sync_blocking.

Picture of my board and current dip switch settings:


texts: How to interface to LPG consumption meter

texts:
I have sourced an LPG consumption meter from China with pulse output. I am looking to hook the output up to an arduino to get the consumption metrics. Unfortunately there is not too much documentation available on the unit that I can find. The suppliers inform me that:

Black wire(signal 1)
Black wire(signal 2)
Red wire(earth wire)

So that's a start, I know the unit pulses a signal for every cubic meter of gas consumed.
What I'm wanting to know is:

What are the input [likely] voltages for the unit (or how could I establish this)?
How do I wire the unit to an arduino?
I can cook up a sketch to do the reading but what is the signal I am looking for?

The mechanical meter itself has a metallic strip on the 0 digit of the wheel (how it achieves the pulsing itself no doubt) so another approach would be something like this http://phk.freebsd.dk/Gasdims/ which is a more accurate option. For this option any suggestions on what photoreflectors are available for the Arduino which could do the job.


texts:
I am building a robot that is both obstacle-avoiding and remote-controlled. The robot uses an infrared remote.  When the front button is pressed the robot moves front, when the right button is pressed the robot turns right, and so on...
When a certain button is pressed the robot switches to obstacle-avoiding mode and starts to drive around. When the ultrasonic sensor detects an object 15cm away the robot turns right, reverses, and then continues moving forward. the obstacle-avoiding code has a problem, though. Here is the code:

#include <EEPROM.h>
#include <IRLib.h>
#include <AFMotor.h>
int frontlights = A1;
int backlights = A2;
int buzzer = A3;
int pingPin = A4; //setup pingpin as A4

//ir variables
int RECV_PIN = A0;
IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
unsigned int Buffer[RAWBUF];

void obstacle_avoiding(){
   while (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){  // when the automatic mode button is pressed and the stop button is not pressed do...

 motor4.setSpeed(230);
 motor3.setSpeed(230);
 motor2.setSpeed(230);
 motor1.setSpeed(230);

    long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(90);

      if(cm>15){          // if an object is greater than 10cm move forward
      motor_forward();
      Serial.println("forward");
      digitalWrite(backlights, LOW);

      }

     else if (cm<=15)     // if an object is less than or equal 10cm move backward then turn right
     {
      motor_stop();
      digitalWrite(frontlights, HIGH);
      digitalWrite(backlights, HIGH);
      digitalWrite(buzzer, HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      delay(2000);
      motor_backward();
      digitalWrite(backlights, HIGH);
      Serial.println("backward");
      delay(500);
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(900);
      motor_right();
      digitalWrite(backlights, LOW);
      Serial.println("right");
      digitalWrite(frontlights, LOW);
      delay(400);

   }
   if (My_Decoder.value==0xFF0AF5){   //the stop button is pressed break the "while" loop and stop the robot
   break;
   motor_stop();
   }
 }
}

void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();

    //automatic code here
            else if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

The code is working however when the "while" statement becomes true it will loop infinitely not stopping even when the condition has become false. I thought while statements should loop until the condition becomes false. Am I misinformed?


texts: ESP-01 adapter and logic level converter

texts:
I read that I'll need a logic level converter like this to run an ESP8266-01 from the Uno.

But I saw this ESP adapter:

http://www.ebay.com/itm/ESP-01-ESP8266-Serial-Wi-Fi-Wireless-Adapter-Module-3-3V-5V-Compatible-Arduino-/282524471281?hash=item41c7c54ff1:g:wp0AAOSwQ59ZaClP

Two questions:

The ESP-01 has 8 connections but this has only 4, how come? Will I get the same functionality?
If I'll use this adapter, then I won't need the logic level converter?


texts:
I'm creating a binary calculator with my Arduino. This will take two different binary numbers and add them together. I am focusing right now on the Byte One Input screen. For this, I can use two buttons, the left to change to selected bit to either 0 or 1 when pressed, and the right button to move to the next bit, or when at the end, to move to the next screen. I am having difficulty with the debouncing of the buttons.

Right now, the debouncing is not working and the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button.

Any help would be great!

Fixed Code: See accepted answer below.

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

int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;

const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;

unsigned long debounceDelay = 50;

//****************************************************************setup*****************************************
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  Serial.begin(9600);
  analogWrite(6,con);
  mylcd.begin();
  lcd.print("Welcome");
}

//************************************************************loop************************************************

void loop() {

  int reading1 = digitalRead(button1Pin);
  int reading2 = digitalRead(button2Pin);

  if (reading1 == lastButton1State &&
      reading2 == lastButton2State)
    return;  // do nothing if no change

  delay (debounceDelay);  // debounce

  // re-read so we can catch both buttons down at once
  reading1 = digitalRead(button1Pin);
  reading2 = digitalRead(button2Pin);

  // save for next time
  lastButton1State = reading1;
  lastButton2State = reading2;

  if (reading1 == LOW && reading2 == HIGH)     // first one down
    btn_push = 'D';
  else if (reading1 == HIGH && reading2 == LOW)  // second one down
    btn_push = 'U';
  else if (reading1 == LOW && reading2 == LOW)  // both
    btn_push = 'S';
  else
    return;  // nothing interesting

 Serial.print("btn_push = ");
 Serial.println(btn_push);

    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    }

}

// The rest is the same, excluding the functions that are no longer needed


texts: Digital Input using a button doesn't work properly when using it to control a relay

texts:
I'm trying to control a relay both via Bluetooth and using a switch. The problem is that, when the LED is off, I can turn it on with the switch but then if I turn off the switch the relay will stay on. Is there something wrong with my code? Thanks in advance. The switch is installed as follows:

Here is my code: Switch is connected to pin 3 and the relay is connected to pin 2.

//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 0; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 if (state == '0'&& valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 else
 if (state == '1' || valor== HIGH) {
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
 }

}

New code:

//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 1; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);
 //si el modulo ha mandado dato, guardarlo en estado.

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 // si el estado es 0 ese sería Apagado “OFF”
 if (valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 // de lo contrario si el estado es 1 ese sería Encendido “ON”
 else
 if (valor== HIGH) {
     if (state== 1){
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
     }
     else if (state== 0){
     digitalWrite(ledPin, LOW);
     Serial1.println("LED: off");

     }
 }

}


texts: Running both sensor and addressable LED strips at a same time?

texts:
I'm trying to obtain the sensors' readings as well as making the LED strips to light up at this particular pattern, if the sensor readings reaches certain values. But since both of these codes are inside the void loop(), there will be a problem. How can I do this correctly?

void loop()
{
    currentSensorReading = analogRead(sensorPin);
    Serial.println(currentSensorReading );

    if(currentSensorReading is in range of certain values){
        rainbowCycle(20);
    } else { turn LEDs off }
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}